text:
/*
 * Copyright 2021 CloudWeGo Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Package discovery defines interfaces for service discovery.
// Developers that are willing to customize service discovery
// should implement their own Resolver and supply it with the
// option WithResolver at client's creation.
package discovery

import (
	"context"
	"net"

	"github.com/cloudwego/kitex/pkg/rpcinfo"
	"github.com/cloudwego/kitex/pkg/utils"
)

// DefaultWeight is the default weight for an instance.
const DefaultWeight = 10

// Result contains the result of service discovery process.
// Cacheable tells whether the instance list can/should be cached.
// When Cacheable is true, CacheKey can be used to map the instance list in cache.
type Result struct {
	Cacheable bool
	CacheKey  string
	Instances []Instance
}

// Change contains the difference between the current discovery result and the previous one.
// It is designed for providing detail information when dispatching an event for service
// discovery result change.
// Since the loadbalancer may rely on caching the result of resolver to improve performance,
// the resolver implementation should dispatch an event when result changes.
type Change struct {
	Result  Result
	Added   []Instance
	Updated []Instance
	Removed []Instance
}

// Resolver resolves the target endpoint into a list of Instance.
type Resolver interface {
	// Target should return a description for the given target that is suitable for being a key for cache.
	Target(ctx context.Context, target rpcinfo.EndpointInfo) (description string)

	// Resolve returns a list of instances for the given description of a target.
	Resolve(ctx context.Context, desc string) (Result, error)

	// Diff computes the difference between two results.
	// When `next` is cacheable, the Change should be cacheable, too. And the `Result` field's CacheKey in
	// the return value should be set with the given cacheKey.
	Diff(cacheKey string, prev, next Result) (Change, bool)

	// Name returns the name of the resolver.
	Name() string
}

// DefaultDiff provides a natural implementation for the Diff method of the Resolver interface.
func DefaultDiff(cacheKey string, prev, next Result) (Change, bool) {
	ch := Change{
		Result: Result{
			Cacheable: next.Cacheable,
			CacheKey:  cacheKey,
			Instances: next.Instances,
		},
	}

	prevMap := make(map[string]struct{}, len(prev.Instances))
	for _, ins := range prev.Instances {
		prevMap[ins.Address().String()] = struct{}{}
	}

	nextMap := make(map[string]struct{}, len(next.Instances))
	for _, ins := range next.Instances {
		addr := ins.Address().String()
		nextMap[addr] = struct{}{}
		if _, found := prevMap[addr]; !found {
			ch.Added = append(ch.Added, ins)
		}
	}

	for _, ins := range prev.Instances {
		if _, found := nextMap[ins.Address().String()]; !found {
			ch.Removed = append(ch.Removed, ins)
		}
	}
	return ch, len(ch.Added)+len(ch.Removed) != 0
}

type instance struct {
	addr   net.Addr
	weight int
	tags   map[string]string
}

func (i *instance) Address() net.Addr {
	return i.addr
}

func (i *instance) Weight() int {
	return i.weight
}

func (i *instance) Tag(key string) (value string, exist bool) {
	value, exist = i.tags[key]
	return
}

// NewInstance creates a Instance using the given network, address and tags
func NewInstance(network, address string, weight int, tags map[string]string) Instance {
	return &instance{
		addr:   utils.NewNetAddr(network, address),
		weight: weight,
		tags:   tags,
	}
}

// SynthesizedResolver synthesizes a Resolver using a resolve function.
type SynthesizedResolver struct {
	TargetFunc  func(ctx context.Context, target rpcinfo.EndpointInfo) string
	ResolveFunc func(ctx context.Context, key string) (Result, error)
	DiffFunc    func(key string, prev, next Result) (Change, bool)
	NameFunc    func() string
}

// Target implements the Resolver interface.
func (sr SynthesizedResolver) Target(ctx context.Context, target rpcinfo.EndpointInfo) string {
	if sr.TargetFunc == nil {
		return ""
	}
	return sr.TargetFunc(ctx, target)
}

// Resolve implements the Resolver interface.
func (sr SynthesizedResolver) Resolve(ctx context.Context, key string) (Result, error) {
	return sr.ResolveFunc(ctx, key)
}

// Diff implements the Resolver interface.
func (sr SynthesizedResolver) Diff(key string, prev, next Result) (Change, bool) {
	if sr.DiffFunc == nil {
		return DefaultDiff(key, prev, next)
	}
	return sr.DiffFunc(key, prev, next)
}

// Name implements the Resolver interface
func (sr SynthesizedResolver) Name() string {
	if sr.NameFunc == nil {
		return ""
	}
	return sr.NameFunc()
}

// Instance contains information of an instance from the target service.
type Instance interface {
	Address() net.Addr
	Weight() int
	Tag(key string) (value string, exist bool)
}

repository: golanglib/kitex

repo_name: golanglib/kitex

branch_name: refs/heads/develop


text:
/*
Copyright 2020 Cortex Labs, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package docker

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/cortexlabs/cortex/pkg/lib/aws"
	"github.com/cortexlabs/cortex/pkg/lib/errors"
	"github.com/cortexlabs/cortex/pkg/lib/exit"
	"github.com/cortexlabs/cortex/pkg/lib/parallel"
	dockertypes "github.com/docker/docker/api/types"
	dockerclient "github.com/docker/docker/client"
	"github.com/docker/docker/pkg/jsonmessage"
	"github.com/docker/docker/pkg/term"
)

var NoAuth string

var _cachedDockerClient *dockerclient.Client

func init() {
	NoAuth, _ = EncodeAuthConfig(dockertypes.AuthConfig{})
}

func createDockerClient() (*dockerclient.Client, error) {
	if _cachedDockerClient != nil {
		return _cachedDockerClient, nil
	}

	var err error
	_cachedDockerClient, err = dockerclient.NewClientWithOpts(dockerclient.FromEnv)
	if err != nil {
		return nil, WrapDockerError(err)
	}

	_cachedDockerClient.NegotiateAPIVersion(context.Background())
	return _cachedDockerClient, nil
}

func GetDockerClient() (*dockerclient.Client, error) {
	dockerClient, err := createDockerClient()
	if err != nil {
		return nil, err
	}

	if _, err := dockerClient.Info(context.Background()); err != nil {
		return nil, WrapDockerError(err)
	}

	return dockerClient, nil
}

func MustDockerClient() *dockerclient.Client {
	dockerClient, err := GetDockerClient()
	if err != nil {
		exit.Error(err)
	}

	return dockerClient
}

func AWSAuthConfig(awsClient *aws.Client) (string, error) {
	dockerClient, err := GetDockerClient()
	if err != nil {
		return "", err
	}

	ecrAuthConfig, err := awsClient.GetECRAuthConfig()
	if err != nil {
		return "", err
	}

	auth := dockertypes.AuthConfig{
		Username:      ecrAuthConfig.Username,
		Password:      ecrAuthConfig.AccessToken,
		ServerAddress: ecrAuthConfig.ProxyEndpoint,
	}

	_, err = dockerClient.RegistryLogin(context.Background(), auth)
	if err != nil {
		return "", err
	}

	authConfig, err := EncodeAuthConfig(auth)
	if err != nil {
		return "", err
	}

	return authConfig, nil
}

func WrapDockerError(err error) error {
	if dockerclient.IsErrConnectionFailed(err) {
		return ErrorConnectToDockerDaemon()
	}

	if strings.Contains(strings.ToLower(err.Error()), "permission denied") {
		return ErrorDockerPermissions(err)
	}

	return errors.WithStack(err)
}

func PullImage(managerImage, encodedAuthConfig string) error {
	docker, err := GetDockerClient()
	if err != nil {
		return err
	}

	images, err := docker.ImageList(context.Background(), dockertypes.ImageListOptions{})
	if err != nil {
		return WrapDockerError(err)
	}

	for _, image := range images {
		for _, tag := range image.RepoTags {
			if tag == managerImage {
				return nil
			}
		}
	}

	pullOutput, err := docker.ImagePull(context.Background(), managerImage, dockertypes.ImagePullOptions{
		RegistryAuth: encodedAuthConfig,
	})
	if err != nil {
		return WrapDockerError(err)
	}
	defer pullOutput.Close()

	termFd, isTerm := term.GetFdInfo(os.Stderr)
	jsonmessage.DisplayJSONMessagesStream(pullOutput, os.Stderr, termFd, isTerm, nil)
	fmt.Println()

	return nil
}

func StreamDockerLogs(containerID string, containerIDs ...string) error {
	containerIDs = append([]string{containerID}, containerIDs...)

	docker, err := GetDockerClient()
	if err != nil {
		return err
	}

	fns := make([]func() error, len(containerIDs))
	for i, containerID := range containerIDs {
		fns[i] = StreamDockerLogsFn(containerID, docker)
	}

	err = parallel.RunFirstErr(fns[0], fns[1:]...)

	if err != nil {
		return WrapDockerError(err)
	}

	return nil
}

func StreamDockerLogsFn(containerID string, docker *dockerclient.Client) func() error {
	return func() error {
		// Use ContainerLogs() so lines are only printed once they end in \n
		logsOutput, err := docker.ContainerLogs(context.Background(), containerID, dockertypes.ContainerLogsOptions{
			ShowStdout: true,
			ShowStderr: true,
			Follow:     true,
		})
		if err != nil {
			return WrapDockerError(err)
		}

		_, err = io.Copy(os.Stdout, logsOutput)
		if err != nil && err != io.EOF {
			return errors.WithStack(err)
		}

		return nil
	}
}

func EncodeAuthConfig(authConfig dockertypes.AuthConfig) (string, error) {
	encoded, err := json.Marshal(authConfig)
	if err != nil {
		return "", errors.Wrap(err, "failed to encode docker login credentials")
	}
	registryAuth := base64.URLEncoding.EncodeToString(encoded)
	return registryAuth, nil
}

func CheckImageAccessible(c *dockerclient.Client, dockerImage, authConfig string) error {
	if _, err := c.DistributionInspect(context.Background(), dockerImage, authConfig); err != nil {
		return ErrorImageInaccessible(dockerImage, err)
	}
	return nil
}

repository: morristech/cortex

license_type: permissive

repo_name: morristech/cortex

branch_name: refs/heads/master

extension: go


text:
//go:build windows
// +build windows

// Copyright 2022 Antrea Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package portcache

import (
	"fmt"

	"k8s.io/klog/v2"

	"antrea.io/antrea/pkg/agent/nodeportlocal/rules"
)

const (
	// stateInUse means that the NPL rule has been installed.
	stateInUse protocolSocketState = 1
)

// podIPPortFormat formats the ip, port to string ip:port.
func podIPPortProtoFormat(ip string, port int, protocol string) string {
	return fmt.Sprintf("%s:%d:%s", ip, port, protocol)
}

func (pt *PortTable) getEntryByPodIPPortProto(ip string, port int, protocol string) *NodePortData {
	return pt.PodEndpointTable[podIPPortProtoFormat(ip, port, protocol)]
}

func (pt *PortTable) GetEntry(ip string, port int, protocol string) *NodePortData {
	pt.tableLock.RLock()
	defer pt.tableLock.RUnlock()
	// Return pointer to copy of data from the PodEndpointTable.
	if data := pt.getEntryByPodIPPortProto(ip, port, protocol); data != nil {
		dataCopy := *data
		return &dataCopy
	}
	return nil
}

func addRuleForPort(podPortRules rules.PodPortRules, port int, podIP string, podPort int, protocol string) ([]ProtocolSocketData, error) {
	// Only the protocol used here should be returned if NetNatStaticMapping rule
	// can be inserted to an unused protocol port.
	protocols := make([]ProtocolSocketData, 0, 1)
	err := podPortRules.AddRule(port, podIP, podPort, protocol)
	if err != nil {
		klog.ErrorS(err, "Local port cannot be opened", "port", port, "protocol", protocol)
		return nil, err
	}
	protocols = append(protocols, ProtocolSocketData{
		Protocol: protocol,
		State:    stateInUse,
		socket:   nil,
	})
	return protocols, nil
}

func (pt *PortTable) addRuleforFreePort(podIP string, podPort int, protocol string) (int, []ProtocolSocketData, error) {
	klog.V(2).InfoS("Looking for free Node port on Windows", "podIP", podIP, "podPort", podPort, "protocol", protocol)
	numPorts := pt.EndPort - pt.StartPort + 1
	for i := 0; i < numPorts; i++ {
		port := pt.PortSearchStart + i
		if port > pt.EndPort {
			// handle wrap around
			port = port - numPorts
		}
		if _, ok := pt.NodePortTable[NodePortProtoFormat(port, protocol)]; ok {
			// protocol port is already taken
			continue
		}

		protocols, err := addRuleForPort(pt.PodPortRules, port, podIP, podPort, protocol)
		if err != nil {
			klog.ErrorS(err, "Port cannot be reserved, moving on to the next one", "port", port)
			continue
		}

		pt.PortSearchStart = port + 1
		if pt.PortSearchStart > pt.EndPort {
			pt.PortSearchStart = pt.StartPort
		}
		return port, protocols, nil
	}
	return 0, nil, fmt.Errorf("no free port found")
}

func (pt *PortTable) AddRule(podIP string, podPort int, protocol string) (int, error) {
	pt.tableLock.Lock()
	defer pt.tableLock.Unlock()
	npData := pt.getEntryByPodIPPortProto(podIP, podPort, protocol)
	exists := (npData != nil)
	if !exists {
		nodePort, protocols, err := pt.addRuleforFreePort(podIP, podPort, protocol)
		//success means port, protocol available.
		if err != nil {
			return 0, err
		}
		npData = &NodePortData{
			NodePort:  nodePort,
			PodIP:     podIP,
			PodPort:   podPort,
			Protocols: protocols,
		}

		pt.NodePortTable[NodePortProtoFormat(nodePort, protocol)] = npData
		pt.PodEndpointTable[podIPPortProtoFormat(podIP, podPort, protocol)] = npData
	} else {
		// Only add rules for if the entry does not exist.
		return 0, fmt.Errorf("existed windows nodeport entry for %s:%d:%s", podIP, podPort, protocol)
	}
	return npData.NodePort, nil
}

// RestoreRules should be called at Antrea Agent startup to restore a set of NPL rules.
func (pt *PortTable) RestoreRules(allNPLPorts []rules.PodNodePort, synced chan<- struct{}) error {
	pt.tableLock.Lock()
	defer pt.tableLock.Unlock()
	for _, nplPort := range allNPLPorts {
		protocols, err := addRuleForPort(pt.PodPortRules, nplPort.NodePort, nplPort.PodIP, nplPort.PodPort, nplPort.Protocol)
		if err != nil {
			// This will be handled gracefully by the NPL controller: if there is an
			// annotation using this port, it will be removed and replaced with a new
			// one with a valid port mapping.
			klog.ErrorS(err, "Cannot bind to local port, skipping it", "port", nplPort.NodePort)
			continue
		}

		npData := &NodePortData{
			NodePort:  nplPort.NodePort,
			PodPort:   nplPort.PodPort,
			PodIP:     nplPort.PodIP,
			Protocols: protocols,
		}
		pt.PodEndpointTable[podIPPortProtoFormat(nplPort.PodIP, nplPort.PodPort, nplPort.Protocol)] = pt.NodePortTable[NodePortProtoFormat(nplPort.NodePort, nplPort.Protocol)]
		pt.NodePortTable[NodePortProtoFormat(nplPort.NodePort, nplPort.Protocol)] = npData
	}
	// No need to sync up again because addRuleForPort has updated all rules on Windows
	close(synced)
	return nil
}

func (pt *PortTable) DeleteRule(podIP string, podPort int, protocol string) error {
	pt.tableLock.Lock()
	defer pt.tableLock.Unlock()
	data := pt.getEntryByPodIPPortProto(podIP, podPort, protocol)
	if data == nil {
		// Delete not required when the PortTable entry does not exist
		return nil
	}
	var protocolSocketData *ProtocolSocketData
	protocolSocketData = &data.Protocols[0]
	if protocolSocketData != nil {
		if err := pt.PodPortRules.DeleteRule(data.NodePort, podIP, podPort, protocol); err != nil {
			return err
		}
	}
	delete(pt.NodePortTable, NodePortProtoFormat(data.NodePort, protocol))
	delete(pt.PodEndpointTable, podIPPortProtoFormat(podIP, podPort, protocol))
	return nil
}

func (pt *PortTable) DeleteRulesForPod(podIP string) error {
	pt.tableLock.Lock()
	defer pt.tableLock.Unlock()
	podEntries := pt.getDataForPodIP(podIP)
	for _, podEntry := range podEntries {
		if len(podEntry.Protocols) > 0 {
			protocolSocketData := podEntry.Protocols[0]
			if err := pt.PodPortRules.DeleteRule(podEntry.NodePort, podIP, podEntry.PodPort, protocolSocketData.Protocol); err != nil {
				return err
			}
			delete(pt.PodEndpointTable, podIPPortProtoFormat(podIP, podEntry.PodPort, protocolSocketData.Protocol))
			delete(pt.NodePortTable, NodePortProtoFormat(podEntry.NodePort, protocolSocketData.Protocol))
		}
	}
	return nil
}

repository: edwardbadboy/antrea

repo_name: edwardbadboy/antrea

branch_name: refs/heads/main

gha_language: Go


text:
package main

import (
	"fmt"
	"bufio"
	"os"
)

const PROMPT = "p2p-fh> "

func Interact() {
	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print(PROMPT)
		text, _ := reader.ReadString('\n')
		HandleCommand(text[:len(text) - 1])
	}
}

func HandleCommand(cmd string) {
	switch cmd {
	case "show peers":
		// TODO: implement communicating between goroutines
		fmt.Println("Peers:")
		fmt.Println(peerList)
	}
}


text:
package api

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/bihe/bookmarks/internal/store"
	"github.com/go-chi/render"
)

// --------------------------------------------------------------------------
// Models
// --------------------------------------------------------------------------

// available node-types
// swagger:enum NodeType
type NodeType string

const (
	Node   NodeType = "Node"
	Folder NodeType = "Folder"
)

// Bookmark is the model provided via the REST API
// swagger:model
type Bookmark struct {
	ID          string     `json:"id"`
	Path        string     `json:"path"`
	DisplayName string     `json:"displayName"`
	URL         string     `json:"url"`
	SortOrder   int        `json:"sortOrder"`
	Type        NodeType   `json:"type"`
	Created     time.Time  `json:"created"`
	Modified    *time.Time `json:"modified,omitempty"`
	ChildCount  int        `json:"childCount"`
	AccessCount int        `json:"accessCount"`
	Favicon     string     `json:"favicon"`
}

// BookmarkList is a collection of Bookmarks
// swagger:model
type BookmarkList struct {
	Success bool       `json:"success"`
	Count   int        `json:"count"`
	Message string     `json:"message"`
	Value   []Bookmark `json:"value"`
}

// BookmarkResult has additional information about a Bookmark
// swagger:model
type BookmarkResult struct {
	Success bool     `json:"success"`
	Message string   `json:"message"`
	Value   Bookmark `json:"value"`
}

// Result is a generic response with a string value
// swagger:model
type Result struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Value   string `json:"value"`
}

// BookmarksSortOrder contains a sorting for a list of ids
// swagger:model
type BookmarksSortOrder struct {
	IDs       []string `json:"ids"`
	SortOrder []int    `json:"sortOrder"`
}

// --------------------------------------------------------------------------
// convert entities to models
// --------------------------------------------------------------------------

func entityToModel(b store.Bookmark) *Bookmark {
	return &Bookmark{
		ID:          b.ID,
		DisplayName: b.DisplayName,
		Path:        b.Path,
		Type:        entityEnumToModel(b.Type),
		URL:         b.URL,
		SortOrder:   b.SortOrder,
		Created:     b.Created,
		Modified:    b.Modified,
		AccessCount: b.AccessCount,
		ChildCount:  b.ChildCount,
		Favicon:     b.Favicon,
	}
}

func entityListToModel(bms []store.Bookmark) []Bookmark {
	var model = make([]Bookmark, 0)
	for _, b := range bms {
		model = append(model, *entityToModel(b))
	}
	return model
}

func entityEnumToModel(t store.NodeType) NodeType {
	if t == store.Folder {
		return Folder
	}
	return Node
}

// --------------------------------------------------------------------------
// Swagger specific definitions
// --------------------------------------------------------------------------

// swagger:parameters CreateBookmark UpdateBookmark
type BookMarkRequestSwagger struct {
	// In: body
	Body Bookmark
}

// swagger:parameters UpdateSortOrder
type BookmarksSortOrderRequestSwagger struct {
	// In: body
	Body BookmarksSortOrder
}

// --------------------------------------------------------------------------
// BookmarkRequest
// --------------------------------------------------------------------------

// BookmarkRequest is the request payload for Bookmark data model.
type BookmarkRequest struct {
	*Bookmark
}

// Bind assigns the the provided data to a BookmarkRequest
func (b *BookmarkRequest) Bind(r *http.Request) error {
	// a Bookmark is nil if no Bookmark fields are sent in the request. Return an
	// error to avoid a nil pointer dereference.
	if b.Bookmark == nil {
		return fmt.Errorf("missing required Bookmarks fields")
	}
	return nil
}

// String returns a string representation of a BookmarkRequest
func (b *BookmarkRequest) String() string {
	return fmt.Sprintf("Bookmark: '%s, %s' (Id: %s, Type: %s)", b.Path, b.DisplayName, b.ID, b.Type)
}

// --------------------------------------------------------------------------
// BookmarksSortOrderRequest
// --------------------------------------------------------------------------

// BookmarksSortOrderRequest is the request payload for Bookmark data model.
type BookmarksSortOrderRequest struct {
	*BookmarksSortOrder
}

// Bind assigns the the provided data to a BookmarksSortOrderRequest
func (b *BookmarksSortOrderRequest) Bind(r *http.Request) error {
	if b.BookmarksSortOrder == nil {
		return fmt.Errorf("missing required BookmarksSortOrder fields")
	}
	return nil
}

// String returns a string representation of a BookmarkRequest
func (b *BookmarksSortOrderRequest) String() string {
	var order []string
	for i := range b.SortOrder {
		order = append(order, strconv.Itoa(i))
	}
	return fmt.Sprintf("IDs: '%s', SortOrder: %s", strings.Join(b.IDs, ","), strings.Join(order, ","))
}

// --------------------------------------------------------------------------
// BookmarkResponse
// --------------------------------------------------------------------------

// BookmarkResponse is the response payload for the Bookmark data model.
type BookmarkResponse struct {
	*Bookmark
}

// Render the specific response
func (b BookmarkResponse) Render(w http.ResponseWriter, r *http.Request) error {
	// Pre-processing before a response is marshalled and sent across the wire
	return nil
}

// --------------------------------------------------------------------------
// BookmarkListResponse
// --------------------------------------------------------------------------

// BookmarkListResponse returns a list of Bookmark Items
type BookmarkListResponse struct {
	*BookmarkList
}

// Render the specific response
func (b BookmarkListResponse) Render(w http.ResponseWriter, r *http.Request) error {
	// Pre-processing before a response is marshalled and sent across the wire
	return nil
}

// --------------------------------------------------------------------------
// BookmarResultResponse
// --------------------------------------------------------------------------

// BookmarResultResponse returns BookmarResult
type BookmarResultResponse struct {
	*BookmarkResult
}

// Render the specific response
func (b BookmarResultResponse) Render(w http.ResponseWriter, r *http.Request) error {
	// Pre-processing before a response is marshalled and sent across the wire
	return nil
}

// --------------------------------------------------------------------------
// BookmarksPathsResponse
// --------------------------------------------------------------------------

// BookmarksPathsResponse returns available Paths
// swagger:model
type BookmarksPathsResponse struct {
	Paths []string `json:"paths"`
	Count int      `json:"count"`
}

// Render the specific response
func (b BookmarksPathsResponse) Render(w http.ResponseWriter, r *http.Request) error {
	return nil
}

// --------------------------------------------------------------------------
// ResultResponse
// --------------------------------------------------------------------------

// ResultResponse returns Result
type ResultResponse struct {
	*Result
	Status int `json:"-"` // ignore this
}

// Render the specific response
func (b ResultResponse) Render(w http.ResponseWriter, r *http.Request) error {
	if b.Status == 0 {
		render.Status(r, http.StatusOK)
	} else {
		render.Status(r, b.Status)
	}
	return nil
}

repository: bihe/bookmarks

repo_name: bihe/bookmarks


text:
package thumbnail

import (
	"github.com/ViBiOh/fibr/pkg/provider"
	"github.com/ViBiOh/httputils/v3/pkg/logger"
)

// Remove thumbnail of given item
func (a app) Remove(item provider.StorageItem) {
	if !a.Enabled() {
		return
	}

	if err := a.storage.Remove(getThumbnailPath(item)); err != nil {
		logger.Error("%s", err)
	}
}

// Rename thumbnails of given items
func (a app) Rename(old, new provider.StorageItem) {
	if !a.Enabled() {
		return
	}

	if err := a.storage.Rename(getThumbnailPath(old), getThumbnailPath(new)); err != nil {
		logger.Error("%s", err)
	}
}

license: MIT

repository: gtaglang/fibr

repo_name: gtaglang/fibr


text:
@Article{refA,
  title = {Can quantum-mechanical description of physical reality be considered complete?},
  author = {A. Einstein and B. Podolsky and N. Rosen},
  journal = {Phys.\ Rev.},
  volume = {47},
  year = {1935},
  pages = {777--780}
}

@Book{refB,
  title = {Probability Theory: The Logic of Science},
  year = {2003},
  author = {E. T. Jaynes},
  publisher = {Cambridge University Press}
}

@Incollection{refC,
  title = {On the present status of the radiation problem},
  author = {Albert Einstein},
  booktitle = {The Collected Papers of Albert Einstein},
  publisher = {Princeton University Press},
  year = {1989},
  pages = {357--375},
  volume = {2}
}

@Mastersthesis{refD,
  title = {Optical aberration coefficients},
  author = {Matthew Peter Rimmer},
  school = {University of Rochester},
  year = {1963}
}

@Phdthesis{refBOLD,
  title = {On the theory of quanta},
  author = {Louis-Victor de Broglie},
  school = {University of Paris},
  year = {1925}
}

repository: nzhagen/bibulous

repo_name: nzhagen/bibulous

gha_language: TeX

extension: bib


text:
package uninstall

import (
	"context"
	"fmt"
	"os"
	"testing"

	"github.com/linkerd/linkerd2/testutil"
)

var TestHelper *testutil.TestHelper

func TestMain(m *testing.M) {
	TestHelper = testutil.NewTestHelper()
	if !TestHelper.Uninstall() {
		fmt.Fprintln(os.Stderr, "Uninstall test disabled")
		os.Exit(0)
	}
	os.Exit(m.Run())
}

func TestInstall(t *testing.T) {
	args := []string{
		"install",
		"--crds",
		"--controller-log-level", "debug",
		"--proxy-log-level", "warn,linkerd=debug",
		"--set", fmt.Sprintf("proxy.image.version=%s", TestHelper.GetVersion()),
	}

	out, err := TestHelper.LinkerdRun(args...)
	if err != nil {
		testutil.AnnotatedFatal(t, "'linkerd install --crds' command failed", err)
	}
	out, err = TestHelper.KubectlApply(out, "")
	if err != nil {
		testutil.AnnotatedFatalf(t, "'kubectl apply' command failed",
			"'kubectl apply' command failed\n%s", out)
	}

	args = []string{
		"install",
		"--controller-log-level", "debug",
		"--proxy-log-level", "warn,linkerd=debug",
		"--set", fmt.Sprintf("proxy.image.version=%s", TestHelper.GetVersion()),
	}

	out, err = TestHelper.LinkerdRun(args...)
	if err != nil {
		testutil.AnnotatedFatal(t, "'linkerd install' command failed", err)
	}

	out, err = TestHelper.KubectlApply(out, "")
	if err != nil {
		testutil.AnnotatedFatalf(t, "'kubectl apply' command failed",
			"'kubectl apply' command failed\n%s", out)
	}

	var (
		vizCmd  = []string{"viz", "install"}
		vizArgs = []string{
			"--set", fmt.Sprintf("namespace=%s", TestHelper.GetVizNamespace()), "--wait", "60m"}
	)

	// Install Linkerd Viz Extension
	exec := append(vizCmd, vizArgs...)
	out, err = TestHelper.LinkerdRun(exec...)
	if err != nil {
		testutil.AnnotatedFatal(t, "'linkerd viz install' command failed", err)
	}

	out, err = TestHelper.KubectlApply(out, "")
	if err != nil {
		testutil.AnnotatedFatalf(t, "'kubectl apply' command failed",
			"'kubectl apply' command failed\n%s", out)
	}

}

func TestResourcesPostInstall(t *testing.T) {
	ctx := context.Background()
	// Tests Namespace
	err := TestHelper.CheckIfNamespaceExists(ctx, TestHelper.GetLinkerdNamespace())
	if err != nil {
		testutil.AnnotatedFatalf(t, "received unexpected output",
			"received unexpected output\n%s", err.Error())
	}

	// Tests Pods and Deployments

	expectedDeployments := testutil.LinkerdDeployReplicasEdge
	if !TestHelper.ExternalPrometheus() {
		expectedDeployments["prometheus"] = testutil.DeploySpec{Namespace: "linkerd-viz", Replicas: 1}
	}
	// Upgrade Case
	if TestHelper.UpgradeHelmFromVersion() != "" {
		expectedDeployments = testutil.LinkerdDeployReplicasStable
	}
	for deploy, spec := range expectedDeployments {
		if err := TestHelper.CheckPods(ctx, spec.Namespace, deploy, spec.Replicas); err != nil {
			//nolint:errorlint
			if rce, ok := err.(*testutil.RestartCountError); ok {
				testutil.AnnotatedWarn(t, "CheckPods timed-out", rce)
			} else {
				testutil.AnnotatedError(t, "CheckPods timed-out", err)
			}
		}
	}
}

func TestUninstall(t *testing.T) {
	var (
		vizCmd = []string{"viz", "uninstall"}
	)

	// Uninstall Linkerd Viz Extension
	out, err := TestHelper.LinkerdRun(vizCmd...)
	if err != nil {
		testutil.AnnotatedFatal(t, "'linkerd viz uninstall' command failed", err)
	}

	args := []string{"delete", "-f", "-"}
	out, err = TestHelper.Kubectl(out, args...)
	if err != nil {
		testutil.AnnotatedFatalf(t, "'kubectl delete' command failed",
			"'kubectl delete' command failed\n%s", out)
	}

	args = []string{"uninstall"}
	out, err = TestHelper.LinkerdRun(args...)
	if err != nil {
		testutil.AnnotatedFatal(t, "'linkerd install' command failed", err)
	}

	args = []string{"delete", "-f", "-"}
	out, err = TestHelper.Kubectl(out, args...)
	if err != nil {
		testutil.AnnotatedFatalf(t, "'kubectl delete' command failed",
			"'kubectl delete' command failed\n%s", out)
	}
}

func TestCheckPostUninstall(t *testing.T) {
	if err := TestHelper.TestCheckPre(); err != nil {
		t.Fatalf("'linkerd check' command failed: %s", err)
	}
}


text:
package main

/**
颠倒给定的 32 位无符号整数的二进制位。

提示：
请注意，在某些语言（如 Java）中，没有无符号整数类型。在这种情况下，输入和输出都将被指定为有符号整数类型，并且不应影响您的实现，因为无论整数是有符号的还是无符号的，其内部的二进制表示形式都是相同的。
在 Java 中，编译器使用二进制补码记法来表示有符号整数。因此，在上面的示例 2中，输入表示有符号整数 -3，输出表示有符号整数 -1073741825。

进阶:
如果多次调用这个函数，你将如何优化你的算法？

示例 1：
输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596，
     因此返回 964176192，其二进制表示形式为 00111001011110000010100101000000。

示例 2：
输入：11111111111111111111111111111101
输出：10111111111111111111111111111111
解释：输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293，
    因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。

示例 1：
输入：n = 00000010100101000001111010011100
输出：964176192 (00111001011110000010100101000000)
解释：输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596，
     因此返回 964176192，其二进制表示形式为 00111001011110000010100101000000。

示例 2：
输入：n = 11111111111111111111111111111101
输出：3221225471 (10111111111111111111111111111111)
解释：输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293，
    因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。

提示：输入是一个长度为 32 的二进制字符串
*/

/**
逐位分离
*/
func reverseBits(num uint32) uint32 {
	var res uint32 = 0
	for i := 0; i < 32; i++ {
		res <<= 1
		res |= num & 1
		num >>= 1
	}
	return res
}

/**
分治算法 https://pic.leetcode-cn.com/1616982968-vXsJSf-190.001.jpeg 图解
*/
const (
	m1 = 0x55555555 // 01010101010101010101010101010101
	m2 = 0x33333333 // 00110011001100110011001100110011
	m4 = 0x0f0f0f0f // 00001111000011110000111100001111
	m8 = 0x00ff00ff // 00000000111111110000000011111111
)

func reverseBits2(n uint32) uint32 {
	n = n>>1&m1 | n&m1<<1
	n = n>>2&m2 | n&m2<<2
	n = n>>4&m4 | n&m4<<4
	n = n>>8&m8 | n&m8<<8
	return n>>16 | n<<16
}

func main() {

}

repository: WAYLON/algorithm-go

repo_name: WAYLON/algorithm-go


text:
DESCRIPTION = "FreeGLUT is a free-software/open-source alternative to the OpenGL \
               Utility Toolkit (GLUT) library"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://COPYING;md5=89c0b58a3e01ce3d8254c9f59e78adfb"

SRC_URI = "https://sourceforge.net/projects/${BPN}/files/${BPN}/${PV}/${BPN}-${PV}.tar.gz"
SRC_URI[sha256sum] = "3c0bcb915d9b180a97edaebd011b7a1de54583a838644dcd42bb0ea0c6f3eaec"

inherit cmake features_check pkgconfig

# depends on virtual/libgl
REQUIRED_DISTRO_FEATURES = "opengl"

PACKAGECONFIG ?= "${@bb.utils.filter('DISTRO_FEATURES', 'wayland x11', d)}"
PACKAGECONFIG[gles] = "-DFREEGLUT_GLES=ON,-DFREEGLUT_GLES=OFF,"
PACKAGECONFIG[wayland] = "-DFREEGLUT_WAYLAND=ON,-DFREEGLUT_WAYLAND=OFF,libxkbcommon"
PACKAGECONFIG[demos] = "-DFREEGLUT_BUILD_DEMOS=ON,-DFREEGLUT_BUILD_DEMOS=OFF,"
PACKAGECONFIG[x11] = ",,virtual/libx11 libice libxmu libglu libxrandr libxext"
# Add -Wno-implicit-function-declaration since it might be otherwise treated at
# error by clang16+ and this is not really a problem
CFLAGS += "-Wno-implicit-function-declaration"

PROVIDES += "mesa-glut"

DEPENDS = "virtual/libgl libxi"

do_install:append() {
    # Remove buildpaths
    sed -i "s#${RECIPE_SYSROOT}##g" ${D}${libdir}/cmake/FreeGLUT/FreeGLUTTargets.cmake
}

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_license_id: MIT

gha_language: BitBake

extension: bb


text:
package writers

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"io"
	"sort"
	"strings"

	"github.com/imdario/mergo"

	"github.com/thlcodes/genfig/models"

	"github.com/thlcodes/genfig/util"
	u "github.com/thlcodes/genfig/util"
)

func init() {
	gob.Register(map[string]interface{}{})
	gob.Register([]interface{}{})
}

//WriteConfig writes
func WriteConfig(w io.Writer, s models.SchemaMap, config map[string]interface{}, def map[string]interface{}, env string) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = u.RecoverError(r)
			return
		}
	}()

	// first write into buffer, so that no gobbledygook is written
	// into some files, when someting panics
	buf := bytes.NewBuffer([]byte{})

	// assigns this config to the according child of the global 'Envs' var
	// via an init function
	buf.Write(u.B("func init() {" + nl + indent + "Envs." + strings.Title(env) + " = "))

	merged := make(map[string]interface{})
	copyMap(def, &merged)
	if err := mergo.Merge(&merged, config, mergo.WithOverride); err != nil {
		panic(err)
	}

	// write actual config
	WriteConfigValue(buf, defaultSchemaRootName, merged, s, 1)

	// closing bracket of init func
	buf.Write(u.B(nl + "}" + nl))

	// now write buffer to writer
	w.Write(buf.Bytes())

	return
}

//WriteConfigLine writes
func WriteConfigLine(w io.Writer, p string, k string, v interface{}, s models.SchemaMap, l int) {
	if l > maxLevel {
		panic(fmt.Errorf("Maximum of %d levels exceeded", maxLevel))
	}

	n := strings.Title(k)

	if _, ex := s[p+n]; !ex {
		panic(fmt.Errorf("Config property '%s' is not defined in the default config", p+n))
	}

	w.Write(u.B(indents[:l*len(indent)]))
	w.Write(u.B(n + ": "))

	WriteConfigValue(w, p+n, v, s, l)

	w.Write(u.B("," + nl))
}

//WriteConfigValue writes
func WriteConfigValue(w io.Writer, p string, v interface{}, s models.SchemaMap, l int) {
	switch v.(type) {
	case map[string]interface{}:
		w.Write(u.B(p + "{" + nl))
		keys := []string{}
		for _k := range v.(map[string]interface{}) {
			keys = append(keys, _k)
		}
		sort.Strings(keys)
		for _, _k := range keys {
			_v := v.(map[string]interface{})[_k]
			//_o := getOverwriteEntry(o, _k)
			WriteConfigLine(w, p, _k, _v /*, _o*/, s, l+1)
		}
		w.Write(u.B(indents[:l*len(indent)]))
		w.Write(u.B("}"))
	case []interface{}:
		t := &v
		typ := util.DetectSliceTypeString((*t).([]interface{}))
		w.Write(u.B(strings.Replace(fmt.Sprintf("%#v", *t), "[]interface {}", typ, 1)))
	default:
		t := &v
		fmt.Fprintf(w, `%#v`, *t)
	}
}

func copyMap(from map[string]interface{}, to *map[string]interface{}) error {
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	dec := gob.NewDecoder(&buf)
	err := enc.Encode(from)
	if err != nil {
		return err
	}
	err = dec.Decode(to)
	if err != nil {
		return err
	}
	return nil
}

repository: thlcodes/genfig

repo_name: thlcodes/genfig


text:
L4T_DEB_COPYRIGHT_MD5 = "38ef63b8f3232378d9f652f640ee0a3f"

require tegra-debian-libraries-common.inc

DESCRIPTION = "Prebuilt OPTEE normal-world binaries"
MAINSUM = "7f7c120849696957b432f9c280a905d957dc634bffac22444469d583f21e393d"

inherit systemd

LIC_FILES_CHKSUM += " \
    file://usr/share/doc/nvidia-tegra/LICENSE.optee_test;md5=daa2bcccc666345ab8940aab1315a4fa \
    file://usr/share/doc/nvidia-tegra/LICENSE.optee_client;md5=69663ab153298557a59c67a60a743e5b \
    file://usr/share/doc/nvidia-tegra/LICENSE.nvhwkey-app;md5=6938d70d5e5d49d31049419e85bb82f8 \
    file://usr/share/doc/nvidia-tegra/LICENSE.nvluks-srv-app;md5=6938d70d5e5d49d31049419e85bb82f8 \
    file://usr/share/doc/nvidia-tegra/LICENSE.82154947-c1bc-4bdf-b89d-04f93c0ea97c.ta;md5=6938d70d5e5d49d31049419e85bb82f8 \
"
LICENSE += "& BSD-2-Clause & GPL-2.0-only"
LICENSE:${PN} = "BSD-2-Clause"
LICENSE:${PN}-base-tas = "BSD-2-Clause"
LICENSE:${PN}-test = "GPL-2.0-only & BSD-2-Clause"
LICENSE:${PN}-nvsamples = "BSD-2-Clause"

PROVIDES += "optee-client optee-test optee-nvsamples"

do_install() {
    install -d ${D}${libdir} ${D}${libdir}/tee-supplicant/plugins
    install -m 0644 ${S}/usr/lib/libckteec.so.0.1.0 ${D}${libdir}
    install -m 0644 ${S}/usr/lib/libteec.so.1.0.0 ${D}${libdir}
    ln -s libckteec.so.0.1.0 ${D}${libdir}/libckteec.so.0.1
    ln -s libckteec.so.0.1 ${D}${libdir}/libckteec.so.0
    ln -s libckteec.so.0 ${D}${libdir}/libckteec.so
    ln -s libteec.so.1.0.0 ${D}${libdir}/libteec.so.1.0
    ln -s libteec.so.1.0 ${D}${libdir}/libteec.so.1
    ln -s libteec.so.1 ${D}${libdir}/libteec.so
    install -m 0755 ${S}/usr/lib/tee-supplicant/plugins/f07bfc66-958c-4a15-99c0-260e4e7375dd.plugin ${D}${libdir}/tee-supplicant/plugins

    install -d ${D}${sbindir}
    install -m 0755 ${S}/usr/sbin/nvhwkey-app ${D}${sbindir}
    install -m 0755 ${S}/usr/sbin/nvluks-srv-app ${D}${sbindir}
    install -m 0755 ${S}/usr/sbin/tee-supplicant ${D}${sbindir}

    install -d ${D}${base_libdir}/optee_armtz
    install -m 0644 ${S}/lib/optee_armtz/*.ta ${D}${base_libdir}/optee_armtz/

    install -d ${D}${systemd_system_unitdir}
    install -m 0644 ${S}/etc/systemd/system/nv-tee-supplicant.service ${D}${systemd_system_unitdir}/
}

# Put -test last here so TAs end up in the right package
PACKAGES =+ "${PN}-nvsamples-luks-srv ${PN}-nvsamples-hwkey-agent ${PN}-nvsamples ${PN}-base-tas ${PN}-test"
RPROVIDES:${PN} = "optee-client"
RCONFLICTS:${PN} = "optee-client"
RREPLACES:${PN} = "optee-client"
RPROVIDES:${PN}-base-tas = "optee-os"
RCONFLICTS:${PN}-base-tas = "optee-os"
RREPLACES:${PN}-base-tas = "optee-os"
RPROVIDES:${PN}-test = "optee-test"
RCONFLICTS:${PN}-test = "optee-test"
RREPLACES:${PN}-test = "optee-test"
RPROVIDES:${PN}-nvsamples-hwkey-agent = "optee-nvsamples-hwkey-agent"
RCONFLICTS:${PN}-nvsamples-hwkey-agent = "optee-nvsamples-hwkey-agent"
RREPLACES:${PN}-nvsamples-hwkey-agent = "optee-nvsamples-hwkey-agent"
RPROVIDES:${PN}-nvsamples-luks-srv = "optee-nvsamples-luks-srv"
RCONFLICTS:${PN}-nvsamples-luks-srv = "optee-nvsamples-luks-srv"
RREPLACES:${PN}-nvsamples-luks-srv = "optee-nvsamples-luks-srv"
RPROVIDES:${PN}-nvsamples = "optee-nvsamples"
RCONFLICTS:${PN}-nvsamples = "optee-nvsamples"
RREPLACES:${PN}-nvsamples = "optee-nvsamples"
ALLOW_EMPTY:${PN}-nvsamples = "1"
RDEPENDS:${PN}-nvsamples = "${PN}-nvsamples-hwkey-agent ${PN}-nvsamples-luks-srv"

SYSTEMD_SERVICE:${PN} = "nv-tee-supplicant.service"

FILES:${PN}-nvsamples-hwkey-agent = "\
    ${sbindir}/nvhwkey-app \
    ${nonarch_base_libdir}/optee_armtz/82154947-c1bc-4bdf-b89d-04f93c0ea97c.ta \
"
FILES:${PN}-nvsamples-luks-srv = "\
    ${sbindir}/nvluks-srv-app \
"
FILES:${PN}-base-tas = "\
    ${nonarch_base_libdir}/optee_armtz/023f8f1a-292a-432b-8fc4-de8471358067.ta \
    ${nonarch_base_libdir}/optee_armtz/f04a0fe7-1f5d-4b9b-abf7-619b85b4ce8c.ta \
    ${nonarch_base_libdir}/optee_armtz/fd02c9da-306c-48c7-a49c-bbd827ae86ee.ta \
"
FILES:${PN}-test = "\
    ${bindir}/xtest \
    ${libdir}/tee-supplicant/plugins \
    ${nonarch_base_libdir}/optee_armtz \
"
RDEPENDS:${PN}-test = "${PN}"
RDEPENDS:${PN}-nvsamples = "${PN}"
RDEPENDS:${PN} = "${PN}-base-tas"

repository: lfdmn/meta-tegra

repo_name: lfdmn/meta-tegra


text:
SUMMARY = "Main program"
DESCRIPTION = "Handle main function"
LICENSE = "CLOSED"

FILESEXTRAPATHS_prepend := "${THISDIR}/../../../../:"

SRC_URI =  " \
    file://main.service \
    file://dist/ \
    file://src/ \
    file://CMakeLists.txt \
"

inherit systemd cmake

S = "${WORKDIR}"
EXTRA_OECMAKE = ""

DEPENDS = "nlohmann-json pistache openssl wpa-supplicant"
RDEPENDS_${PN} += "bash libwpa-client"
SYSTEMD_PACKAGES = "${PN}"
SYSTEMD_SERVICE_${PN} = "main.service"
SYSTEMD_AUTO_ENABLE = "enable"
SYSTEMD_AUTO_ENABLE_${PN} = "enable"

do_install_append () {

    install -d ${D}${sysconfdir}
    cp -r ${WORKDIR}/dist ${D}${sysconfdir}

    install -d ${D}${systemd_unitdir}/system/
    install -m 0644 ${WORKDIR}/main.service ${D}${systemd_unitdir}/system
}

license: Unlicense,MIT

repository: jasonmnemonic/xiaopi

detected_licenses: Unlicense MIT

repo_name: jasonmnemonic/xiaopi


text:
package main

import (
	"database/sql"
	"strconv"
	"time"
)

type VoteChoice string
type VoteID uint64

const (
	Hot     = VoteChoice("hot")
	Comfort = VoteChoice("comfort")
	Cold    = VoteChoice("cold")
)

type Vote struct {
	VoteID    VoteID
	RoomID    RoomID
	S         *Session
	Choice    VoteChoice
	Timestamp time.Time
}

// 投票内容を変更する。VoteID, RoomID, Sが指定されていなければならない。
// 初投票の場合は、VoteIDはデフォルト値(VoteID(0))に設定すること。
func (v *Vote) UpdateChoice(tx *sql.Tx, choice VoteChoice) error {
	now := time.Now()
	if v.VoteID == VoteID(0) {
		// 初投票の場合
		if _, err := tx.Exec(`
			INSERT INTO vote(
				session_id, room_id, choice, timestamp
			) VALUES (?, ?, ?, ?)`,
			v.S.SessionID, v.RoomID, string(choice), now,
		); err != nil {
			return err
		}
	} else {
		// 投票内容を変更する場合
		if _, err := tx.Exec(`
			UPDATE vote SET choice=?, timestamp=? WHERE vote_id=?`,
			string(choice), now, v.VoteID,
		); err != nil {
			return err
		}
	}
	v.Choice = choice
	v.Timestamp = now
	return nil
}

type RoomID uint64
type BuildingName string
type FloorID int64

type Room struct {
	RoomID       RoomID
	Name         string
	BuildingName BuildingName
	FloorID      FloorID
}

func StringToRoomID(strid string) (id RoomID, err error) {
	var i uint64
	i, err = strconv.ParseUint(strid, 10, 64)
	id = RoomID(i)
	return
}


text:
@InProceedings{mohri14,
  pdf = {http://jmlr.org/proceedings/papers/v32/mohri14.pdf},
  section = {cycle-1},
  supplementary = {Supplementary:mohri14-supp.pdf},
  title = {Learning Theory and Algorithms for revenue optimization in second price auctions with reserve},
  author = {Mehryar Mohri and Andres Munoz Medina},
  pages = {262-270},
  abstract = {Second-price auctions with reserve play a critical role for    modern search engine and popular online sites since the revenue of   these companies often directly depends on the outcome of such   auctions. The choice of the reserve price is the main mechanism   through which the auction revenue can be influenced in these   electronic markets. We cast the problem of selecting the reserve   price to optimize revenue as a learning problem and present a full   theoretical analysis dealing with the complex properties of the   corresponding loss function (it is non-convex and discontinuous). We further give novel algorithms for solving this problem and report the results of encouraging experiments   demonstrating their effectiveness.},
}

repository: mreid/papersite

repo_name: mreid/papersite


text:
package openmall

import (
	"encoding/xml"

	"github.com/bububa/opentaobao/model"
)

// TaobaoOpenmallTradeCloseAPIResponse 关闭订单 API返回值
// taobao.openmall.trade.close
//
// 关闭订单
type TaobaoOpenmallTradeCloseAPIResponse struct {
	model.CommonResponse
	TaobaoOpenmallTradeCloseAPIResponseModel
}

// TaobaoOpenmallTradeCloseAPIResponseModel is 关闭订单 成功返回结果
type TaobaoOpenmallTradeCloseAPIResponseModel struct {
	XMLName xml.Name `xml:"openmall_trade_close_response"`
	// 平台颁发的每次请求访问的唯一标识
	RequestId string `json:"request_id,omitempty" xml:"request_id,omitempty"`
	// 出参
	Result *TopTradeResultVo `json:"result,omitempty" xml:"result,omitempty"`
}

repository: bububa/opentaobao

repo_name: bububa/opentaobao


text:
package cache

import (
	"testing"
	"time"

	"github.com/x893675/gopkg/clock"
)

func expectEntry(t *testing.T, c *LRUExpireCache, key interface{}, value interface{}) {
	result, ok := c.Get(key)
	if !ok || result != value {
		t.Errorf("Expected cache[%v]: %v, got %v", key, value, result)
	}
}

func expectNotEntry(t *testing.T, c *LRUExpireCache, key interface{}) {
	if result, ok := c.Get(key); ok {
		t.Errorf("Expected cache[%v] to be empty, got %v", key, result)
	}
}

func TestSimpleGet(t *testing.T) {
	c := NewLRUExpireCache(10)
	c.Add("long-lived", "12345", 10*time.Hour)
	expectEntry(t, c, "long-lived", "12345")
}

func TestExpiredGet(t *testing.T) {
	fakeClock := clock.NewFakeClock(time.Now())
	c := NewLRUExpireCacheWithClock(10, fakeClock)
	c.Add("short-lived", "12345", 1*time.Millisecond)
	// ensure the entry expired
	fakeClock.Step(2 * time.Millisecond)
	expectNotEntry(t, c, "short-lived")
}

func TestLRUOverflow(t *testing.T) {
	c := NewLRUExpireCache(4)
	c.Add("elem1", "1", 10*time.Hour)
	c.Add("elem2", "2", 10*time.Hour)
	c.Add("elem3", "3", 10*time.Hour)
	c.Add("elem4", "4", 10*time.Hour)
	c.Add("elem5", "5", 10*time.Hour)
	expectNotEntry(t, c, "elem1")
	expectEntry(t, c, "elem2", "2")
	expectEntry(t, c, "elem3", "3")
	expectEntry(t, c, "elem4", "4")
	expectEntry(t, c, "elem5", "5")
}


text:
SUMMARY = "Protocol Buffers Python bindings"
SECTION = "devel/python"
LICENSE = "BSD-3-Clause"

LIC_FILES_CHKSUM = "file://${WORKDIR}/git/LICENSE;md5=35953c752efc9299b184f91bef540095"

inherit setuptools3

SRCREV = "a6189acd18b00611c1dc7042299ad75486f08a1a"
PV = "3.3.0+git${SRCPV}"
SRC_URI = "git://github.com/google/protobuf.git"

S = "${WORKDIR}/git/python"

DEPENDS = "python3 protobuf protobuf-native python3-setuptools-native"

repository: intel/intel-iot-refkit

repo_name: intel/intel-iot-refkit

gha_language: Python


text:
'use strict';

// Import Express
var express = require('express');
var Employee = require('../models/employee');

// Create a Router to prevent namespace collisions
var router = express.Router();

/*
  API ROUTES
*/
// NOTE: GET Route - fetches ALL employees
router.get('/employees', function(request, response){

  // query directly from the model Todo object.
  Employee.find({}, function(err, employees){

    if(err) {
      return response.status(500).json({message: err.message});
    }
    response.json({employees: employees});
  });

});

// TODO: GET Route - fetches employee by ID

// NOTE: POST Route - adds an employee to the database
router.post('/employees', function(request, response){
  var employee = request.body;

  Employee.create(employee, function(err, employee){
    if(err) {
      return response.status(500).json({err: err.message});
    }

    response.json({'employee': employee, message: 'Employee Created'});
  })
});

// NOTE: PUT Route - updates an existing employee in the database
router.put('/employees/:id', function(request, response){
  // Get the ID of the Todo to update
  var id = request.params.id;
  var employee = request.body;

  if(employee && employee._id != id) {
    return response.status(500).json({err: "Did not find a match to the ID provided."});
  }

  Employee.findByIdAndUpdate(id, employee, {new: true}, function(err, employee){
    // the {new: true} is an option. With this set to true, the data
    // returned in the response body contains the updated data, rather
    // than the old data.
    if(err) {
      return response.status(500).json({err: err.message});
    }

    response.json({'employee': employee, message: 'Employee Updated'});
  });
});

// NOTE: DELETE Route - removes an existing employee out of the database
router.delete('/employees/:id', function(request, response){
  // Get the ID of the Todo to update
  var id = request.params.id;
  var employee = request.body;

  if(employee && employee._id != id) {
    return response.status(500).json({err: "Did not find a match to the ID provided."});
  }

  Employee.findByIdAndRemove(id, function(err, employee){

    if(err) {
      return response.status(500).json({err: err.message});
    }

    response.json({'employee': employee, message: 'Employee Deleted'});
  });
});

// Export the router so it can be accessed in app.js
// Think of this like the Video Out cable on the back of your DVD player.
// When you require the Router in the app.js file, that would be you plugging
// in the cable into this socket.
module.exports = router;

repository: markfilter/Mongo-Express-Node-REST-App

repo_name: markfilter/Mongo-Express-Node-REST-App

extension: js


text:
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc.  All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cassandra

import (
	"fmt"
	"strings"

	"github.com/urfave/cli"

	"go.temporal.io/server/common/auth"
	c "go.temporal.io/server/common/config"
	"go.temporal.io/server/common/log"
	"go.temporal.io/server/common/log/tag"
	"go.temporal.io/server/environment"
	"go.temporal.io/server/tools/common/schema"
)

const defaultNumReplicas = 1

// SetupSchemaConfig contains the configuration params needed to setup schema tables
type SetupSchemaConfig struct {
	CQLClientConfig
	schema.SetupConfig
}

// setupSchema executes the setupSchemaTask
// using the given command line arguments
// as input
func setupSchema(cli *cli.Context, logger log.Logger) error {
	config, err := newCQLClientConfig(cli)
	if err != nil {
		logger.Error("Unable to read config.", tag.Error(schema.NewConfigError(err.Error())))
		return err
	}
	client, err := newCQLClient(config, logger)
	if err != nil {
		logger.Error("Unable to establish CQL session.", tag.Error(err))
		return err
	}
	defer client.Close()
	if err := schema.Setup(cli, client, logger); err != nil {
		logger.Error("Unable to setup CQL schema.", tag.Error(err))
		return err
	}
	return nil
}

// updateSchema executes the updateSchemaTask
// using the given command lien args as input
func updateSchema(cli *cli.Context, logger log.Logger) error {
	config, err := newCQLClientConfig(cli)
	if err != nil {
		logger.Error("Unable to read config.", tag.Error(schema.NewConfigError(err.Error())))
		return err
	}
	client, err := newCQLClient(config, logger)
	if err != nil {
		logger.Error("Unable to establish CQL session.", tag.Error(err))
		return err
	}
	defer client.Close()
	if err := schema.Update(cli, client, logger); err != nil {
		logger.Error("Unable to update CQL schema.", tag.Error(err))
		return err
	}
	return nil
}

func createKeyspace(cli *cli.Context, logger log.Logger) error {
	config, err := newCQLClientConfig(cli)
	if err != nil {
		logger.Error("Unable to read config.", tag.Error(schema.NewConfigError(err.Error())))
		return err
	}
	keyspace := cli.String(schema.CLIOptKeyspace)
	if keyspace == "" {
		err := fmt.Errorf("missing %s argument", flag(schema.CLIOptKeyspace))
		logger.Error("Unable to read config.", tag.Error(schema.NewConfigError(err.Error())))
		return err
	}
	err = doCreateKeyspace(config, keyspace, logger)
	if err != nil {
		logger.Error("Unable to create keyspace.", tag.Error(err))
		return err
	}
	return nil
}

func dropKeyspace(cli *cli.Context, logger log.Logger) error {
	config, err := newCQLClientConfig(cli)
	if err != nil {
		logger.Error("Unable to read config.", tag.Error(schema.NewConfigError(err.Error())))
		return err
	}
	keyspace := cli.String(schema.CLIOptKeyspace)
	if keyspace == "" {
		err := fmt.Errorf("missing %s argument", flag(schema.CLIOptKeyspace))
		logger.Error("Unable to read config.", tag.Error(schema.NewConfigError(err.Error())))
		return err
	}
	err = doDropKeyspace(config, keyspace, logger)
	if err != nil {
		logger.Error("Unable to drop keyspace.", tag.Error(err))
		return err
	}
	return nil
}

func validateHealth(cli *cli.Context, logger log.Logger) error {
	config, err := newCQLClientConfig(cli)
	if err != nil {
		logger.Error("Unable to read config.", tag.Error(schema.NewConfigError(err.Error())))
		return err
	}

	config.Keyspace = systemKeyspace

	client, err := newCQLClient(config, logger)
	if err != nil {
		logger.Error("Unable to establish CQL session.", tag.Error(err))
		return err
	}

	defer client.Close()
	return nil
}

func doCreateKeyspace(cfg *CQLClientConfig, name string, logger log.Logger) error {
	cfg.Keyspace = systemKeyspace
	client, err := newCQLClient(cfg, logger)
	if err != nil {
		return err
	}
	defer client.Close()
	return client.createKeyspace(name)
}

func doDropKeyspace(cfg *CQLClientConfig, name string, logger log.Logger) error {
	cfg.Keyspace = systemKeyspace
	client, err := newCQLClient(cfg, logger)
	if err != nil {
		return err
	}
	defer client.Close()
	return client.dropKeyspace(name)
}

func newCQLClientConfig(cli *cli.Context) (*CQLClientConfig, error) {
	config := &CQLClientConfig{
		Hosts:                    cli.GlobalString(schema.CLIOptEndpoint),
		Port:                     cli.GlobalInt(schema.CLIOptPort),
		User:                     cli.GlobalString(schema.CLIOptUser),
		Password:                 cli.GlobalString(schema.CLIOptPassword),
		Timeout:                  cli.GlobalInt(schema.CLIOptTimeout),
		Keyspace:                 cli.GlobalString(schema.CLIOptKeyspace),
		numReplicas:              cli.Int(schema.CLIOptReplicationFactor),
		Datacenter:               cli.String(schema.CLIOptDatacenter),
		Consistency:              cli.String(schema.CLIOptConsistency),
		DisableInitialHostLookup: cli.GlobalBool(schema.CLIFlagDisableInitialHostLookup),
	}

	if cli.GlobalBool(schema.CLIFlagEnableTLS) {
		config.TLS = &auth.TLS{
			Enabled:                true,
			CertFile:               cli.GlobalString(schema.CLIFlagTLSCertFile),
			KeyFile:                cli.GlobalString(schema.CLIFlagTLSKeyFile),
			CaFile:                 cli.GlobalString(schema.CLIFlagTLSCaFile),
			ServerName:             cli.GlobalString(schema.CLIFlagTLSHostName),
			EnableHostVerification: !cli.GlobalBool(schema.CLIFlagTLSDisableHostVerification),
		}
	}

	config.AddressTranslator = &c.CassandraAddressTranslator{
		Translator: cli.GlobalString(schema.CLIOptAddressTranslator),
		Options:    parseOptionsMap(cli.GlobalString(schema.CLIOptAddressTranslatorOptions)),
	}

	if err := validateCQLClientConfig(config); err != nil {
		return nil, err
	}
	return config, nil
}

func parseOptionsMap(value string) map[string]string {
	if len(value) == 0 {
		return make(map[string]string)
	}

	split := strings.Split(value, ",")

	parsedMap := make(map[string]string)

	for _, pair := range split {
		trimmedPair := strings.ReplaceAll(pair, " ", "")
		if len(trimmedPair) == 0 {
			continue
		}
		splitPair := strings.Split(trimmedPair, "=")
		if len(splitPair) != 2 {
			continue
		}
		if len(splitPair[0]) == 0 || len(splitPair[1]) == 0 {
			continue
		}
		parsedMap[splitPair[0]] = splitPair[1]
	}

	return parsedMap
}

func validateCQLClientConfig(config *CQLClientConfig) error {
	if len(config.Hosts) == 0 {
		return schema.NewConfigError("missing cassandra endpoint argument " + flag(schema.CLIOptEndpoint))
	}
	if config.Keyspace == "" {
		return schema.NewConfigError("missing " + flag(schema.CLIOptKeyspace) + " argument ")
	}
	if config.Port == 0 {
		config.Port = environment.GetCassandraPort()
	}
	if config.numReplicas == 0 {
		config.numReplicas = defaultNumReplicas
	}

	if config.AddressTranslator != nil && len(config.AddressTranslator.Options) != 0 {
		if len(config.AddressTranslator.Translator) == 0 {
			return schema.NewConfigError("missing address translator argument " + flag(schema.CLIOptAddressTranslator))
		}
	}

	return nil
}

func flag(opt string) string {
	return "(-" + opt + ")"
}

repository: temporalio/temporal

repo_name: temporalio/temporal


text:
SECTION = "console/network"
LICENSE = "GPL"
DESCRIPTION = "dhcpcd is an RFC2131-, RFC2132-, and \
RFC1541-compliant DHCP client daemon. It gets an IP address \
and other information from the DHCP server, automatically \
configures the network interface, and tries to renew the \
lease time according to RFC2131 or RFC1541."
PR = "r1"

sbindir = "/sbin"

SRC_URI = "http://www.phystech.com/ftp/dhcpcd-${PV}.tar.gz \
	   file://config_dir.patch \
	   file://paths.patch"

inherit autotools

SRC_URI[md5sum] = "dd627a121e43835bead3ffef5b1a72fd"
SRC_URI[sha256sum] = "f435e14e1f54dc8792f4e655463d07f2bdbe6d8a8581bd62f5167334ab18bb87"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package routers

import (
	"gin-api/controllers/conn"
	"gin-api/controllers/opentracing"
	"gin-api/controllers/ping"
	"gin-api/global"
	"gin-api/middlewares/limiter"
	"gin-api/middlewares/log"
	"gin-api/middlewares/panic"
	"gin-api/middlewares/timeout"
	"gin-api/response"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func InitRouter() *gin.Engine {
	server := gin.New()

	server.Use(log.InitContext())

	server.Use(panic.ThrowPanic())

	server.Use(timeout.TimeoutMiddleware(time.Duration(global.Global.ContextTimeout) * time.Millisecond))

	server.Use(limiter.Limiter(10))

	server.Use(log.LoggerMiddleware())

	server.NoRoute(func(c *gin.Context) {
		response.Response(c, response.CodeUriNotFound, nil, "")
		c.AbortWithStatus(http.StatusNotFound)
	})

	pingGroup := server.Group("/ping")
	{
		pingGroup.GET("", ping.Ping)
	}

	testGroup := server.Group("/test")
	{
		testGroup.POST("/rpc", opentracing.Rpc)
		testGroup.POST("/rpc1", opentracing.Rpc1)
		testGroup.POST("/panic", opentracing.Panic)
		testGroup.POST("/conn", conn.Do)
	}

	return server
}

repository: leeonsoft/gin-api

repo_name: leeonsoft/gin-api


text:
@Article{sesia2019,
    author = {Sesia, M. and Sabatti, C. and Cand{\`e}s, E. J.},
    title = {Gene hunting with hidden Markov model knockoffs},
    journal = {Biometrika},
    volume = {106},
    pages = {1--18},
    year = 2019,
    doi = {10.1093/biomet/asy033},
},
@Article{LZ-LJ:2020,
  title={Floodgate: Inference for Model-Free Variable Importance},
  author={Zhang, Lu and Janson, Lucas},
  journal={arXiv preprint arXiv:2007.01283},
  year={2020}
}

repository: LuZhangH/floodgate

repo_name: LuZhangH/floodgate


text:
@InProceedings{zhao14,
  supplementary = {Supplementary:zhao14-supp.pdf},
  title = {Robust Principal Component Analysis with Complex Noise},
  author = {Qian Zhao and Deyu Meng and Zongben Xu and Wangmeng Zuo and Lei Zhang},
  pages = {55-63},
  abstract = {The research on robust principal component analysis (RPCA) has been attracting much attention recently. The original RPCA model assumes sparse noise, and use the $L_1$-norm to characterize the error term. In practice, however, the noise is much more complex and it is not appropriate to simply use a certain $L_p$-norm for noise modeling. We propose a generative RPCA model under the Bayesian framework by modeling data noise as a mixture of Gaussians (MoG). The MoG is a universal approximator to continuous distributions and thus our model is able to fit a wide range of noises such as Laplacian, Gaussian, sparse noises and any combinations of them. A variational Bayes algorithm is presented to infer the posterior of the proposed model. All involved parameters can be recursively updated in closed form. The advantage of our method is demonstrated by extensive experiments on synthetic data, face modeling and background subtraction.},
  section = {cycle-2},
}


text:
package bosh

import (
	"fmt"

	"github.com/cloudfoundry-incubator/candiedyaml"
	"github.com/pivotal-cf-experimental/bosh-bootloader/aws/cloudformation"
)

type CloudConfigurator struct {
	logger    logger
	generator cloudConfigGenerator
}

type logger interface {
	Step(message string)
	Println(string)
}

type cloudConfigGenerator interface {
	Generate(CloudConfigInput) (CloudConfig, error)
}

func NewCloudConfigurator(logger logger, generator cloudConfigGenerator) CloudConfigurator {
	return CloudConfigurator{
		logger:    logger,
		generator: generator,
	}
}

func (c CloudConfigurator) Configure(stack cloudformation.Stack, azs []string, boshClient Client) error {
	var subnets []SubnetInput
	for az := range azs {
		az++
		subnets = append(subnets, SubnetInput{
			AZ:             stack.Outputs[fmt.Sprintf("InternalSubnet%dAZ", az)],
			Subnet:         stack.Outputs[fmt.Sprintf("InternalSubnet%dName", az)],
			CIDR:           stack.Outputs[fmt.Sprintf("InternalSubnet%dCIDR", az)],
			SecurityGroups: []string{stack.Outputs["InternalSecurityGroup"]},
		})
	}

	cloudConfigInput := CloudConfigInput{
		AZs:     azs,
		Subnets: subnets,
		LBs:     c.populateLBs(stack),
	}

	c.logger.Step("generating cloud config")
	cloudConfig, err := c.generator.Generate(cloudConfigInput)
	if err != nil {
		return err
	}

	yaml, err := candiedyaml.Marshal(cloudConfig)
	if err != nil {
		return err
	}

	c.logger.Step("applying cloud config")
	if err := boshClient.UpdateCloudConfig(yaml); err != nil {
		return err
	}

	return nil
}

func (CloudConfigurator) populateLBs(stack cloudformation.Stack) []LoadBalancerExtension {
	lbs := []LoadBalancerExtension{}

	if value := stack.Outputs["ConcourseLoadBalancer"]; value != "" {
		lbs = append(lbs, LoadBalancerExtension{
			Name:    "lb",
			ELBName: value,
			SecurityGroups: []string{
				stack.Outputs["ConcourseInternalSecurityGroup"],
				stack.Outputs["InternalSecurityGroup"],
			},
		})
	}

	if value := stack.Outputs["CFRouterLoadBalancer"]; value != "" {
		lbs = append(lbs, LoadBalancerExtension{
			Name:    "router-lb",
			ELBName: value,
			SecurityGroups: []string{
				stack.Outputs["CFRouterInternalSecurityGroup"],
				stack.Outputs["InternalSecurityGroup"],
			},
		})
	}

	if value := stack.Outputs["CFSSHProxyLoadBalancer"]; value != "" {
		lbs = append(lbs, LoadBalancerExtension{
			Name:    "ssh-proxy-lb",
			ELBName: value,
			SecurityGroups: []string{
				stack.Outputs["CFSSHProxyInternalSecurityGroup"],
				stack.Outputs["InternalSecurityGroup"],
			},
		})
	}

	return lbs
}

repository: vfonsecapv/bosh-bootloader

repo_name: vfonsecapv/bosh-bootloader


text:
#.rst:
# clapack config for vcpkg
# ------------
#
# Find the clapack includes and library.
#
# Result Variables
# ^^^^^^^^^^^^^^^^
#
# This script defines the following variables:
#
# ``CLAPACK_FOUND``
#   True if clapack library found
#
# ``CLAPACK_VERSION``
#   Containing the clapack version tag (manually defined)
#
# ``CLAPACK_INCLUDE_DIR``
#   Location of clapack headers
#
# ``CLAPACK_LIBRARY``
#   List of libraries to link with when using clapack
#
# Result Targets
# ^^^^^^^^^^^^^^
#
# This script defines the following targets:
#
# ``clapack::clapack``
#   Target to use clapack
#
# Compatibility Variables
# ^^^^^^^^^^^^^^^^^^^^^^^
#
# This script defines the following variables for compatibility reasons:
#
# ``F2C_FOUND``
#   True if f2c (fortran-to-c wrap layer) library found
#
# ``F2C_INCLUDE_DIR``
#   Location of clapack headers
#
# ``F2C_LIBRARY``
#   Library containing the fortran-to-c wrap layer, necessary for clapack and automatically included when used
#
# ``LAPACK_FOUND``
#   True if clapack library found
#
# ``LAPACK_VERSION``
#   Containing the clapack version tag (manually defined)
#
# ``LAPACK_INCLUDE_DIR``
#   Location of clapack headers
#
# ``LAPACK_LIBRARY``
#   List of libraries to link with when using clapack
#
# Compatibility Targets
# ^^^^^^^^^^^^^^
#
# This script defines the following targets for compatibility reasons:
#
# ``lapack``
#   Target to use lapack

include(${CMAKE_ROOT}/Modules/SelectLibraryConfigurations.cmake)
include(${CMAKE_ROOT}/Modules/CheckSymbolExists.cmake)
include(${CMAKE_ROOT}/Modules/FindPackageHandleStandardArgs.cmake)

set(CLAPACK_VERSION "3.2.1")

if(UNIX)
  find_library(ADDITIONAL_LAPACK_LIBRARY m)
endif()

if(NOT F2C_LIBRARY)
    find_library(F2C_LIBRARY_RELEASE NAMES f2c libf2c)
    find_library(F2C_LIBRARY_DEBUG NAMES f2cd libf2cd)
    list(APPEND F2C_LIBRARY_RELEASE ${ADDITIONAL_LAPACK_LIBRARY})
    list(APPEND F2C_LIBRARY_DEBUG ${ADDITIONAL_LAPACK_LIBRARY})
    select_library_configurations(F2C)
endif()

find_package(BLAS)

if(NOT LAPACK_LIBRARY)
    find_library(LAPACK_LIBRARY_RELEASE NAMES lapack)
    find_library(LAPACK_LIBRARY_DEBUG NAMES lapackd)
    list(APPEND LAPACK_LIBRARY_RELEASE ${F2C_LIBRARY_RELEASE})
    list(APPEND LAPACK_LIBRARY_DEBUG ${F2C_LIBRARY_DEBUG})
    select_library_configurations(LAPACK)
endif()

list(APPEND LAPACK_LIBRARY ${BLAS_LIBRARIES})

set(F2C_LIBRARIES "${F2C_LIBRARY}" CACHE STRING "" FORCE)
set(LAPACK_VERSION "${CLAPACK_VERSION}" CACHE STRING "" FORCE)
set(LAPACK_LIBRARIES "${LAPACK_LIBRARY}" CACHE STRING "" FORCE)
set(CLAPACK_LIBRARY "${LAPACK_LIBRARY}" CACHE STRING "" FORCE)
set(CLAPACK_LIBRARIES "${LAPACK_LIBRARY}" CACHE STRING "" FORCE)

if(NOT F2C_INCLUDE_DIR)
  find_path(F2C_INCLUDE_DIR NAMES f2c.h)
endif()

if(NOT LAPACK_INCLUDE_DIR)
  find_path(LAPACK_INCLUDE_DIR NAMES clapack.h)
endif()

list(APPEND LAPACK_INCLUDE_DIR ${F2C_INCLUDE_DIR})
set(LAPACK_INCLUDE_DIRS "${LAPACK_INCLUDE_DIR}" CACHE PATH "" FORCE)
set(CLAPACK_INCLUDE_DIR "${LAPACK_INCLUDE_DIR}" CACHE PATH "" FORCE)
set(CLAPACK_INCLUDE_DIRS "${LAPACK_INCLUDE_DIR}" CACHE PATH "" FORCE)
set(F2C_INCLUDE_DIRS "${F2C_INCLUDE_DIR}" CACHE PATH "" FORCE)

if(WIN32)
  string( REPLACE ".lib" ".dll" LAPACK_LIBRARY_RELEASE_DLL "${LAPACK_LIBRARY_RELEASE}" )
  string( REPLACE ".lib" ".dll" LAPACK_LIBRARY_DEBUG_DLL   "${LAPACK_LIBRARY_DEBUG}" )
  string( REPLACE ".lib" ".dll" F2C_LIBRARY_RELEASE_DLL    "${F2C_LIBRARY_RELEASE}" )
  string( REPLACE ".lib" ".dll" F2C_LIBRARY_DEBUG_DLL      "${F2C_LIBRARY_DEBUG}" )
endif()

find_package_handle_standard_args(CLAPACK DEFAULT_MSG CLAPACK_LIBRARY CLAPACK_INCLUDE_DIR)
mark_as_advanced(CLAPACK_INCLUDE_DIR CLAPACK_LIBRARY)

find_package_handle_standard_args(LAPACK  DEFAULT_MSG LAPACK_LIBRARY LAPACK_INCLUDE_DIR)
mark_as_advanced(LAPACK_INCLUDE_DIR LAPACK_LIBRARY)

find_package_handle_standard_args(F2C     DEFAULT_MSG F2C_LIBRARY F2C_INCLUDE_DIR)
mark_as_advanced(F2C_INCLUDE_DIR F2C_LIBRARY)

#TARGETS
if( CLAPACK_FOUND AND NOT TARGET clapack::clapack )
  if( EXISTS "${LAPACK_LIBRARY_RELEASE_DLL}" )
    add_library( clapack::clapack      SHARED IMPORTED )
    set_target_properties( clapack::clapack PROPERTIES
      IMPORTED_LOCATION_RELEASE         "${LAPACK_LIBRARY_RELEASE_DLL}"
      IMPORTED_IMPLIB                   "${LAPACK_LIBRARY_RELEASE}"
      INTERFACE_INCLUDE_DIRECTORIES     "${LAPACK_INCLUDE_DIR}"
      IMPORTED_CONFIGURATIONS           Release
      IMPORTED_LINK_INTERFACE_LANGUAGES "C" )
    if( EXISTS "${LAPACK_LIBRARY_DEBUG_DLL}" )
      set_property( TARGET clapack::clapack APPEND PROPERTY IMPORTED_CONFIGURATIONS Debug )
      set_target_properties( clapack::clapack PROPERTIES
        IMPORTED_LOCATION_DEBUG           "${LAPACK_LIBRARY_DEBUG_DLL}"
        IMPORTED_IMPLIB_DEBUG             "${LAPACK_LIBRARY_DEBUG}" )
    endif()
  else()
    add_library( clapack::clapack      UNKNOWN IMPORTED )
    set_target_properties( clapack::clapack PROPERTIES
      IMPORTED_LOCATION_RELEASE         "${LAPACK_LIBRARY_RELEASE}"
      INTERFACE_INCLUDE_DIRECTORIES     "${LAPACK_INCLUDE_DIR}"
      IMPORTED_CONFIGURATIONS           Release
      IMPORTED_LINK_INTERFACE_LANGUAGES "C" )
    if( EXISTS "${LAPACK_LIBRARY_DEBUG}" )
      set_property( TARGET clapack::clapack APPEND PROPERTY IMPORTED_CONFIGURATIONS Debug )
      set_target_properties( clapack::clapack PROPERTIES
        IMPORTED_LOCATION_DEBUG           "${LAPACK_LIBRARY_DEBUG}" )
    endif()
  endif()
endif()

if( CLAPACK_FOUND AND NOT TARGET lapack )
  if( EXISTS "${LAPACK_LIBRARY_RELEASE_DLL}" )
    add_library( lapack      SHARED IMPORTED )
    set_target_properties( lapack PROPERTIES
      IMPORTED_LOCATION_RELEASE         "${LAPACK_LIBRARY_RELEASE_DLL}"
      IMPORTED_IMPLIB                   "${LAPACK_LIBRARY_RELEASE}"
      INTERFACE_INCLUDE_DIRECTORIES     "${LAPACK_INCLUDE_DIR}"
      IMPORTED_CONFIGURATIONS           Release
      IMPORTED_LINK_INTERFACE_LANGUAGES "C" )
    if( EXISTS "${LAPACK_LIBRARY_DEBUG_DLL}" )
      set_property( TARGET lapack APPEND PROPERTY IMPORTED_CONFIGURATIONS Debug )
      set_target_properties( lapack PROPERTIES
        IMPORTED_LOCATION_DEBUG           "${LAPACK_LIBRARY_DEBUG_DLL}"
        IMPORTED_IMPLIB_DEBUG             "${LAPACK_LIBRARY_DEBUG}" )
    endif()
  else()
    add_library( lapack      UNKNOWN IMPORTED )
    set_target_properties( lapack PROPERTIES
      IMPORTED_LOCATION_RELEASE         "${LAPACK_LIBRARY_RELEASE}"
      INTERFACE_INCLUDE_DIRECTORIES     "${LAPACK_INCLUDE_DIR}"
      IMPORTED_CONFIGURATIONS           Release
      IMPORTED_LINK_INTERFACE_LANGUAGES "C" )
    if( EXISTS "${LAPACK_LIBRARY_DEBUG}" )
      set_property( TARGET lapack APPEND PROPERTY IMPORTED_CONFIGURATIONS Debug )
      set_target_properties( lapack PROPERTIES
        IMPORTED_LOCATION_DEBUG           "${LAPACK_LIBRARY_DEBUG}" )
    endif()
  endif()
endif()

set(LAPACK_LIBRARY "${LAPACK_LIBRARY}" CACHE STRING "" FORCE)
set(F2C_LIBRARY "${F2C_LIBRARY}" CACHE STRING "" FORCE)
set(LAPACK_LIBRARY_RELEASE "${LAPACK_LIBRARY_RELEASE}" CACHE STRING "" FORCE)
set(LAPACK_LIBRARY_DEBUG "${LAPACK_LIBRARY_DEBUG}" CACHE STRING "" FORCE)
set(F2C_LIBRARY_RELEASE "${F2C_LIBRARY_RELEASE}" CACHE STRING "" FORCE)
set(F2C_LIBRARY_DEBUG "${F2C_LIBRARY_DEBUG}" CACHE STRING "" FORCE)

repository: NulAsh/vcpkg

repo_name: NulAsh/vcpkg

gha_license_id: NOASSERTION

extension: cmake


text:
package webserver

import "net/http"

//HttpServer defines the interface to server HTTP request
type HttpServer interface {
	Handle(pattern string, handler http.Handler)
	ListenAndServe(addr string, handler http.Handler) error
}

//HttpServerWrapper is a wrapper around the http package
type HttpServerWrapper struct {
}

//Handle is a wrapper around the same method from http package
func (server *HttpServerWrapper) Handle(pattern string, handler http.Handler) {
	http.Handle(pattern, handler)
}

//ListenAndServe is a wrapper around the same method from http package
func (server *HttpServerWrapper) ListenAndServe(addr string, handler http.Handler) error {
	return http.ListenAndServe(addr, handler)
}


text:
// Copyright 2014 The Cayley Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package path

import "github.com/google/cayley/graph"

type morphism struct {
	Name     string
	Reversal func() morphism
	Apply    graph.ApplyMorphism
	tags     []string
}

// Path represents either a morphism (a pre-defined path stored for later use),
// or a concrete path, consisting of a morphism and an underlying QuadStore.
type Path struct {
	stack []morphism
	qs    graph.QuadStore // Optionally. A nil qs is equivalent to a morphism.
}

// IsMorphism returns whether this Path is a morphism.
func (p *Path) IsMorphism() bool { return p.qs == nil }

// StartMorphism creates a new Path with no underlying QuadStore.
func StartMorphism(nodes ...string) *Path {
	return StartPath(nil, nodes...)
}

// StartPath creates a new Path from a set of nodes and an underlying QuadStore.
func StartPath(qs graph.QuadStore, nodes ...string) *Path {
	return &Path{
		stack: []morphism{
			isMorphism(nodes...),
		},
		qs: qs,
	}
}

func PathFromIterator(qs graph.QuadStore, it graph.Iterator) *Path {
	return &Path{
		stack: []morphism{
			iteratorMorphism(it),
		},
		qs: qs,
	}
}

// NewPath creates a new, empty Path.
func NewPath(qs graph.QuadStore) *Path {
	return &Path{
		qs: qs,
	}
}

// Reverse returns a new Path that is the reverse of the current one.
func (p *Path) Reverse() *Path {
	newPath := NewPath(p.qs)
	for i := len(p.stack) - 1; i >= 0; i-- {
		newPath.stack = append(newPath.stack, p.stack[i].Reversal())
	}
	return newPath
}

// Is declares that the current nodes in this path are only the nodes
// passed as arguments.
func (p *Path) Is(nodes ...string) *Path {
	p.stack = append(p.stack, isMorphism(nodes...))
	return p
}

// Tag adds tag strings to the nodes at this point in the path for each result
// path in the set.
func (p *Path) Tag(tags ...string) *Path {
	p.stack = append(p.stack, tagMorphism(tags...))
	return p
}

// Out updates this Path to represent the nodes that are adjacent to the
// current nodes, via the given outbound predicate.
//
// For example:
//  // Returns the list of nodes that "A" follows.
//  //
//  // Will return []string{"B"} if there is a predicate (edge) from "A"
//  // to "B" labelled "follows".
//  StartPath(qs, "A").Out("follows")
func (p *Path) Out(via ...interface{}) *Path {
	p.stack = append(p.stack, outMorphism(via...))
	return p
}

// In updates this Path to represent the nodes that are adjacent to the
// current nodes, via the given inbound predicate.
//
// For example:
//  // Return the list of nodes that follow "B".
//  //
//  // Will return []string{"A", "C", "D"} if there are the appropriate
//  // edges from those nodes to "B" labelled "follows".
//  StartPath(qs, "B").In("follows")
func (p *Path) In(via ...interface{}) *Path {
	p.stack = append(p.stack, inMorphism(via...))
	return p
}

// And updates the current Path to represent the nodes that match both the
// current Path so far, and the given Path.
func (p *Path) And(path *Path) *Path {
	p.stack = append(p.stack, andMorphism(path))
	return p
}

// And updates the current Path to represent the nodes that match either the
// current Path so far, or the given Path.
func (p *Path) Or(path *Path) *Path {
	p.stack = append(p.stack, orMorphism(path))
	return p
}

// Except updates the current Path to represent the all of the current nodes
// except those in the supplied Path.
//
// For example:
//  // Will return []string{"B"}
//  StartPath(qs, "A", "B").Except(StartPath(qs, "A"))
func (p *Path) Except(path *Path) *Path {
	p.stack = append(p.stack, exceptMorphism(path))
	return p
}

// Follow allows you to stitch two paths together. The resulting path will start
// from where the first path left off and continue iterating down the path given.
func (p *Path) Follow(path *Path) *Path {
	p.stack = append(p.stack, followMorphism(path))
	return p
}

// FollowReverse is the same as follow, except it will iterate backwards up the
// path given as argument.
func (p *Path) FollowReverse(path *Path) *Path {
	p.stack = append(p.stack, followMorphism(path.Reverse()))
	return p
}

// Save will, from the current nodes in the path, retrieve the node
// one linkage away (given by either a path or a predicate), add the given
// tag, and propagate that to the result set.
//
// For example:
// // Will return []map[string]string{{"social_status: "cool"}}
// StartPath(qs, "B").Save("status", "social_status"
func (p *Path) Save(via interface{}, tag string) *Path {
	p.stack = append(p.stack, saveMorphism(via, tag))
	return p
}

// SaveReverse is the same as Save, only in the reverse direction
// (the subject of the linkage should be tagged, instead of the object).
func (p *Path) SaveReverse(via interface{}, tag string) *Path {
	p.stack = append(p.stack, saveReverseMorphism(via, tag))
	return p
}

// Has limits the paths to be ones where the current nodes have some linkage
// to some known node.
func (p *Path) Has(via interface{}, nodes ...string) *Path {
	p.stack = append(p.stack, hasMorphism(via, nodes...))
	return p
}

// BuildIterator returns an iterator from this given Path.  Note that you must
// call this with a full path (not a morphism), since a morphism does not have
// the ability to fetch the underlying quads.  This function will panic if
// called with a morphism (i.e. if p.IsMorphism() is true).
func (p *Path) BuildIterator() graph.Iterator {
	if p.IsMorphism() {
		panic("Building an iterator from a morphism. Bind a QuadStore with BuildIteratorOn(qs)")
	}
	return p.BuildIteratorOn(p.qs)
}

// BuildIteratorOn will return an iterator for this path on the given QuadStore.
func (p *Path) BuildIteratorOn(qs graph.QuadStore) graph.Iterator {
	return p.Morphism()(qs, qs.NodesAllIterator())
}

// Morphism returns the morphism of this path.  The returned value is a
// function that, when given a QuadStore and an existing Iterator, will
// return a new Iterator that yields the subset of values from the existing
// iterator matched by the current Path.
func (p *Path) Morphism() graph.ApplyMorphism {
	return func(qs graph.QuadStore, it graph.Iterator) graph.Iterator {
		i := it.Clone()
		for _, m := range p.stack {
			i = m.Apply(qs, i)
		}
		return i
	}
}

repository: bmatsuo/cayley

repo_name: bmatsuo/cayley