text:
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: filesystem/watch.proto

package filesystem // import "github.com/havoc-io/mutagen/pkg/filesystem"

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

// WatchMode specifies the mode for filesystem watching.
type WatchMode int32

const (
	// WatchMode_WatchDefault represents an unspecified watch mode. It should be
	// converted to one of the following values based on the desired default
	// behavior.
	WatchMode_WatchDefault WatchMode = 0
	// WatchMode_WatchPortable specifies that native recursive watching should
	// be used to monitor paths on systems that support it if those paths fall
	// under the home directory. In these cases, a watch on the entire home
	// directory is established and filtered for events pertaining to the
	// specified path. On all other systems and for all other paths, poll-based
	// watching is used.
	WatchMode_WatchPortable WatchMode = 1
	// WatchMode_WatchForcePoll specifies that only poll-based watching should
	// be used.
	WatchMode_WatchForcePoll WatchMode = 2
)

var WatchMode_name = map[int32]string{
	0: "WatchDefault",
	1: "WatchPortable",
	2: "WatchForcePoll",
}
var WatchMode_value = map[string]int32{
	"WatchDefault":   0,
	"WatchPortable":  1,
	"WatchForcePoll": 2,
}

func (x WatchMode) String() string {
	return proto.EnumName(WatchMode_name, int32(x))
}
func (WatchMode) EnumDescriptor() ([]byte, []int) {
	return fileDescriptor_watch_1d03fb588bc80a09, []int{0}
}

func init() {
	proto.RegisterEnum("filesystem.WatchMode", WatchMode_name, WatchMode_value)
}

func init() { proto.RegisterFile("filesystem/watch.proto", fileDescriptor_watch_1d03fb588bc80a09) }

var fileDescriptor_watch_1d03fb588bc80a09 = []byte{
	// 154 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4b, 0xcb, 0xcc, 0x49,
	0x2d, 0xae, 0x2c, 0x2e, 0x49, 0xcd, 0xd5, 0x2f, 0x4f, 0x2c, 0x49, 0xce, 0xd0, 0x2b, 0x28, 0xca,
	0x2f, 0xc9, 0x17, 0xe2, 0x42, 0x88, 0x6b, 0xb9, 0x70, 0x71, 0x86, 0x83, 0xa4, 0x7c, 0xf3, 0x53,
	0x52, 0x85, 0x04, 0xb8, 0x78, 0xc0, 0x1c, 0x97, 0xd4, 0xb4, 0xc4, 0xd2, 0x9c, 0x12, 0x01, 0x06,
	0x21, 0x41, 0x2e, 0x5e, 0xb0, 0x48, 0x40, 0x7e, 0x51, 0x49, 0x62, 0x52, 0x4e, 0xaa, 0x00, 0xa3,
	0x90, 0x10, 0x17, 0x1f, 0x58, 0xc8, 0x2d, 0xbf, 0x28, 0x39, 0x35, 0x20, 0x3f, 0x27, 0x47, 0x80,
	0xc9, 0x49, 0x27, 0x4a, 0x2b, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x3f,
	0x23, 0xb1, 0x2c, 0x3f, 0x59, 0x37, 0x33, 0x5f, 0x3f, 0xb7, 0xb4, 0x24, 0x31, 0x3d, 0x35, 0x4f,
	0xbf, 0x20, 0x3b, 0x5d, 0x1f, 0x61, 0x67, 0x12, 0x1b, 0xd8, 0x19, 0xc6, 0x80, 0x00, 0x00, 0x00,
	0xff, 0xff, 0x02, 0x8c, 0x88, 0xc2, 0xa0, 0x00, 0x00, 0x00,
}

repository: Toilal/mutagen

repo_name: Toilal/mutagen


text:
package hostdb

import (
	"io/ioutil"
	"os"
	"testing"

	"github.com/NebulousLabs/Sia/build"
	"github.com/NebulousLabs/Sia/modules"
	"github.com/NebulousLabs/Sia/modules/renter/hostdb/hosttree"
	"github.com/NebulousLabs/Sia/persist"
)

// bareHostDB returns a HostDB with its fields initialized, but without any
// dependencies or scanning threads. It is only intended for use in unit tests.
func bareHostDB() *HostDB {
	hdb := &HostDB{
		log: persist.NewLogger(ioutil.Discard),

		activeHosts: make(map[modules.NetAddress]*hostEntry),
		allHosts:    make(map[modules.NetAddress]*hostEntry),
		scanPool:    make(chan *hostEntry, scanPoolSize),
	}
	hdb.hostTree = hosttree.New(hdb.calculateHostWeight)
	return hdb
}

// newStub is used to test the New function. It implements all of the hostdb's
// dependencies.
type newStub struct{}

// consensus set stubs
func (newStub) ConsensusSetSubscribe(modules.ConsensusSetSubscriber, modules.ConsensusChangeID) error {
	return nil
}

// TestNew tests the New function.
func TestNew(t *testing.T) {
	// Using a stub implementation of the dependencies is fine, as long as its
	// non-nil.
	var stub newStub
	dir := build.TempDir("hostdb", "TestNew")

	// Sane values.
	_, err := New(stub, dir)
	if err != nil {
		t.Fatalf("expected nil, got %v", err)
	}

	// Nil consensus set.
	_, err = New(nil, dir)
	if err != errNilCS {
		t.Fatalf("expected %v, got %v", errNilCS, err)
	}

	// Bad persistDir.
	_, err = New(stub, "")
	if !os.IsNotExist(err) {
		t.Fatalf("expected invalid directory, got %v", err)
	}
}

// TestRandomHosts tests the hostdb's exported RandomHosts method.
func TestRandomHosts(t *testing.T) {
	hdb := bareHostDB()

	var entries []modules.HostDBEntry
	nentries := 10
	for i := 0; i < nentries; i++ {
		entry := makeHostDBEntry()
		entry.NetAddress = fakeAddr(uint8(i))
		entries = append(entries, entry)
		hdb.activeHosts[entry.NetAddress] = &hostEntry{HostDBEntry: entry}
		hdb.hostTree.Insert(entry)
	}

	hosts := hdb.RandomHosts(nentries, nil)
	if len(hosts) != nentries {
		t.Fatalf("RandomHosts returned fewer entries than expected. got %v wanted %v\n", len(hosts), nentries)
	}

	hosts = hdb.RandomHosts(nentries/2, nil)
	if len(hosts) != nentries/2 {
		t.Fatalf("RandomHosts returned fewer entries than expected. got %v wanted %v\n", len(hosts), nentries/2)
	}

	// ignore every other entry and verify that the exclude list worked correctly
	var exclude []modules.HostDBEntry
	for idx, entry := range entries {
		if idx%2 == 0 {
			exclude = append(exclude, entry)
		}
	}

	var exclusionAddresses []modules.NetAddress
	for _, exclusionHost := range exclude {
		exclusionAddresses = append(exclusionAddresses, exclusionHost.NetAddress)
	}

	hosts = hdb.RandomHosts(nentries, exclusionAddresses)
	if len(hosts) != len(entries)/2 {
		t.Fatalf("hosts had wrong length after passing exclusion slice. got %v wanted %v\n", len(hosts), len(entries)/2)
	}
	for _, host := range hosts {
		for _, excluded := range exclude {
			if string(host.PublicKey.Key) == string(excluded.PublicKey.Key) {
				t.Fatal("RandomHosts returned an excluded host!")
			}
		}
	}
}

license: MIT

repository: ondrocks/Sia

license_type: permissive

repo_name: ondrocks/Sia

branch_name: refs/heads/master

extension: go


text:
// Autogenerated with msg-import, do not edit.
package geometry_msgs

import (
	"github.com/aler9/goroslib/msgs"
)

type Inertia struct {
	msgs.Package `ros:"geometry_msgs"`
	M            float64
	Com          Vector3
	Ixx          float64
	Ixy          float64
	Ixz          float64
	Iyy          float64
	Iyz          float64
	Izz          float64
}

repository: knuesel/goroslib

repo_name: knuesel/goroslib

gha_license_id: MIT


text:
SUMMARY = "Andri's Main Loop"
DESCRIPTION = "Andri's Main Loop"
HOMEPAGE = "https://github.com/any1/aml"
LICENSE = "ISC"
LIC_FILES_CHKSUM = "file://COPYING;md5=e6f3cfaa39204b96e14b68b9d50d3e4e"

SRC_URI = "git://github.com/any1/aml;branch=master;protocol=https"

SRCREV = "b83f3576ce4187d9285f06e9066ef43a691464d4"

PV = "0.3.0+git${SRCPV}"

S = "${WORKDIR}/git"

PACKAGECONFIG ??= ""
PACKAGECONFIG[examples] = "-Dexamples=true,-Dexamples=false"

PACKAGE_BEFORE_PN += "${PN}-examples"
ALLOW_EMPTY:${PN}-examples = "1"
FILES:${PN}-examples = "${bindir}"

inherit meson pkgconfig

AML_EXAMPLES = "ticker nested-ticker reader"

do_install:append () {
	if ${@bb.utils.contains('PACKAGECONFIG', 'examples', 'true', 'false', d)}; then
		install -d ${D}${bindir}
		for bin in ${AML_EXAMPLES}; do
			install -m 0755 ${B}/examples/$bin ${D}${bindir}
		done
	fi
}

BBCLASSEXTEND = "native"

repository: YoeDistro/meta-openembedded

repo_name: YoeDistro/meta-openembedded

extension: bb


text:
package main

import (
	"context"
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"text/template"
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	_ "k8s.io/api/admissionregistration/v1alpha1"
	"k8s.io/apimachinery/pkg/runtime"
	_ "k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/watch"
	_ "k8s.io/apimachinery/pkg/watch"
	"k8s.io/client-go/kubernetes"
	_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"
	_ "k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"

	"github.com/dparrish/kube-phpipam/phpipam"
	"github.com/spotahome/kooper/log"
	"github.com/spotahome/kooper/operator/controller"
	"github.com/spotahome/kooper/operator/handler"
	"github.com/spotahome/kooper/operator/retrieve"
	"gopkg.in/yaml.v2"
)

const (
	DefaultNameTemplate        = "{{.Name}}"
	DefaultDescriptionTemplate = "{{.Spec.Type}} in namespace {{.Namespace}}"
)

var (
	configFile = flag.String("config", "config.yaml", "Path to configuration YAML file")

	subnetCache = make(map[string]*phpipam.Subnet)
	ipCache     = make(map[string]string)
)

func getSubnet(client *phpipam.Client, cidr string) (*phpipam.Subnet, error) {
	if x, ok := subnetCache[cidr]; ok {
		return x, nil
	}
	var subnets phpipam.SubnetsResponse
	if err := client.GET("subnets/cidr/"+cidr, &subnets); err != nil {
		return nil, err
	}
	if len(subnets.Data) == 0 {
		return nil, fmt.Errorf("no subnet found matching CIDR %s", cidr)
	}
	if len(subnets.Data) > 1 {
		return nil, fmt.Errorf("multiple subnet found matching CIDR %s", cidr)
	}
	subnetCache[cidr] = &subnets.Data[0]
	return &subnets.Data[0], nil
}

func createIP(client *phpipam.Client, subnet, ip, hostname, description string) error {
	var out phpipam.IPAddressPatchResponse
	url := fmt.Sprintf("addresses/")
	if err := client.POST(url, map[string]interface{}{
		"ip":          ip,
		"hostname":    hostname,
		"subnetId":    subnet,
		"note":        "Added by kube-phpipam",
		"description": description,
	}, &out); err != nil {
		return fmt.Errorf("error adding IP address %q: %v", ip, err)
	}
	if out.Code < 200 || out.Code > 299 {
		return fmt.Errorf("Error from phpIPAM adding IP address %q: %v", ip, out.Message)
	}
	ipCache[ip] = hostname
	return nil
}

func getIP(client *phpipam.Client, ip string) (*phpipam.IPAddress, error) {
	var res phpipam.IPAddressResponse
	if err := client.GET(fmt.Sprintf("addresses/search/%s/", ip), &res); err != nil {
		return nil, err
	}
	if res.Code != 200 {
		return nil, fmt.Errorf("%s", res.Message)
	}
	if len(res.Data) == 0 {
		return nil, nil
	}
	if len(res.Data) > 1 {
		return nil, fmt.Errorf("multiple IPs found matching %s", ip)
	}
	return &res.Data[0], nil
}

func setHostname(client *phpipam.Client, id, ip, hostname, description string) error {
	var out phpipam.IPAddressPatchResponse
	url := fmt.Sprintf("addresses/%s/", id)
	if err := client.PATCH(url, map[string]string{
		"hostname":    hostname,
		"note":        "Added by kube-phpipam",
		"description": description,
	}, &out); err != nil {
		return err
	}
	if out.Code < 200 || out.Code > 299 {
		return fmt.Errorf("%s", out.Message)
	}
	ipCache[ip] = hostname
	return nil
}

func executeTemplate(t string, svc *corev1.Service) (string, error) {
	tmpl, err := template.New("hostname").Parse(t)
	if err != nil {
		return "", fmt.Errorf("invalid template %q: %v", t, err)
	}
	var b strings.Builder
	if err := tmpl.Execute(&b, svc); err != nil {
		return "", fmt.Errorf("unable to execute template %q: %v", t, err)
	}
	return b.String(), nil
}

func main() {
	flag.Parse()
	log := &log.Std{}
	cfg, err := ioutil.ReadFile(*configFile)
	if err != nil {
		log.Errorf("Unable to read configuration file %s: %v", *configFile, err)
		os.Exit(1)
	}
	var config Config
	if err := yaml.Unmarshal(cfg, &config); err != nil {
		log.Errorf("Unable to read configuration file %s: %v", *configFile, err)
		os.Exit(1)
	}

	client, err := phpipam.NewClient(context.Background(), config.PHPIpam.Host, config.PHPIpam.AppID, config.PHPIpam.Username, config.PHPIpam.Password)
	if err != nil {
		log.Errorf("%v", err)
		os.Exit(1)
	}
	defer client.Close()

	k8scfg, err := rest.InClusterConfig()
	if err != nil {
		// No in cluster? letr's try locally
		kubehome := filepath.Join(homedir.HomeDir(), ".kube", "config")
		k8scfg, err = clientcmd.BuildConfigFromFlags("", kubehome)
		if err != nil {
			log.Errorf("error loading kubernetes configuration: %s", err)
			os.Exit(1)
		}
	}
	k8scli, err := kubernetes.NewForConfig(k8scfg)
	if err != nil {
		log.Errorf("error creating kubernetes client: %s", err)
		os.Exit(1)
	}

	retriever := &retrieve.Resource{
		Object: &corev1.Service{},
		ListerWatcher: &cache.ListWatch{
			ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
				return k8scli.CoreV1().Services("").List(options)
			},
			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
				return k8scli.CoreV1().Services("").Watch(options)
			},
		},
	}

	// Our domain logic that will print every add/sync/update and delete event we .
	hand := &handler.HandlerFunc{
		AddFunc: func(_ context.Context, obj runtime.Object) error {
			svc := obj.(*corev1.Service)
			log.Infof("Service added: %s/%s", svc.Namespace, svc.Name)

			for _, subnet := range config.Subnets {
				nameTemplate := subnet.NameTemplate
				if nameTemplate == "" {
					nameTemplate = DefaultNameTemplate
				}
				hostname, err := executeTemplate(nameTemplate, svc)
				if err != nil {
					log.Errorf("%v", err)
					continue
				}

				descriptionTemplate := subnet.DescriptionTemplate
				if descriptionTemplate == "" {
					descriptionTemplate = DefaultDescriptionTemplate
				}
				description, err := executeTemplate(descriptionTemplate, svc)
				if err != nil {
					log.Errorf("%v", err)
					continue
				}

				/*
					if l, ok := svc.Annotations["metallb.universe.tf/allow-shared-ip"]; ok {
						hostname = fmt.Sprintf("%s/%s", svc.Namespace, l)
					}
				*/

				if subnet.Namespace != "" && svc.Namespace != subnet.Namespace {
					//log.Infof("skipping because of wrong namespace")
					continue
				}
				if subnet.Type != "" && svc.Spec.Type != subnet.Type {
					//log.Infof("skipping because of wrong type")
					continue
				}
				if subnet.Regex != "" {
					re, err := regexp.Compile(subnet.Regex)
					if err != nil {
						log.Errorf("Error compiling regex %q for subnet: %v", subnet.Regex, err)
						continue
					}
					if !re.MatchString(svc.Name) {
						//log.Infof("skipping because of regex")
						continue
					}
				}

				_, ipnet, err := net.ParseCIDR(subnet.CIDR)
				if err != nil {
					log.Errorf("Config subnet contains invalid CIDR address %q: %v", subnet.CIDR, err)
					continue
				}

				ipamSubnet, err := getSubnet(client, subnet.CIDR)
				if err != nil {
					log.Errorf("Subnet matching %s not found in phpIPAM: %v", subnet.CIDR, err)
					continue
				}
				//log.Infof("phpIPAM subnet: %+v", ipamSubnet)

				var ips []string
				appendip := func(ip string) {
					if ip != "" && ipnet.Contains(net.ParseIP(ip)) {
						ips = append(ips, ip)
					}
				}
				appendip(svc.Spec.LoadBalancerIP)
				appendip(svc.Spec.ClusterIP)
				for _, ip := range svc.Spec.ExternalIPs {
					appendip(ip)
				}

				for _, ip := range ips {
					var res phpipam.IPAddressResponse
					url := fmt.Sprintf("addresses/search/%s/", ip)
					//log.Infof("Looking for phpipam matching address: %s", url)
					if err := client.GET(url, &res); err != nil {
						log.Errorf("%v", err)
						continue
					}
					if res.Code != 200 {
						log.Infof("IP address %s not found in phpIPAM, adding to subnet %s with hostname %s", ip, ipamSubnet.ID, hostname)
						if err := createIP(client, ipamSubnet.ID, ip, hostname, description); err != nil {
							log.Errorf("Error creating IP in phpIPAM: %v", err)
						}
						continue
					}

					var change bool
					for _, foundIP := range res.Data {
						if foundIP.Hostname == nil {
							change = true
							break
						}
						if *foundIP.Hostname != hostname {
							change = true
							break
						}

						var fd string
						if foundIP.Description != nil {
							fd = *foundIP.Description
						}
						if description != fd {
							change = true
						}
					}
					if !change {
						//log.Infof("IP %s already has the right allocation in phpipam", ip)
						ipCache[ip] = hostname
						continue
					}

					if err := setHostname(client, res.Data[0].ID, ip, hostname, description); err != nil {
						log.Errorf("Error from phpIPAM patching IP address %s: %v", ip, err)
						continue
					}
				}
			}
			return nil
		},
		DeleteFunc: func(_ context.Context, s string) error {
			log.Infof("Service deleted: %s", s)
			for ip, name := range ipCache {
				if name != s {
					continue
				}
				log.Infof("Found existing IP cache for %s: %s", s, ip)

				ipamip, err := getIP(client, ip)
				if err != nil {
					log.Errorf("%v", err)
					continue
				}
				if ipamip == nil {
					// Does not exist, that's fine.
					continue
				}

				log.Infof("phpIPAM contains mapping for %s: %s", ip, ipamip.ID)
				var res phpipam.IPAddressDeleteResponse
				if err := client.DELETE(fmt.Sprintf("addresses/%s/", ipamip.ID), &res); err != nil {
					log.Errorf("Error deleting IP from phpIPAM: %v", err)
				}
				if res.Code < 200 || res.Code > 299 {
					log.Errorf("Error deleting IP from phpIPAM: %v", res.Message)
				}
				delete(ipCache, ip)
				break
			}
			return nil
		},
	}

	// Create the controller that will refresh every 30 seconds.
	ctrl := controller.New(&controller.Config{
		Name:              "kube-phpipam",
		ConcurrentWorkers: 1,
		ResyncInterval:    1 * time.Minute,
	}, hand, retriever, nil, nil, nil, log)

	// Start our controller.
	stopC := make(chan struct{})
	if err := ctrl.Run(stopC); err != nil {
		log.Errorf("error running controller: %s", err)
		os.Exit(1)
	}
	client.Close()
	<-client.Done
}

repository: fumitaka-m/kube-phpipam

repo_name: fumitaka-m/kube-phpipam


text:
@article{nori_12,
 author = {Francesco Nori and Bastien Berret and Luca Fiorio and Alberto Parmiggiani and Giulio Sandini},
 doi = {https://doi.org/10.3182/20120905-3-HR-2030.00175},
 issn = {1474-6670},
 journal = {IFAC Proceedings Volumes},
 note = {10th IFAC Symposium on Robot Control},
 number = {22},
 pages = {473 - 478},
 title = {Control of a single Degree of Freedom Noise Rejecting - Variable Impedance Actuator},
 url = {http://www.sciencedirect.com/science/article/pii/S1474667016336552},
 volume = {45},
 year = {2012}
}

repository: miggia/academic-kickstart

repo_name: miggia/academic-kickstart

extension: bib


text:
DESCRIPTION = "Sound configuration files provided by L4T"
L4T_DEB_COPYRIGHT_MD5 = "0a282b202b51eab090698fcda604cb76"

L4T_DEB_TRANSLATED_BPN = "nvidia-l4t-init"

require tegra-debian-libraries-common.inc

MAINSUM = "9a7b2a92b8900af7d47a6d1f9e2c3c00e6fe78184c0bd02a8edfa72dcd2fa74b"

do_install() {
    if [ -n "${TEGRA_AUDIO_DEVICE}" ]; then
        install -d ${D}${sysconfdir}
        install -m 0644 ${S}/etc/asound.conf.${TEGRA_AUDIO_DEVICE} ${D}${sysconfdir}/asound.conf
    fi

    install -d ${D}${datadir}/alsa/cards ${D}${datadir}/alsa/init/postinit
    install -m 0644 ${S}/usr/share/alsa/cards/*.conf ${D}${datadir}/alsa/cards/
    install -m 0644 ${S}/usr/share/alsa/init/postinit/* ${D}${datadir}/alsa/init/postinit/
}

FILES:${PN} = "${sysconfdir} ${datadir}/alsa"
PACKAGE_ARCH = "${MACHINE_ARCH}"

repository: SOL-Space-Operating-Linux/meta-tegra

repo_name: SOL-Space-Operating-Linux/meta-tegra

gha_language: BitBake


text:
package store

import (
	"context"
	"net"
	"time"
)

type ProxyStore interface {
	Save(ctx context.Context, proxy Proxy) error
	FindAll(ctx context.Context, page, pageSize int64) ([]Proxy, error)
	Close()
}

type Proxy struct {
	Addr    net.IP    `json:"addr"`
	Port    uint16    `json:"port"`
	Proto   string    `json:"proto"`
	Updated time.Time `json:"updated"`
}

repository: qjex/ursus

repo_name: qjex/ursus


text:
require u-boot-ti.inc

LIC_FILES_CHKSUM = "file://Licenses/README;md5=5a7450c57ffe5ae63fd732446b988025"

PR = "r11"

BRANCH = "ti-u-boot-2021.01"

SRCREV = "53e79d0e89f975eeb874366dd9a92f68b3a599d1"

repository: acrlinux/acrlinux-yocto

repo_name: acrlinux/acrlinux-yocto


text:
package commands

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"os"
	"path"
	"testing"

	"github.com/darcinc/afero"
	"github.com/darcinc/repository"
)

const testPubkey = `-----BEGIN RSA PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAziXOEOxPp01Kq2gtASVI
MkRJxtnDKh9n3xZL+mJYkh5IVUN6+OhSy5QYPif5pjomCR3qDsK5utTDZosNxVYu
M7Gc00DNlS4y4JxaTJzyzwm9izIWataQpFvqc2ou8tzVmZzaJQ+5YopRLU/biCOV
kjgeyGwpgZ762t+qRk9YIX7KXYwAXiw9X5/9CTKtRiJRLSj5ArHfmfESPZekp5I1
qM0TPn2HE7rqvU6IWMN5v4Q07LXJb0+IWrZ2Sh6oo29dWgEtJ0KbTU5jyb/1297N
XxArvnCfn5lSMu7Oie+no9Dgbo/cQ+vVoygbFS8qaIg32dFwmltznVY73DZymh2g
3QIDAQAB
-----END RSA PUBLIC KEY-----`

func createTestKeyFile(fs afero.Fs) {
	pk, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(err)
	}

	keybytes := x509.MarshalPKCS1PrivateKey(pk)
	file, err := fs.OpenFile(path.Join(repository.HomeDir(), "test.pem"), os.O_WRONLY|os.O_CREATE, 0600)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	file, err = fs.OpenFile(path.Join(repository.HomeDir(), "test3.pem"), os.O_WRONLY|os.O_CREATE, 0600)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	_, err = file.Write([]byte(testPubkey))
	if err != nil {
		panic(err)
	}

	err = pem.Encode(file, &pem.Block{Type: "PRIVATE KEY", Bytes: keybytes})
	if err != nil {
		panic(err)
	}

	keybytes, err = x509.MarshalPKIXPublicKey(&pk.PublicKey)
	if err != nil {
		panic(err)
	}
	file, err = fs.OpenFile(path.Join(repository.HomeDir(), "test2.pem"), os.O_WRONLY|os.O_CREATE, 0600)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	err = pem.Encode(file, &pem.Block{Type: "PUBLIC KEY", Bytes: keybytes})
	if err != nil {
		panic(err)
	}
}

func TestImportPrivateKey(t *testing.T) {
	fs := createFSWithKeystore(t)
	createTestKeyFile(fs)

	file, err := fs.Open(path.Join(repository.HomeDir(), "test.pem"))
	if err != nil {
		t.Fatalf("Unable to open test key file: %v", err)
	}
	defer file.Close()

	err = importKey(fs, "foo", "imported", file)
	if err != nil {
		t.Fatalf("Unable to import key: %v", err)
	}

	filename := repository.NamedKeystoreFile("foo")
	file, err = fs.Open(filename)
	if err != nil {
		t.Fatalf("Unale to open keystore file: %v", err)
	}
	defer file.Close()

	keystore, err := repository.OpenKeystore(file)
	if err != nil {
		t.Fatalf("Unable to read keystore file: %v", err)
	}

	_, ok := keystore.FindPrivateKey("imported")
	if !ok {
		t.Error("Failed to find testkey after import")
	}

}

func TestImportPublicKey(t *testing.T) {
	fs := createFSWithKeystore(t)
	createTestKeyFile(fs)

	file, err := fs.Open(path.Join(repository.HomeDir(), "test2.pem"))
	if err != nil {
		t.Fatalf("Unable to find public key test key: %v", err)
	}
	defer file.Close()

	err = importKey(fs, "foo", "imported2", file)
	if err != nil {
		t.Errorf("Failed to import public key: %v", err)
	}

	filename := repository.NamedKeystoreFile("foo")
	file, err = fs.Open(filename)
	if err != nil {
		t.Fatalf("Unale to open keystore file: %v", err)
	}
	defer file.Close()

	keystore, err := repository.OpenKeystore(file)
	if err != nil {
		t.Fatalf("Unable to read keystore file: %v", err)
	}

	_, ok := keystore.FindPublicKey("imported2")
	if !ok {
		t.Error("Failed to find imported2 after import")
	}
}

func TestImportSSHPublicKey(t *testing.T) {
	fs := createFSWithKeystore(t)
	createTestKeyFile(fs)

	file, err := fs.Open(path.Join(repository.HomeDir(), "test3.pem"))
	if err != nil {
		t.Fatalf("Unable to find public ssh key test key: %v", err)
	}
	defer file.Close()

	err = importKey(fs, "foo", "public-ssh", file)
	if err != nil {
		t.Errorf("Failed to import public key: %v", err)
	}

	filename := repository.NamedKeystoreFile("foo")
	file, err = fs.Open(filename)
	if err != nil {
		t.Fatalf("Unale to open keystore file: %v", err)
	}
	defer file.Close()

	keystore, err := repository.OpenKeystore(file)
	if err != nil {
		t.Fatalf("Unable to read keystore file: %v", err)
	}

	_, ok := keystore.FindPublicKey("public-ssh")
	if !ok {
		t.Error("Failed to find public-ssh after import")
	}
}

repository: DarcInc/repository

repo_name: DarcInc/repository

gha_language: Go


text:
SUMMARY = "Tools for TPM2."
DESCRIPTION = "tpm2-tools"
LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://docs/LICENSE;md5=a846608d090aa64494c45fc147cc12e3"
SECTION = "tpm"

DEPENDS = "tpm2-abrmd tpm2-tss openssl curl autoconf-archive"

SRC_URI = "https://github.com/tpm2-software/${BPN}/releases/download/${PV}/${BPN}-${PV}.tar.gz"

SRC_URI[sha256sum] = "1fdb49c730537bfdaed088884881a61e3bfd121e957ec0bdceeec0261236c123"

UPSTREAM_CHECK_URI = "https://github.com/tpm2-software/${BPN}/releases"

inherit autotools pkgconfig bash-completion

# need tss-esys
RDEPENDS:${PN} = "libtss2 tpm2-abrmd"

repository: foundriesio/meta-lmp

repo_name: foundriesio/meta-lmp

branch_name: refs/heads/main


text:
@article{nakashima_privacy_2016,
 abstract = {The recent popularization of social network services (SNSs), such as YouTube, Dailymotion, and Facebook, enables people to easily publish their personal videos taken with mobile cameras. However, at the same time, such popularity has raised a new problem: video privacy. In such social videos, the privacy of people, i.e., their appearances, must be protected, but naively obscuring all people might spoil the video content. To address this problem, we focus on videographers' capture intentions. In a social video, some persons are usually essential for the video content. They are intentionally captured by the videographers, called intentionally captured persons (ICPs), and the others are accidentally framed-in (non-ICPs). Videos containing the appearances of the non-ICPs might violate their privacy. In this paper, we developed a system called BEPS, which adopts a novel conditional random field (CRF)-based method for ICP detection, as well as a novel approach to obscure non-ICPs and preserve ICPs using background estimation. BEPS reduces the burden of manually obscuring the appearances of the non-ICPs before uploading the video to SNSs. Compared with conventional systems, the following are the main advantages of BEPS: (i) it maintains the video content, and (ii) it is immune to the failure of person detection; false positives in person detection do not violate privacy. Our experimental results successfully validated these two advantages.},
 author = {Nakashima, Yuta and Babaguchi, Noboru and Fan, Jianping},
 doi = {10.1587/transinf.2015EDP7378},
 file = {Snapshot:/Users/n-yuta/Zotero/storage/ZLUGA56G/_article.html:text/html;Full Text PDF:/Users/n-yuta/Zotero/storage/Y88BYF9H/Nakashima et al. - 2016 - Privacy Protection for Social Video via Background.pdf:application/pdf},
 issn = {0916-8532, 1745-1361},
 journal = {IEICE Transactions on Information and Systems},
 language = {en},
 month = {April},
 number = {4},
 pages = {1221--1233},
 title = {Privacy protection for social video via background estimation and CRF-based videographer's intention modeling},
 url = {https://www.jstage.jst.go.jp/article/transinf/E99.D/4/E99.D_2015EDP7378/_article},
 urldate = {2019-04-30},
 volume = {E99.D},
 year = {2016}
}


text:
package packages

import (
	"context"
	"log"
	"math"

	"github.com/agnivade/levenshtein"
)

// Update the package's filename if the latest
// version does not contain the filename
// Note that if the filename is nil it will stay nil.
func UpdateFilenameIfMissing(ctx context.Context, pkg *Package, files []string) error {
	if len(files) == 0 {
		log.Printf("%s: KV version contains no files\n", *pkg.Name)
		return nil
	}

	if pkg.Filename != nil {
		// check if assets contains filename
		filename := *pkg.Filename
		for _, asset := range files {
			if asset == filename {
				return nil // filename included in latest version, so return
			}
		}

		// set filename to be the most similar string in []assets
		mostSimilar := getMostSimilarFilename(filename, files)
		pkg.Filename = &mostSimilar
		log.Printf("%s: Updated filename `%s` -> `%s`\n", *pkg.Name, filename, mostSimilar)
		return nil
	}
	log.Printf("%s: filename missing, so will stay missing.\n", *pkg.Name)
	return nil
}

// Gets the most similar filename to a target filename.
// The []string of alternatives must have at least one element.
func getMostSimilarFilename(target string, filenames []string) string {
	var mostSimilar string
	var minDist int = math.MaxInt32
	for _, f := range filenames {
		if dist := levenshtein.ComputeDistance(target, f); dist < minDist {
			mostSimilar = f
			minDist = dist
		}
	}
	return mostSimilar
}


text:
@Proceedings{ACML2015,
  booktitle = {Proceedings of The 7th Asian Conference on Machine Learning},
  editor = {Geoffrey Holmes and Tie-Yan Liu},
  volume = {45},
  year = {2015},
  shortname = {ACML},
  sections = {preface=Preface|default=Accepted Papers}
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_language: TeX


text:
package v2_test

import (
	"context"
	"reflect"
	"testing"

	v2 "github.com/ovh/cds/sdk/exportentities/v2"

	"github.com/ovh/cds/sdk/exportentities"

	"github.com/ovh/cds/engine/api/test"
	"github.com/ovh/cds/sdk"
	"github.com/stretchr/testify/assert"
	yaml "gopkg.in/yaml.v2"
)

func Test_checkWorkflowNotificationsValidity(t *testing.T) {

	type args struct {
		yaml string
	}
	tests := []struct {
		name string
		args args
		want error
	}{
		{
			name: "test multiple notifications",
			want: nil,
			args: args{
				yaml: `name: test1
version: v2.0
workflow:
  DDOS-me:
    pipeline: DDOS-me
    application: test1
    payload:
      git.author: ""
      git.branch: master
      git.hash: ""
      git.hash.before: ""
      git.message: ""
      git.repository: bnjjj/godevoxx
      git.tag: ""
  DDOS-me_2:
    depends_on:
    - DDOS-me
    when:
    - success
    pipeline: DDOS-me
metadata:
  default_tags: git.branch,git.author
notifications:
- type: email
  pipelines:
  - DDOS-me
  - DDOS-me_2
  settings:
    on_success: always
    on_failure: change
    on_start: true
    send_to_groups: true
    send_to_author: false
    recipients:
    - q
    template:
      subject: '{{.cds.project}}/{{.cds.application}} {{.cds.pipeline}} {{.cds.environment}}#{{.cds.version}}
        {{.cds.status}}'
      body: |-
        Project : {{.cds.project}}
        Application : {{.cds.application}}
        Pipeline : {{.cds.pipeline}}/{{.cds.environment}}#{{.cds.version}}
        Status : {{.cds.status}}
        Details : {{.cds.buildURL}}
        Triggered by : {{.cds.triggered_by.username}}
        Branch : {{.git.branch}}
- type: email
  pipelines:
  - DDOS-me_2
  settings:
    template:
      subject: '{{.cds.project}}/{{.cds.application}} {{.cds.pipeline}} {{.cds.environment}}#{{.cds.version}}
        {{.cds.status}}'
      body: |-
        Project : {{.cds.project}}
        Application : {{.cds.application}}
        Pipeline : {{.cds.pipeline}}/{{.cds.environment}}#{{.cds.version}}
        Status : {{.cds.status}}
        Details : {{.cds.buildURL}}
        Triggered by : {{.cds.triggered_by.username}}
        Branch : {{.git.branch}}
- type: vcs
  settings:
    template:
      disable_comment: true
- type: event
  integration: my-integration
`,
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var w v2.Workflow
			test.NoError(t, yaml.Unmarshal([]byte(tt.args.yaml), &w))
			if got := v2.CheckWorkflowNotificationsValidity(w); got != tt.want {
				t.Errorf("checkWorkflowNotificationsValidity() = %#v, want %v", got, tt.want)
			}
		})
	}
}

func Test_processNotificationValues(t *testing.T) {
	type args struct {
		notif v2.NotificationEntry
	}
	tests := []struct {
		name    string
		args    args
		want    sdk.WorkflowNotification
		wantErr bool
	}{
		// TODO: Add test cases.
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := v2.ProcessNotificationValues(tt.args.notif)
			if (err != nil) != tt.wantErr {
				t.Errorf("processNotificationValues() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("processNotificationValues() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestFromYAMLToYAMLWithNotif(t *testing.T) {
	tests := []struct {
		name    string
		yaml    string
		wantErr bool
	}{
		{
			name: "two pipelines with one notif",
			yaml: `name: test-notif-1
version: v2.0
workflow:
  test:
    pipeline: test
  test_2:
    depends_on:
    - test
    when:
    - success
    pipeline: test
notifications:
- type: email
  pipelines:
  - test
  - test_2
`,
		}, {
			name: "two pipelines with two notifs",
			yaml: `name: test-notif-1
version: v2.0
workflow:
  test:
    pipeline: test
  test_2:
    depends_on:
    - test
    when:
    - success
    pipeline: test
notifications:
- type: email
  pipelines:
  - test
  settings:
    on_success: always
    on_failure: change
    on_start: true
    send_to_groups: true
    send_to_author: false
    recipients:
    - a
    template:
      subject: '{{.cds.project}}/{{.cds.application}} {{.cds.pipeline}} {{.cds.environment}}#{{.cds.version}} {{.cds.status}}'
      body: |-
        Project : {{.cds.project}}
        Application : {{.cds.application}}
        Pipeline : {{.cds.pipeline}}/{{.cds.environment}}#{{.cds.version}}
        Status : {{.cds.status}}
        Details : {{.cds.buildURL}}
        Triggered by : {{.cds.triggered_by.username}}
        Branch : {{.git.branch}}
- type: email
  pipelines:
  - test
  - test_2
  settings:
    template:
      subject: '{{.cds.project}}/{{.cds.application}} {{.cds.pipeline}} {{.cds.environment}}#{{.cds.version}} {{.cds.status}}'
      body: |-
        Project : {{.cds.project}}
        Application : {{.cds.application}}
        Pipeline : {{.cds.pipeline}}/{{.cds.environment}}#{{.cds.version}}
        Status : {{.cds.status}}
        Details : {{.cds.buildURL}}
        Triggered by : {{.cds.triggered_by.username}}
        Branch : {{.git.branch}}
- type: event
  integration: my-integration
`,
		},
		{
			name: "two pipelines with one notif without node name",
			yaml: `name: test-notif-2-pipeline-no-node
version: v2.0
workflow:
  test:
    pipeline: test
  test_2:
    depends_on:
    - test
    when:
    - success
    pipeline: test
notifications:
- type: email
- type: event
  integration: my-integration
`,
		},
	}
	for _, tst := range tests {
		t.Run(tst.name, func(t *testing.T) {
			yamlWorkflow, err := exportentities.UnmarshalWorkflow([]byte(tst.yaml), exportentities.FormatYAML)
			if err != nil {
				if !tst.wantErr {
					t.Error("Unmarshal raised an error", err)
					return
				}
			}
			if tst.wantErr {
				t.Error("Unmarshal should return an error but it doesn't")
				return
			}
			w, err := exportentities.ParseWorkflow(context.TODO(), yamlWorkflow)
			if err != nil {
				if !tst.wantErr {
					t.Error("GetWorkflow raised an error", err)
					return
				}
			}
			if tst.wantErr {
				t.Error("GetWorkflow should return an error but it doesn't")
				return
			}

			// Set the hook and outgoing hook models properly before export all the things
			w.VisitNode(func(n *sdk.Node, w *sdk.Workflow) {
				for i := range n.Hooks {
					for _, m := range sdk.BuiltinHookModels {
						if n.Hooks[i].HookModelName == m.Name {
							break
						}
					}
				}
				if n.OutGoingHookContext != nil {
					for _, m := range sdk.BuiltinOutgoingHookModels {
						if n.OutGoingHookContext.HookModelName == m.Name {
							n.OutGoingHookContext.HookModelID = m.ID
							break
						}
					}
				}
			})
			exportedWorkflow, err := exportentities.NewWorkflow(context.TODO(), *w)
			if err != nil {
				if !tst.wantErr {
					t.Error("NewWorkflow raised an error", err)
					return
				}
			}
			if tst.wantErr {
				t.Error("NewWorkflow should return an error but it doesn't")
				return
			}
			b, err := yaml.Marshal(exportedWorkflow)
			if err != nil {
				if !tst.wantErr {
					t.Error("Marshal raised an error", err)
					return
				}
			}
			if tst.wantErr {
				t.Error("Marshal should return an error but it doesn't")
				return
			}
			assert.Equal(t, tst.yaml, string(b))
		})
	}
}

repository: ovh/cds

repo_name: ovh/cds


text:
require xinput-calibrator.inc

PV = "0.6.0+gitr${SRCPV}"
PR = "${INC_PR}.0"

SRC_URI = "git://github.com/tias/xinput_calibrator.git;protocol=git;branch=misclick"

SRCREV = "496d4401731c6e5ed550e446cc2fc4b12d999ad8"
S = "${WORKDIR}/git/"

do_install_append() {
        install -d ${D}${bindir}
        install -m 0755 scripts/xinput_calibrator_pointercal.sh ${D}${bindir}/xinput_calibrator_once.sh
        ln -s ${bindir}/xinput_calibrator_x11 ${D}${bindir}/xinput_calibrator
        install -d ${D}${datadir}/applications/
        install -m 0755 scripts/xinput_calibrator.desktop ${D}${datadir}/applications/xinput-calibrator.desktop
}

# remove this after misclick branch is well-tested and merged to master
DEFAULT_PREFERENCE = "-1"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package strings

import (
	"github.com/MG-RAST/golib/stretchr/testify/assert"
	"testing"
)

func TestParse(t *testing.T) {

	assert.Exactly(t, nil, Parse(""))
	assert.Exactly(t, nil, Parse("null"))

	assert.Exactly(t, int(1), Parse("1"))
	assert.Exactly(t, 9223372036854775807, Parse("9223372036854775807"))
	assert.Exactly(t, float32(92233720368547758071), Parse("92233720368547758071"))
	assert.Exactly(t, float32(1.11), Parse("1.11"))
	assert.Exactly(t, uint64(18446744073709551615), Parse("18446744073709551615"))

	assert.Exactly(t, true, Parse("true"))
	assert.Exactly(t, false, Parse("false"))
	assert.Exactly(t, true, Parse("TRUE"))
	assert.Exactly(t, false, Parse("FALSE"))
	assert.Exactly(t, "something", Parse("something"))

}

func TestParse_ForcedStrings(t *testing.T) {

	assert.Exactly(t, "true", Parse("'true'"))
	assert.Exactly(t, "true", Parse(`"true"`))

}

repository: MG-RAST/golib

repo_name: MG-RAST/golib


text:
#
# Base recipe: meta/recipes-graphics/xorg-lib/libxcursor_1.1.14.bb
# Base branch: daisy
#

SUMMARY = "Xcursor: X Cursor management library"

DESCRIPTION = "Xcursor is a simple library designed to help locate and \
load cursors. Cursors can be loaded from files or memory. A library of \
common cursors exists which map to the standard X cursor names. Cursors \
can exist in several sizes and the library automatically picks the best \
size."

require xorg-lib-common.inc

PR = "${INC_PR}.0"

LICENSE = "MIT-style"
LIC_FILES_CHKSUM = "file://COPYING;md5=8902e6643f7bcd7793b23dcd5d8031a4"

DEPENDS += "libxrender libxfixes"
BBCLASSEXTEND = "native"

# There is no debian patch
DEBIAN_PATCH_TYPE = "nopatch"

DEBIANNAME_${PN}-dbg = "${PN}1-dbg"

repository: nghiaht-tsdv/meta-debian

repo_name: nghiaht-tsdv/meta-debian

branch_name: refs/heads/jethro


text:
SUMMARY = "Python module used in SELinux policy generation"
DESCRIPTION = "The sepolgen library is structured to give flexibility to the application \
using it. The library contains: Reference Policy Representation, \
which are Objects for representing policies and the reference policy \
interfaces. Secondly, it has objects and algorithms for representing \
access and sets of access in an abstract way and searching that \
access. It also has a parser for reference policy "headers". It \
contains infrastructure for parsing SELinux related messages as \
produced by the audit system. It has facilities for generating policy \
based on required access."
HOMEPAGE = "http://userspace.selinuxproject.org/"

PR = "r0"

inherit debian-package

LICENSE = "GPLv2+ & LGPLv2.1+"
LIC_FILES_CHKSUM = " \
    file://COPYING;md5=393a5ca445f6965873eca0259a17f833 \
    file://src/sepolgen/yacc.py;endline=22;md5=ac24ba658bf16b09297ca83ec064d56a \
"

inherit pythonnative

DEPENDS += "python"

# source format is 3.0 (quilt) but there is no debian patch
DEBIAN_QUILT_PATCHES = ""

do_install() {
	oe_runmake DESTDIR=${D} \
	           PYTHONLIBDIR='${PYTHON_SITEPACKAGES_DIR}' \
	           install
}

FILES_${PN} += "${libdir}/${PYTHON_DIR}/*-packages/sepolgen/*"

PKG_${PN} = "python-${PN}"

BBCLASSEXTEND = "native"


text:
// Copyright © 2020 by PACE Telematics GmbH. All rights reserved.
// Created at 2020/04/16 by Vincent Landgraf

package locale

import (
	"log"

	"github.com/caarlos0/env"
)

type config struct {
	Language string `env:"LOCALE_FALLBACK_LANGUAGE" envDefault:"de-DE"`
	Timezone string `env:"LOCALE_FALLBACK_TIMEZONE" envDefault:"Europe/Berlin"`
}

var cfg config

func init() {
	err := env.Parse(&cfg)
	if err != nil {
		log.Fatalf("Failed to parse environment: %v", err)
	}
}

repository: pace/bricks

repo_name: pace/bricks


text:
package handler

import (
	"fmt"
	"github.com/bwmarrin/discordgo"
	"github.com/ryanbradynd05/go-tmdb"
	log "github.com/sirupsen/logrus"
)

func TMDbSearchMovie(t *tmdb.TMDb, q string) (*discordgo.MessageEmbed, error) {
	l := log.WithFields(log.Fields{
		"action": "handler.TMDbSearchMovie",
	})

	movieResult, err := t.SearchMovie(q, nil)
	if err != nil {
		l.Errorf("Failed to look up TMDB: %v", err)
		return &discordgo.MessageEmbed{}, err
	}

	if len(movieResult.Results) == 0 {
		return &discordgo.MessageEmbed{}, fmt.Errorf("No matching movie found")
	}

	randMovie := movieResult.Results[0]
	responseEmbed := &discordgo.MessageEmbed{
		Title: randMovie.Title,
		Description: fmt.Sprintf("%v\n\n**Release date:** %v\n**Score:** %.0f%%", randMovie.Overview,
			randMovie.ReleaseDate, (randMovie.VoteAverage * 10)),
		Type: discordgo.EmbedTypeImage,
		Image: &discordgo.MessageEmbedImage{
			URL:   fmt.Sprintf("https://image.tmdb.org/t/p/w300%v", randMovie.PosterPath),
			Width: 300,
		},
		URL: fmt.Sprintf("https://www.themoviedb.org/movie/%v", randMovie.ID),
	}

	return responseEmbed, nil
}
func TMDbSearchTvShow(t *tmdb.TMDb, q string) (*discordgo.MessageEmbed, error) {
	l := log.WithFields(log.Fields{
		"action": "handler.TMDbSearchTvShow",
	})

	tvSeriesResult, err := t.SearchTv(q, nil)
	if err != nil {
		l.Errorf("Failed to look up TMDB: %v", err)
		return &discordgo.MessageEmbed{}, err
	}

	if len(tvSeriesResult.Results) == 0 {
		return &discordgo.MessageEmbed{}, fmt.Errorf("No matching TV show found")
	}

	randTvSeries := tvSeriesResult.Results[0]
	randTvDetails, err := t.GetTvInfo(randTvSeries.ID, nil)
	if err != nil {
		return &discordgo.MessageEmbed{}, err
	}
	responseEmbed := &discordgo.MessageEmbed{
		Title: randTvSeries.Name,
		Description: fmt.Sprintf("%v\n\n**First aired:** %v\n**Score:** %.0f%%", randTvDetails.Overview,
			randTvSeries.FirstAirDate, (randTvSeries.VoteAverage * 10)),
		Type: discordgo.EmbedTypeImage,
		Image: &discordgo.MessageEmbedImage{
			URL:   fmt.Sprintf("https://image.tmdb.org/t/p/w300%v", randTvSeries.PosterPath),
			Width: 300,
		},
		URL: fmt.Sprintf("https://www.themoviedb.org/tv/%v", randTvSeries.ID),
	}

	return responseEmbed, nil
}

repository: echox/sotbot

repo_name: echox/sotbot


text:
@article{Weber-2016-Description,
    title = "Description of current and future snow processes in a small basin in the Bavarian Alps",
    author = {Weber, M.  and
      Bernhardt, M.  and
      Pomeroy, J. W.  and
      Fang, X.  and
      H{\"a}rer, S.  and
      Schulz, K.},
    journal = "Environmental Earth Sciences, Volume 75, Issue 17",
    volume = "75",
    number = "17",
    year = "2016",
    publisher = "Springer Science and Business Media LLC",
    url = "https://aclanthology.org/G16-4001",
    doi = "10.1007/s12665-016-6027-1",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

gha_language: Python


text:
// Learn about using x/mobile/app API directly.
package main

import (
	"math"
	"time"

	"golang.org/x/mobile/app"
	"golang.org/x/mobile/event/lifecycle"
	"golang.org/x/mobile/event/paint"
	"golang.org/x/mobile/event/size"
	"golang.org/x/mobile/event/touch"
	"golang.org/x/mobile/gl"
)

var (
	touchX float32
	touchY float32
)

func main() {
	app.Main(func(a app.App) {
		var glctx gl.Context
		var sz size.Event
		for e := range a.Events() {
			switch e := a.Filter(e).(type) {
			case lifecycle.Event:
				switch e.Crosses(lifecycle.StageVisible) {
				case lifecycle.CrossOn:
					glctx, _ = e.DrawContext.(gl.Context)
					onStart(glctx)
					a.Send(paint.Event{})
				case lifecycle.CrossOff:
					onStop(glctx)
					glctx = nil
				}
			case size.Event:
				sz = e
				touchX = float32(sz.WidthPx / 2)
				touchY = float32(sz.HeightPx / 2)
			case paint.Event:
				if glctx == nil || e.External {
					// As we are actively painting as fast as
					// we can (usually 60 FPS), skip any paint
					// events sent by the system.
					continue
				}

				onPaint(glctx, sz)
				a.Publish()
				// Drive the animation by preparing to paint the next frame
				// after this one is shown.
				a.Send(paint.Event{})
			case touch.Event:
				touchX = e.X
				touchY = e.Y
			}
		}
	})
}

func onStart(glctx gl.Context) {
}

func onStop(glctx gl.Context) {
}

var started = time.Now()

func onPaint(glctx gl.Context, sz size.Event) {
	glctx.ClearColor(0.8*(0.5*(1.0+float32(math.Sin(time.Since(started).Seconds())))), 0.3, 0.01, 1)
	glctx.Clear(gl.COLOR_BUFFER_BIT)
}

license: Unlicense

repository: shurcooL/play

repo_name: shurcooL/play


text:
// Copyright (c) 2021 Terminus, 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 dao

import (
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/erda-project/erda/apistructs"
)

func Test_validateTestCasePagingRequest(t *testing.T) {
	type args struct {
		req apistructs.TestCasePagingRequest
	}
	orderBy := true
	tests := []struct {
		name    string
		args    args
		wantErr bool
	}{
		{
			name: "missing project",
			args: args{
				req: apistructs.TestCasePagingRequest{},
			},
			wantErr: true,
		},
		{
			name: "invalid priority",
			args: args{
				req: apistructs.TestCasePagingRequest{Priorities: []apistructs.TestCasePriority{"xxx"}},
			},
			wantErr: true,
		},
		{
			name: "order by both priority asc/desc",
			args: args{
				req: apistructs.TestCasePagingRequest{OrderByPriorityAsc: &orderBy, OrderByPriorityDesc: &orderBy},
			},
			wantErr: true,
		},
		{
			name: "order by both updaterID asc/desc",
			args: args{
				req: apistructs.TestCasePagingRequest{OrderByUpdaterIDAsc: &orderBy, OrderByUpdaterIDDesc: &orderBy},
			},
			wantErr: true,
		},
		{
			name: "order by both updatedAt asc/desc",
			args: args{
				req: apistructs.TestCasePagingRequest{OrderByUpdatedAtAsc: &orderBy, OrderByUpdatedAtDesc: &orderBy},
			},
			wantErr: true,
		},
		{
			name: "order by both id asc/desc",
			args: args{
				req: apistructs.TestCasePagingRequest{OrderByIDAsc: &orderBy, OrderByIDDesc: &orderBy},
			},
			wantErr: true,
		},
		{
			name: "order by both testSetID asc/desc",
			args: args{
				req: apistructs.TestCasePagingRequest{OrderByTestSetIDAsc: &orderBy, OrderByTestSetIDDesc: &orderBy},
			},
			wantErr: true,
		},
		{
			name: "order by both testSetName asc/desc",
			args: args{
				req: apistructs.TestCasePagingRequest{OrderByTestSetNameAsc: &orderBy, OrderByTestSetNameDesc: &orderBy},
			},
			wantErr: true,
		},
		{
			name: "valid request",
			args: args{
				req: apistructs.TestCasePagingRequest{ProjectID: 1},
			},
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if err := validateTestCasePagingRequest(tt.args.req); (err != nil) != tt.wantErr {
				t.Errorf("validateTestCasePagingRequest() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

func Test_setDefaultForTestCasePagingRequest(t *testing.T) {
	// must order by testSet
	req1 := apistructs.TestCasePagingRequest{OrderByPriorityAsc: &[]bool{true}[0]}
	setDefaultForTestCasePagingRequest(&req1)
	assert.Equal(t, 1, len(req1.OrderFields))
	assert.Equal(t, tcFieldTestSetID, req1.OrderFields[0])
	assert.True(t, *req1.OrderByTestSetIDAsc)

	// set default order inside a testSet
	req2 := apistructs.TestCasePagingRequest{OrderByTestSetIDAsc: &[]bool{true}[0]}
	setDefaultForTestCasePagingRequest(&req2)
	assert.Equal(t, 1, len(req1.OrderFields))
	assert.Equal(t, tcFieldID, req2.OrderFields[0])
	assert.True(t, *req2.OrderByIDAsc)

	// default page
	req3 := apistructs.TestCasePagingRequest{}
	setDefaultForTestCasePagingRequest(&req3)
	assert.True(t, 1 == req3.PageNo)
	assert.True(t, 20 == req3.PageSize)
}

repository: erda-project/erda

repo_name: erda-project/erda


text:
package main

import (
	"fmt"
	"net/http"
	"time"
)

type Symbol string

type Candle struct {
	Timestamp int64
	Volume    float64
	Open      float64
	Close     float64
	High      float64
	Low       float64
}

type Result struct {
	Symbol       Symbol
	Currency     string
	Timezone     string
	CurrentPrice float64
	HighestPrice float64
	LowerPrice   float64
	Candles      []Candle
}

type Query struct {
	Symbol   Symbol
	Start    int64
	End      int64
	Interval string
}

type Client interface {
	SetHttpClient(http http.Client)
	Get(symbol Symbol) (Result, error)
}

type Yahoofinance struct {
	httpClient http.Client
}

func (y *Yahoofinance) SetHttpClient(httpClient http.Client) {
	y.httpClient = httpClient
}

func (y *Yahoofinance) Get(symbol Symbol) (Result, error) {
	fmt.Println(symbol)
	return Result{}, nil
}

type Finance struct {
	HttpClient http.Client
	Client     Client
}

func (f *Finance) SetupWithYahooFinance() {
	f.Client = &Yahoofinance{}
	f.Client.SetHttpClient(f.HttpClient)
}

func main() {
	httpClient := http.Client{Timeout: 30 * time.Second}
	finance := Finance{HttpClient: httpClient}
	finance.SetupWithYahooFinance()
	finance.Client.Get("PETR4")
}

repository: kelvinoenning/go-finance

repo_name: kelvinoenning/go-finance


text:
package tools

import (
	"github.com/emicklei/go-restful"
	"github.com/wonderivan/logger"
)

type responseObject struct {
	Message string      `json:"message"`
	Code    int32       `json:"code"`
	Data    interface{} `json:"data"`
}

//ResponseSuccess is web response for success
func ResponseSuccess(response *restful.Response, data interface{}) {
	logger.Info("return response data: ", data)
	err := response.WriteEntity(responseObject{Code: 200, Message: "success", Data: data})
	if err != nil {
		logger.Error("return response error: ", err)
	}
}

//ResponseErrorAndCodeMessage is web response for error
func ResponseErrorAndCodeMessage(response *restful.Response, code int32, err error, message string) {
	logger.Error("response error: ", err)
	err = response.WriteEntity(responseObject{Code: code, Message: message, Data: ""})
	if err != nil {
		logger.Error("return response error: ", err)
	}
}

//ResponseError is web response for error
func ResponseError(response *restful.Response, err error) {
	ResponseErrorAndCodeMessage(response, 500, err, err.Error())
}

//ResponseSystemError is web response for error
func ResponseSystemError(response *restful.Response, err error) {
	ResponseErrorAndCodeMessage(response, 500, err, ErrMessageSystem)
}

//ResponseErrorAndMessage is web response for error
func ResponseErrorAndMessage(response *restful.Response, err error, message string) {
	ResponseErrorAndCodeMessage(response, 500, err, message)
}

//ResponseAuthError is web response for error of cookie not login
func ResponseAuthError(response *restful.Response) {
	ResponseErrorAndCodeMessage(response, 401, ErrUserNotLogin, ErrUserNotLogin.Error())
}

repository: labring/fist

repo_name: labring/fist


text:
package remoteclientconfig

import (
	"io"

	"github.com/BurntSushi/toml"
	"github.com/pkg/errors"
)

// ReadRemoteConfig takes an io.Reader representing the remote configuration
// file and returns a remoteconfig
func ReadRemoteConfig(reader io.Reader) (*RemoteConfig, error) {
	var remoteConfig RemoteConfig
	// the configuration file does not exist
	if reader == nil {
		return &remoteConfig, ErrNoConfigationFile
	}
	_, err := toml.DecodeReader(reader, &remoteConfig)
	if err != nil {
		return nil, err
	}
	// We need to validate each remote connection has fields filled out
	for name, conn := range remoteConfig.Connections {
		if len(conn.Destination) < 1 {
			return nil, errors.Errorf("connection %q has no destination defined", name)
		}
	}
	return &remoteConfig, err
}

// GetDefault returns the default RemoteConnection. If there is only one
// connection, we assume it is the default as well
func (r *RemoteConfig) GetDefault() (*RemoteConnection, error) {
	if len(r.Connections) == 0 {
		return nil, ErrNoDefinedConnections
	}
	for _, v := range r.Connections {
		v := v
		if len(r.Connections) == 1 {
			// if there is only one defined connection, we assume it is
			// the default whether tagged as such or not
			return &v, nil
		}
		if v.IsDefault {
			return &v, nil
		}
	}
	return nil, ErrNoDefaultConnection
}

// GetRemoteConnection "looks up" a remote connection by name and returns it in the
// form of a RemoteConnection
func (r *RemoteConfig) GetRemoteConnection(name string) (*RemoteConnection, error) {
	if len(r.Connections) == 0 {
		return nil, ErrNoDefinedConnections
	}
	for k, v := range r.Connections {
		v := v
		if k == name {
			return &v, nil
		}
	}
	return nil, errors.Wrap(ErrConnectionNotFound, name)
}

repository: adrianreber/libpod

repo_name: adrianreber/libpod


text:
#
# (pdf)latex document_name(use "\ll" map key in vim with latex-suit)
# biblatex   document_name(.aux)
# (pdf)latex document_name
# (pdf)latex document_name
#

@article{L06,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR1",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L02,
  title     = "Location-based services and GIS in perspective",
  author    = "AUTHOR2",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L01,
  title     = "Location based services using geographical information systems",
  author    = "AUTHOR3",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L07,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR4",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L13,
  title     = "Ubiquitous Location Based Service",
  author    = "AUTHOR5",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L10,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR6",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L08,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR7",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L09,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR8",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L05,
  title     = "An architecture and development methodology for location-based services",
  author    = "AUTHOR9",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L03,
  title     = "A Platform for Interactive Location-Based Services",
  author    = "AUTHOR10",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L11,
  title     = "iZone-A Location-Based Mobile Social Networking System",
  author    = "AUTHOR11",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L04,
  title     = "Location-Based Services in Mobile Communication Infrastructures",
  author    = "AUTHOR12",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D06,
  title     = "Effective Location Based Services with Dynamic Data Management in Mobile Environments",
  author    = "AUTHOR13",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{L12,
  title     = "Zone-Based Update Mechanism for Location based Services",
  author    = "AUTHOR14",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D09,
  title     = "Mining Cluster-based Mobile Sequential Patterns in Location-Based Service Environments",
  author    = "AUTHOR15",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D11,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR16",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D10,
  title     = "A Distributed Location Based Service Framework of Ubiquitous Computin",
  author    = "AUTHOR17",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D02,
  title     = "Intelligent Location-based Mobile News Service System with Automatic News Summarization",
  author    = "AUTHOR18",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D05,
  title     = "Context and Location based Service Grouping and Group Notification",
  author    = "AUTHOR19",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D04,
  title     = "A Location-Based Push Service Architecture with Clustering Method",
  author    = "AUTHOR20",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D08,
  title     = "Location dependent Query Processing – Issues, Challenges and Applications",
  author    = "AUTHOR21",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{D03,
  title     = "An Indoor Location-Based Service Using Access Points as Signal Strength Data Collectors",
  author    = "AUTHOR22",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{P04,
  title     = "LRAP-A Location-Based Remote Client Authentication Protocol for Mobile Environments",
  author    = "AUTHOR23",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{P02,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR24",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{P01,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR25",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{P03,
  title     = "Binomial-Mix-based Location Anonymizer System with Global Dummy Generation to Preserve User Location Privacy in Location-Based Services",
  author    = "AUTHOR26",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@article{P05,
  title     = "A Peer-to-Peer Spatial Cloaking Algorithm for Anonymous Location-based Services",
  author    = "AUTHOR27",
  publisher = "PUBLISHER",
  year      = 9999,
  volume    = 99,
  number    = 9,
  pages     = "1-999"
}

@book{B02,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR28",
  publisher = "PUBLISHER",
  ISBN      = "X-X1-999XXX-X",
  year      = 9999
}

@book{iOSLIB,
  title     = "iOS Developer Lib",
  author    = "AUTHOR30",
  publisher = "PUBLISHER",
  ISBN      = "X-X1-999XXX-X",
  year      = 9999,
}

@book{B01,
  title     = "CHINESE TEMP TITLE",
  author    = "AUTHOR29",
  publisher = "PUBLISHER",
  ISBN      = "X-X1-999XXX-X",
  year      = 9999
}

repository: jvlstudio/iPokeMon-Doc

repo_name: jvlstudio/iPokeMon-Doc


text:
// Copyright 2020 Anapaya Systems
//
// 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 server

import (
	"context"
	"crypto/tls"
	"fmt"
	"net"
	"net/http"
	_ "net/http/pprof" // Register pprof HTTP handlers
	"os"
	"sync"
	"syscall"
	"time"

	"github.com/golang/protobuf/ptypes"
	"github.com/lucas-clemente/quic-go"
	"github.com/spf13/cobra"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	grpcstatus "google.golang.org/grpc/status"

	pb "github.com/anapaya/bwallocation/proto/bwreserver/v1"
	"github.com/anapaya/bwallocation/reservation"
	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/fatal"
	"github.com/scionproto/scion/go/lib/infra/infraenv"
	"github.com/scionproto/scion/go/lib/log"
	"github.com/scionproto/scion/go/lib/sciond"
	"github.com/scionproto/scion/go/lib/serrors"
	"github.com/scionproto/scion/go/lib/slayers"
	"github.com/scionproto/scion/go/lib/snet"
	"github.com/scionproto/scion/go/lib/snet/addrutil"
	"github.com/scionproto/scion/go/lib/snet/squic"
	"github.com/scionproto/scion/go/lib/sock/reliable"
	"github.com/scionproto/scion/go/pkg/app"
	"github.com/scionproto/scion/go/pkg/app/flag"
	"github.com/scionproto/scion/go/pkg/command"
)

func Cmd(pather command.Pather) *cobra.Command {
	var flags struct {
		dispatcher string
		sciond     string
		local      flag.UDPAddr
		pprof      flag.TCPAddr
		logLevel   string
	}
	cmd := &cobra.Command{
		Use:     "server",
		Short:   "Bandwidth Reservation Demo Server",
		Example: "  " + pather.CommandPath() + " server --local :9000",
		Args:    cobra.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			cmd.SilenceUsage = true

			local, err := resolveLocal(flags.sciond, (*net.UDPAddr)(&flags.local))
			if err != nil {
				return err
			}
			if err := app.SetupLog(flags.logLevel); err != nil {
				return serrors.WrapStr("setting up logging", err)
			}

			dispatcher := flags.dispatcher
			v, ok := os.LookupEnv("SCION_DISPATCHER_SOCKET")
			if ok && dispatcher == reliable.DefaultDispPath {
				dispatcher = v
			}
			server, err := newServer(dispatcher, local)
			if err != nil {
				return err
			}

			ctx := app.WithSignal(context.Background(), os.Interrupt, syscall.SIGTERM)
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()

			errs := make(chan error)
			if flags.pprof.Port != 0 {
				go func() {
					defer log.HandlePanic()
					if err := http.ListenAndServe(flags.pprof.String(), nil); err != nil {
						errs <- err
					}
				}()
			}
			go func() {
				defer log.HandlePanic()
				errs <- server.run(ctx)
			}()

			return <-errs
		},
	}
	flags.local = flag.UDPAddr{Port: 9000}
	cmd.Flags().StringVar(&flags.dispatcher, "dispatcher", reliable.DefaultDispPath,
		"dispatcher socket")
	cmd.Flags().Var(&flags.local, "local", "Address to listen on")
	cmd.Flags().StringVar(&flags.sciond, "sciond", sciond.DefaultAPIAddress, "SCION Daemon address")
	cmd.Flags().Var(&flags.pprof, "pprof", "Address to serve pprof")
	cmd.Flags().StringVar(&flags.logLevel, "log.level", "", app.LogLevelUsage)

	return cmd
}

func resolveLocal(sd string, srvAddr *net.UDPAddr) (*snet.UDPAddr, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	daemon, err := sciond.NewService(sd).Connect(ctx)
	if err != nil {
		return nil, serrors.WrapStr("connecting to SCION Daemon", err)
	}
	info, err := app.QueryASInfo(ctx, daemon)
	if err != nil {
		return nil, serrors.WrapStr("querying AS info", err)
	}
	if len(srvAddr.IP) == 0 {
		if srvAddr.IP, err = addrutil.DefaultLocalIP(ctx, daemon); err != nil {
			return nil, serrors.WrapStr("determine default local IP", err)
		}
	}
	return &snet.UDPAddr{
		IA:   info.IA,
		Host: srvAddr,
	}, nil
}

const (
	maxSessions       = 20
	sessionExpiration = 5 * time.Second
	reportInterval    = 1 * time.Second
	quicErrNoErr      = "Application error 0x100"
)

type server struct {
	pb.UnimplementedSessionServiceServer

	network           *snet.SCIONNetwork
	ctrlListener      net.Listener
	host              *net.UDPAddr
	tlsConfig         *tls.Config
	sessions          map[int]session
	statsChan         chan sessionStatsUpdate
	sessionClosedChan chan int
	mu                sync.Mutex
	wg                sync.WaitGroup
}

func newServer(disp string, l *snet.UDPAddr) (*server, error) {
	serverNet := &snet.SCIONNetwork{
		LocalIA: l.IA,
		Dispatcher: &snet.DefaultPacketDispatcherService{
			Dispatcher:  reliable.NewDispatcher(disp),
			SCMPHandler: ignoreSCMP{},
		},
	}
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	serverConn, err := serverNet.Listen(ctx, "udp", l.Host, addr.SvcNone)
	if err != nil {
		return nil, serrors.WrapStr("creating server connection", err)
	}
	tlsConfig, err := infraenv.GenerateTLSConfig()
	if err != nil {
		return nil, serrors.WrapStr("generating TLS config", err)
	}
	listener, err := quic.Listen(serverConn, tlsConfig, nil)
	if err != nil {
		return nil, serrors.WrapStr("listening QUIC/SCION", err)
	}

	return &server{
		network:           serverNet,
		ctrlListener:      squic.NewConnListener(listener),
		host:              l.Host,
		tlsConfig:         tlsConfig,
		sessions:          make(map[int]session, maxSessions),
		statsChan:         make(chan sessionStatsUpdate, maxSessions),
		sessionClosedChan: make(chan int, maxSessions),
	}, nil
}

func (s *server) run(ctx context.Context) error {
	grpcServer := grpc.NewServer()
	pb.RegisterSessionServiceServer(grpcServer, s)
	go func() {
		defer log.HandlePanic()
		fmt.Printf("Listening on %s for incoming connections.\n", s.host)
		if err := grpcServer.Serve(s.ctrlListener); err != nil {
			fatal.Fatal(err)
		}
	}()
	for {
		select {
		case update := <-s.statsChan:
			s.reportStats(update)
		case id := <-s.sessionClosedChan:
			s.mu.Lock()
			delete(s.sessions, id)
			s.mu.Unlock()
		case <-ctx.Done():
			s.mu.Lock()
			defer s.mu.Unlock()
			fmt.Println("interrupt received. closing all sessions...")
			for _, session := range s.sessions {
				session.close()
			}
			s.wg.Wait()
			fmt.Println("all sessions closed. terminating...")
			return nil
		}
	}
}

func (s *server) reportStats(stats sessionStatsUpdate) {
	receiveRate := float64(stats.bytesReceived*8) / stats.elapsed.Seconds() / 1e6
	fmt.Printf("session %d\tremote: %s\telapsed time: %s\treceive rate: %.2fmbps\n",
		stats.sessionID, stats.remote, stats.elapsed.Round(time.Second), receiveRate)
}

func (s *server) Stats(ctx context.Context,
	req *pb.StatsRequest) (*pb.StatsResponse, error) {

	id := int(req.SessionId)
	session, ok := s.sessions[id]
	if !ok {
		return nil, grpcstatus.Error(codes.Internal, "session id was not found")
	}

	e := session.stat()
	start, err := ptypes.TimestampProto(e.start)
	if err != nil {
		return nil, grpcstatus.Error(codes.Internal, "server encountered internal error")
	}
	current, err := ptypes.TimestampProto(e.curr)
	if err != nil {
		return nil, grpcstatus.Error(codes.Internal, "server encountered internal error")
	}
	return &pb.StatsResponse{
		Start:         start,
		Current:       current,
		BytesReceived: uint64(e.bytes),
	}, nil
}

func (s *server) OpenSession(ctx context.Context,
	request *pb.OpenSessionRequest) (*pb.OpenSessionResponse, error) {

	s.mu.Lock()
	defer s.mu.Unlock()

	srcIA := addr.IAInt(request.SrcIsdAs).IA()
	srcHost := net.IP(request.SrcHost)
	fmt.Printf("Session request received from %s,%s\n", srcIA, srcHost)

	if len(s.sessions) == maxSessions {
		return nil, grpcstatus.Error(codes.ResourceExhausted,
			"server cannot handle any more sessions")
	}

	protocol := request.Protocol
	if protocol == pb.Protocol_PROTOCOL_UNSPECIFIED {
		protocol = pb.Protocol_PROTOCOL_UDP
	}

	// Create new data conn.
	l := &net.UDPAddr{
		IP:   s.host.IP,
		Port: 0,
		Zone: s.host.Zone,
	}
	c, err := s.network.Listen(ctx, "udp", l, addr.SvcNone)
	if err != nil {
		return nil, grpcstatus.Error(codes.Unavailable, "server cannot open UDP socket")
	}
	localAddr := c.LocalAddr().(*net.UDPAddr)
	port := localAddr.Port
	if _, ok := s.sessions[port]; ok {
		// Lingering session for this port still exists. Cannot create a new one.
		c.Close()
		return nil, grpcstatus.Error(codes.Internal, "server encountered internal error")
	}
	var session session
	if protocol == pb.Protocol_PROTOCOL_UDP {
		session, err = s.createUDPSession(localAddr, c)
	} else {
		session, err = s.createQUICSession(localAddr, c)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "error creating data session: %s\n", err)
		c.Close()
		return nil, grpcstatus.Error(codes.Unavailable, "server cannot create data session")
	}

	s.sessions[port] = session

	go func() {
		defer log.HandlePanic()
		defer s.wg.Done()

		s.wg.Add(1)
		session.serve()
	}()

	return &pb.OpenSessionResponse{
		SessionId: uint64(port),
		Port:      uint32(port),
		Protocol:  protocol,
	}, nil
}

func (s *server) createUDPSession(local *net.UDPAddr, c *snet.Conn) (session, error) {
	return &udpSession{
		sessionBase: sessionBase{
			id:                local.Port,
			local:             local,
			statsChan:         s.statsChan,
			sessionClosedChan: s.sessionClosedChan,
			closeChan:         make(chan struct{}),
		},
		conn: c,
	}, nil
}

func (s *server) createQUICSession(local *net.UDPAddr, c *snet.Conn) (session, error) {
	listener, err := quic.Listen(c, s.tlsConfig, nil)
	if err != nil {
		return nil, err
	}
	return &quicSession{
		sessionBase: sessionBase{
			id:                local.Port,
			local:             local,
			statsChan:         s.statsChan,
			sessionClosedChan: s.sessionClosedChan,
			closeChan:         make(chan struct{}),
		},
		listener: squic.NewConnListener(listener),
	}, nil
}

type sessionStatsUpdate struct {
	sessionID     int
	remote        net.Addr
	elapsed       time.Duration
	bytesReceived int
}

type session interface {
	serve()
	stat() *status
	close()
}

type status struct {
	start, curr time.Time
	bytes       int
}

type sessionBase struct {
	id    int
	local *net.UDPAddr

	statsChan         chan sessionStatsUpdate
	closeChan         chan struct{}
	sessionClosedChan chan int

	mu                 sync.RWMutex
	bytesReceivedTotal int
	bytesReceived      int
	start              time.Time
	lastReport         time.Time
}

func (s *sessionBase) stat() *status {
	s.mu.RLock()
	defer s.mu.RUnlock()

	return &status{
		start: s.start,
		curr:  time.Now(),
		bytes: s.bytesReceivedTotal,
	}
}

func (s *sessionBase) collectStats(n int, remote net.Addr) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.bytesReceived += n
	now := time.Now()
	elapsed := now.Sub(s.lastReport)
	if elapsed >= reportInterval {
		s.statsChan <- sessionStatsUpdate{
			sessionID:     s.id,
			remote:        remote,
			elapsed:       elapsed,
			bytesReceived: s.bytesReceived,
		}
		s.lastReport = now
		s.bytesReceived = 0
	}
	s.bytesReceivedTotal += n
}

func (s *sessionBase) close() {
	close(s.closeChan)
}

type udpSession struct {
	sessionBase
	conn *snet.Conn
}

func (s *udpSession) serve() {
	if s.conn == nil {
		panic("serve called before data conn was initialized")
	}
	defer s.conn.Close()

	fmt.Printf("session %d starting (UDP)...\n", s.id)

	localAddrLen := net.IPv6len
	if v4 := s.local.IP.To4(); v4 != nil {
		localAddrLen = net.IPv4len
	}
	s.bytesReceived = 0
	s.bytesReceivedTotal = 0
	s.start = time.Now()
	s.lastReport = time.Now()

	recvBuf := make([]byte, 9000)
	received := 0
	for {
		select {
		case <-s.closeChan:
			return
		default:
			recvBuf = recvBuf[:cap(recvBuf)]
			s.conn.SetReadDeadline(time.Now().Add(sessionExpiration))
			n, sender, err := s.conn.ReadFrom(recvBuf)
			if err != nil && serrors.IsTimeout(err) {
				fmt.Printf("session %d timed out. closing...\n", s.id)
				s.sessionClosedChan <- s.id
				return
			}
			if err != nil {
				fmt.Fprintf(os.Stderr, "error reading from conn: %s\n", err)
				s.sessionClosedChan <- s.id
				return
			}
			// Account for SCION Header and throughput.
			received = n + headerLen(sender.(*snet.UDPAddr), localAddrLen)
			s.collectStats(received, sender)
		}
	}
}

type quicSession struct {
	sessionBase
	listener *squic.ConnListener
}

func (s *quicSession) serve() {
	if s.listener == nil {
		panic("serve called before QUIC listener was initialized")
	}
	defer s.listener.Close()
	ctx, cancel := context.WithTimeout(context.Background(), sessionExpiration)
	defer cancel()
	conn, err := s.listener.AcceptCtx(ctx)
	if err != nil && serrors.IsTimeout(err) {
		fmt.Printf("session %d timed out. closing...\n", s.id)
		s.sessionClosedChan <- s.id
		return
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "error listening for QUIC data connections: %s\n", err)
		s.sessionClosedChan <- s.id
		return
	}

	fmt.Printf("session %d starting (QUIC)...\n", s.id)

	sender := conn.RemoteAddr().(*snet.UDPAddr)
	localAddrLen := net.IPv6len
	if v4 := s.local.IP.To4(); v4 != nil {
		localAddrLen = net.IPv4len
	}
	s.bytesReceived = 0
	s.lastReport = time.Now()

	recvBuf := make([]byte, 9000)
	received := 0
	for {
		select {
		case <-s.closeChan:
			return
		default:
			recvBuf = recvBuf[:cap(recvBuf)]
			conn.SetReadDeadline(time.Now().Add(sessionExpiration))
			n, err := conn.Read(recvBuf)
			if err != nil {
				if serrors.IsTimeout(err) || err.Error() == quicErrNoErr {
					fmt.Printf("session %d timed out. closing...\n", s.id)
					s.sessionClosedChan <- s.id
					return
				}
				fmt.Fprintf(os.Stderr, "error reading from conn: %s\n", err)
				s.sessionClosedChan <- s.id
				return
			}
			// Account for SCION Header and throughput.
			received = n + headerLen(sender, localAddrLen)
			s.collectStats(received, sender)
		}
	}
}

func headerLen(sender *snet.UDPAddr, localAddrLen int) int {
	senderAddrLen := net.IPv6len
	if v4 := sender.Host.IP.To4(); v4 != nil {
		senderAddrLen = net.IPv4len
	}
	return slayers.CmnHdrLen +
		2*addr.IABytes +
		senderAddrLen +
		localAddrLen +
		reservation.MetaLen + // Meta header is stripped in reversal.
		len(sender.Path.Raw) +
		8 // UDP/SCION header
}

type ignoreSCMP struct{}

func (ignoreSCMP) Handle(pkt *snet.Packet) error {
	// Always reattempt reads from the socket.
	return nil
}

repository: Anapaya/bwallocation

repo_name: Anapaya/bwallocation


text:
package main

import (
	"bytes"
	"errors"
	"fmt"
	"log"

	"github.com/neelance/chanrpc/example/proto"
	"github.com/neelance/chanrpc/gobcodec"
)

var requestsToServer = make(chan *proto.Request, 100)

func main() {
	go startClient()

	stdout, stderr, err := Exec("test", []string{"abc"})
	fmt.Println(string(stdout), string(stderr), err)
}

func startClient() {
	for {
		err := gobcodec.DialAndDeliver(":7000", requestsToServer)
		log.Printf("DialAndDeliver error, reconnecting: %v", err)
	}
}

func Exec(command string, args []string) ([]byte, []byte, error) {
	replyChan := make(chan *proto.ExecReply, 10)
	requestsToServer <- &proto.Request{Exec: &proto.ExecRequest{
		Command:   command,
		Args:      args,
		ReplyChan: replyChan,
	}}
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	done := false
	for reply := range replyChan {
		stdout.Write(reply.Stdout)
		stderr.Write(reply.Stderr)
		done = reply.Done
	}
	if !done {
		return nil, nil, errors.New("rpc failed")
	}
	return stdout.Bytes(), stderr.Bytes(), nil
}

repository: neelance/chanrpc

repo_name: neelance/chanrpc


text:
@Misc{Kerley2019,
author={Kerley, D.
and Smith, M.
and V{\'e}ran, J.-P.
and Dunn, J.
and Gharavi, N.},
title={Herzberg extensible adaptive real-time toolkit (HEART) software architecture},
year={2019},
month={Jun},
day={09},
publisher={AO4ELT6},
keywords={HEART; RTC; AO; MCAO; MOAO; real-time; adaptive optics},
abstract={The National Research Council of Canada Herzberg (NRC-H) is developing the Herzberg Extensible Adaptive Real-time Toolkit (HEART) for the next generation of Adaptive Optics (AO) systems. HEART is a distributed and scalable software framework that includes a collection of libraries, tools and other software that can be assembled to construct a wide variety of real-time AO control systems. HEART is currently under development, implemented in C/C++, and is intended to run on off-the-shelf CPUs; HEART has evolved from the NRC-H design of the Narrow Field Infrared Adaptive Optics System (NFIRAOS) Real Time Controller (RTC) for the Thirty Meter Telescope (TMT), which passed its final design review. HEART is principally designed for Laser Guide Star (LGS) Multi-Conjugate Adaptive Optics (MCAO), however the modular architecture of HEART lends itself to be restructured for different forms of AO systems, such as: Single Conjugate Adaptive Optics (SCAO), Laser Tomography Adaptive Optics (LTAO), Ground Layer Adaptive Optics (GLAO), and Multi-Object Adaptive Optics (MOAO). The primary goal of HEART is to reduce the development time and cost of next generation AO control systems, while providing more reliable and robust control software that minimizes maintenance effort and promotes code reusability.},
note={Collection / Collection : NRC Publications Archive / Archives des publications du CNRC},
note={Record identifier / Identificateur de l'enregistrement : 58fb69f4-6e92-4c08-bb00-459c91924fb5},
language={eng}
}


text:
DESCRIPTION = "parted, the GNU partition resizing program"
HOMEPAGE = "http://www.gnu.org/software/parted/parted.html"
LICENSE = "GPLv3"
SECTION = "console/tools"
DEPENDS = "readline util-linux-ng lvm2"
PR = "r1"

SRC_URI = "${GNU_MIRROR}/parted/parted-${PV}.tar.gz \
           file://use_llseek_syscall.patch \
           file://fix-MiB-handling.patch \
          "

EXTRA_OECONF = "--disable-Werror ac_cv_func_calloc_0_nonnull=yes"

inherit autotools pkgconfig

SRC_URI[md5sum] = "30ceb6df7e8681891e865e2fe5a7903d"
SRC_URI[sha256sum] = "e81fa140805b5cd029ff6dda5cfa94d223e83ac182ebcae94f841d62ce468829"


text:
SUMMARY = "OpenGL (ES) 2.0 benchmark"
DESCRIPTION = "glmark2 is a benchmark for OpenGL (ES) 2.0. \
It uses only the subset of the OpenGL 2.0 API that is compatible with OpenGL ES 2.0."
HOMEPAGE = "https://launchpad.net/glmark2"
BUGTRACKER = "https://bugs.launchpad.net/glmark2"

LICENSE = "GPLv3+ & SGIv1"
LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504 \
                    file://COPYING.SGI;beginline=5;md5=269cdab4af6748677acce51d9aa13552"

DEPENDS = "libpng12 jpeg"

SRC_URI = "https://launchpad.net/${BPN}/trunk/${PV}/+download/${BP}.tar.gz"

SRC_URI[md5sum] = "4f306664aa3886fa0cf93853603603f8"
SRC_URI[sha256sum] = "bea6f9de2cdce376195bd91e4a2fdfdf80bf3e480abff8e05b90a6458c1deb47"

inherit pkgconfig

PACKAGECONFIG ?= "gl gles2"

PACKAGECONFIG[gl] = "--enable-gl,,virtual/libgl"
PACKAGECONFIG[gles2] = "--enable-glesv2,,virtual/libgles2"

do_configure() {
	./waf configure --prefix=${prefix} ${EXTRA_OECONF}
}

do_compile() {
	./waf build ${PARALLEL_MAKE}
}

do_install() {
	./waf install --destdir=${D}
}

repository: ExorEmbedded/exor-workspace

repo_name: ExorEmbedded/exor-workspace


text:
@article{Geissmann:2017ux,
author = {Geissmann, Thomas},
title = {{A probabilistic approach to the computation of the levelized cost of electricity}},
journal = {Energy},
year = {2017},
volume = {124},
pages = {372--381}
}

path: /Energy_Optim_Project/paper/ERCOT Energy Portfolio Optimization_AER/references.bib


text:
package main

import (
	"fmt"
	"github.com/zhenghaoz/gorse/base"
	"github.com/zhenghaoz/gorse/core"
	"github.com/zhenghaoz/gorse/model"
)

func main() {
	// Load dataset
	data := core.LoadDataFromBuiltIn("ml-100k")
	// Split dataset
	train, test := core.Split(data, 0.2)
	// Create model
	bpr := model.NewBPR(base.Params{
		base.NFactors:   10,
		base.Reg:        0.01,
		base.Lr:         0.05,
		base.NEpochs:    100,
		base.InitMean:   0,
		base.InitStdDev: 0.001,
	})
	// Fit model
	bpr.Fit(train, nil)
	// Evaluate model
	scores := core.EvaluateRank(bpr, test, train, 10, core.Precision, core.Recall, core.NDCG)
	fmt.Printf("Precision@10 = %.5f\n", scores[0])
	fmt.Printf("Recall@10 = %.5f\n", scores[1])
	fmt.Printf("NDCG@10 = %.5f\n", scores[1])
	// Generate recommendations for user(4):
	// Get all items in the full dataset
	items := core.Items(data)
	// Get user(4)'s ratings in the training dataset
	excludeItems := train.User("4")
	// Get top 10 recommended items (excluding rated items) for user(4) using BPR
	recommendItems, _ := core.Top(items, "4", 10, excludeItems, bpr)
	fmt.Printf("Recommend for user(4) = %v\n", recommendItems)
}

repository: mehmetcansahin/gorse

repo_name: mehmetcansahin/gorse


text:
package scalars

import (
	"gqlgen-generator/gen/table"
)

var ScalarMapping map[string]string

const (
	SCALAR_BIGINT      = "Bigint"
	SCALAR_INT         = "Int"
	SCALAR_STRING      = "String"
	SCALAR_FLOAT       = "Float"
	SCALAR_NUMERIC     = "Numeric"
	SCALAR_TIMESTAMPTZ = "Timestamptz"
	SCALAR_POINT       = "Point"
	SCALAR_BOOLEAN     = "Boolean"
)

// 默认的gql类型
var DefaultGqlTypeNamed = SCALAR_STRING

func init() {
	ScalarMapping = make(map[string]string)
	ScalarMapping["int8"] = SCALAR_BIGINT
	ScalarMapping["int4"] = SCALAR_INT
	ScalarMapping["text"] = SCALAR_STRING
	ScalarMapping["timestamptz"] = SCALAR_TIMESTAMPTZ
	ScalarMapping["point"] = SCALAR_POINT
	ScalarMapping["float4"] = SCALAR_FLOAT
	ScalarMapping["bool"] = SCALAR_BOOLEAN
	ScalarMapping["numeric"] = SCALAR_NUMERIC
}

// 根据数据库字段类型获取gql字段类型
func CalculateNamedType(columnInfo table.ColumnInfo) string {

	gqlFieldTypeNamed, ok := ScalarMapping[columnInfo.Columntype]
	if !ok {
		return DefaultGqlTypeNamed
	}
	return gqlFieldTypeNamed
}

// 获取主键的gql字段类型
func GetPrimaryKeyType(table table.TableInfo) string {
	for _, column := range table.Columns {
		if column.Primary {
			return CalculateNamedType(column)
		}
	}
	return ""
}


text:
@article{MR1924594,
 author = {López, F. J. and Martín, F. and Morales, S.},
 fjournal = {Journal of Differential Geometry},
 issn = {0022-040X},
 journal = {J. Differential Geom.},
 mrclass = {53A10},
 mrnumber = {1924594},
 mrreviewer = {Athanase Papadopoulos},
 number = {1},
 pages = {155--175},
 title = {Adding handles to Nadirashvili's surfaces},
 url = {http://projecteuclid.org/euclid.jdg/1090351086},
 volume = {60},
 year = {2002}
}

repository: torralbofco/geometric-analysis-fork

repo_name: torralbofco/geometric-analysis-fork


text:
package p2p

import (
	"context"
	"math/big"
	"sync"
	"testing"
	"time"

	"github.com/libp2p/go-libp2p/core/host"
	"github.com/libp2p/go-libp2p/core/network"
	"github.com/libp2p/go-libp2p/core/peer"
	mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
	"github.com/stretchr/testify/require"

	"github.com/ethereum/go-ethereum"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/log"

	"github.com/ethereum-optimism/optimism/op-node/metrics"
	"github.com/ethereum-optimism/optimism/op-node/rollup"
	"github.com/ethereum-optimism/optimism/op-node/testlog"
	"github.com/ethereum-optimism/optimism/op-service/eth"
)

type mockPayloadFn func(n uint64) (*eth.ExecutionPayload, error)

func (fn mockPayloadFn) PayloadByNumber(_ context.Context, number uint64) (*eth.ExecutionPayload, error) {
	return fn(number)
}

var _ L2Chain = mockPayloadFn(nil)

type syncTestData struct {
	sync.RWMutex
	payloads map[uint64]*eth.ExecutionPayload
}

func (s *syncTestData) getPayload(i uint64) (payload *eth.ExecutionPayload, ok bool) {
	s.RLock()
	defer s.RUnlock()
	payload, ok = s.payloads[i]
	return payload, ok
}

func (s *syncTestData) deletePayload(i uint64) {
	s.Lock()
	defer s.Unlock()
	delete(s.payloads, i)
}

func (s *syncTestData) addPayload(payload *eth.ExecutionPayload) {
	s.Lock()
	defer s.Unlock()
	s.payloads[uint64(payload.BlockNumber)] = payload
}

func (s *syncTestData) getBlockRef(i uint64) eth.L2BlockRef {
	s.RLock()
	defer s.RUnlock()
	return eth.L2BlockRef{
		Hash:       s.payloads[i].BlockHash,
		Number:     uint64(s.payloads[i].BlockNumber),
		ParentHash: s.payloads[i].ParentHash,
		Time:       uint64(s.payloads[i].Timestamp),
	}
}

func setupSyncTestData(length uint64) (*rollup.Config, *syncTestData) {
	// minimal rollup config to build mock blocks & verify their time.
	cfg := &rollup.Config{
		Genesis: rollup.Genesis{
			L1:     eth.BlockID{Hash: common.Hash{0xaa}},
			L2:     eth.BlockID{Hash: common.Hash{0xbb}},
			L2Time: 9000,
		},
		BlockTime: 2,
		L2ChainID: big.NewInt(1234),
	}

	// create some simple fake test blocks
	payloads := make(map[uint64]*eth.ExecutionPayload)
	payloads[0] = &eth.ExecutionPayload{
		Timestamp: eth.Uint64Quantity(cfg.Genesis.L2Time),
	}
	payloads[0].BlockHash, _ = payloads[0].CheckBlockHash()
	for i := uint64(1); i <= length; i++ {
		payload := &eth.ExecutionPayload{
			ParentHash:  payloads[i-1].BlockHash,
			BlockNumber: eth.Uint64Quantity(i),
			Timestamp:   eth.Uint64Quantity(cfg.Genesis.L2Time + i*cfg.BlockTime),
		}
		payload.BlockHash, _ = payload.CheckBlockHash()
		payloads[i] = payload
	}

	return cfg, &syncTestData{payloads: payloads}
}

func TestSinglePeerSync(t *testing.T) {
	t.Parallel() // Takes a while, but can run in parallel

	log := testlog.Logger(t, log.LvlError)

	cfg, payloads := setupSyncTestData(25)

	// Serving payloads: just load them from the map, if they exist
	servePayload := mockPayloadFn(func(n uint64) (*eth.ExecutionPayload, error) {
		p, ok := payloads.getPayload(n)
		if !ok {
			return nil, ethereum.NotFound
		}
		return p, nil
	})

	// collect received payloads in a buffered channel, so we can verify we get everything
	received := make(chan *eth.ExecutionPayload, 100)
	receivePayload := receivePayloadFn(func(ctx context.Context, from peer.ID, payload *eth.ExecutionPayload) error {
		received <- payload
		return nil
	})

	// Setup 2 minimal test hosts to attach the sync protocol to
	mnet, err := mocknet.FullMeshConnected(2)
	require.NoError(t, err, "failed to setup mocknet")
	defer mnet.Close()
	hosts := mnet.Hosts()
	hostA, hostB := hosts[0], hosts[1]
	require.Equal(t, hostA.Network().Connectedness(hostB.ID()), network.Connected)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Setup host A as the server
	srv := NewReqRespServer(cfg, servePayload, metrics.NoopMetrics)
	payloadByNumber := MakeStreamHandler(ctx, log.New("role", "server"), srv.HandleSyncRequest)
	hostA.SetStreamHandler(PayloadByNumberProtocolID(cfg.L2ChainID), payloadByNumber)

	// Setup host B as the client
	cl := NewSyncClient(log.New("role", "client"), cfg, hostB.NewStream, receivePayload, metrics.NoopMetrics, &NoopApplicationScorer{})

	// Setup host B (client) to sync from its peer Host A (server)
	cl.AddPeer(hostA.ID())
	cl.Start()
	defer cl.Close()

	// request to start syncing between 10 and 20
	require.NoError(t, cl.RequestL2Range(ctx, payloads.getBlockRef(10), payloads.getBlockRef(20)))

	// and wait for the sync results to come in (in reverse order)
	for i := uint64(19); i > 10; i-- {
		p := <-received
		require.Equal(t, uint64(p.BlockNumber), i, "expecting payloads in order")
		exp, ok := payloads.getPayload(uint64(p.BlockNumber))
		require.True(t, ok, "expecting known payload")
		require.Equal(t, exp.BlockHash, p.BlockHash, "expecting the correct payload")
	}
}

func TestMultiPeerSync(t *testing.T) {
	t.Parallel() // Takes a while, but can run in parallel

	log := testlog.Logger(t, log.LvlDebug)

	cfg, payloads := setupSyncTestData(100)

	// Buffered channel of all blocks requested from any client.
	requested := make(chan uint64, 100)

	setupPeer := func(ctx context.Context, h host.Host) (*SyncClient, chan *eth.ExecutionPayload) {
		// Serving payloads: just load them from the map, if they exist
		servePayload := mockPayloadFn(func(n uint64) (*eth.ExecutionPayload, error) {
			requested <- n
			p, ok := payloads.getPayload(n)
			if !ok {
				return nil, ethereum.NotFound
			}
			return p, nil
		})

		// collect received payloads in a buffered channel, so we can verify we get everything
		received := make(chan *eth.ExecutionPayload, 100)
		receivePayload := receivePayloadFn(func(ctx context.Context, from peer.ID, payload *eth.ExecutionPayload) error {
			received <- payload
			return nil
		})

		// Setup as server
		srv := NewReqRespServer(cfg, servePayload, metrics.NoopMetrics)
		payloadByNumber := MakeStreamHandler(ctx, log.New("serve", "payloads_by_number"), srv.HandleSyncRequest)
		h.SetStreamHandler(PayloadByNumberProtocolID(cfg.L2ChainID), payloadByNumber)

		cl := NewSyncClient(log.New("role", "client"), cfg, h.NewStream, receivePayload, metrics.NoopMetrics, &NoopApplicationScorer{})
		return cl, received
	}

	// Setup 3 minimal test hosts to attach the sync protocol to
	mnet, err := mocknet.FullMeshConnected(3)
	require.NoError(t, err, "failed to setup mocknet")
	defer mnet.Close()
	hosts := mnet.Hosts()
	hostA, hostB, hostC := hosts[0], hosts[1], hosts[2]
	require.Equal(t, hostA.Network().Connectedness(hostB.ID()), network.Connected)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	clA, recvA := setupPeer(ctx, hostA)
	clB, recvB := setupPeer(ctx, hostB)
	clC, _ := setupPeer(ctx, hostC)

	// Make them all sync from each other
	clA.AddPeer(hostB.ID())
	clA.AddPeer(hostC.ID())
	clA.Start()
	defer clA.Close()
	clB.AddPeer(hostA.ID())
	clB.AddPeer(hostC.ID())
	clB.Start()
	defer clB.Close()
	clC.AddPeer(hostA.ID())
	clC.AddPeer(hostB.ID())
	clC.Start()
	defer clC.Close()

	// request to start syncing between 10 and 90
	require.NoError(t, clA.RequestL2Range(ctx, payloads.getBlockRef(10), payloads.getBlockRef(90)))

	// With such large range to request we are going to hit the rate-limits of B and C,
	// but that means we'll balance the work between the peers.
	for i := uint64(89); i > 10; i-- { // wait for all payloads
		p := <-recvA
		exp, ok := payloads.getPayload(uint64(p.BlockNumber))
		require.True(t, ok, "expecting known payload")
		require.Equal(t, exp.BlockHash, p.BlockHash, "expecting the correct payload")
	}

	// now see if B can sync a range, and fill the gap with a re-request
	bl25, _ := payloads.getPayload(25) // temporarily remove it from the available payloads. This will create a gap
	payloads.deletePayload(25)
	require.NoError(t, clB.RequestL2Range(ctx, payloads.getBlockRef(20), payloads.getBlockRef(30)))
	for i := uint64(29); i > 25; i-- {
		p := <-recvB
		exp, ok := payloads.getPayload(uint64(p.BlockNumber))
		require.True(t, ok, "expecting known payload")
		require.Equal(t, exp.BlockHash, p.BlockHash, "expecting the correct payload")
	}
	// Wait for the request for block 25 to be made
	ctx, cancelFunc := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancelFunc()
	requestMade := false
	for requestMade != true {
		select {
		case blockNum := <-requested:
			if blockNum == 25 {
				requestMade = true
			}
		case <-ctx.Done():
			t.Fatal("Did not request block 25 in a reasonable time")
		}
	}
	// the request for 25 should fail. See:
	// server: WARN  peer requested unknown block by number   num=25
	// client: WARN  failed p2p sync request    num=25 err="peer failed to serve request with code 1"
	require.Zero(t, len(recvB), "there is a gap, should not see other payloads yet")
	// Add back the block
	payloads.addPayload(bl25)
	// race-condition fix: the request for 25 is expected to error, but is marked as complete in the peer-loop.
	// But the re-request checks the status in the main loop, and it may thus look like it's still in-flight,
	// and thus not run the new request.
	// Wait till the failed request is recognized as marked as done, so the re-request actually runs.
	ctx, cancelFunc = context.WithTimeout(context.Background(), 30*time.Second)
	defer cancelFunc()
	for {
		isInFlight, err := clB.isInFlight(ctx, 25)
		require.NoError(t, err)
		if !isInFlight {
			break
		}
		time.Sleep(time.Second)
	}
	// And request a range again, 25 is there now, and 21-24 should follow quickly (some may already have been fetched and wait in quarantine)
	require.NoError(t, clB.RequestL2Range(ctx, payloads.getBlockRef(20), payloads.getBlockRef(26)))
	for i := uint64(25); i > 20; i-- {
		p := <-recvB
		exp, ok := payloads.getPayload(uint64(p.BlockNumber))
		require.True(t, ok, "expecting known payload")
		require.Equal(t, exp.BlockHash, p.BlockHash, "expecting the correct payload")
	}
}

repository: ethereum-optimism/optimism

repo_name: ethereum-optimism/optimism

branch_name: refs/heads/develop


text:
@article{las-05-portal-journal,
 abstract = {Computational scientists often develop large models and codes intended to be used by larger user communities or for repetitive tasks such as parametric studies. Lowering the barrier of entry for access to these codes is often a technical and sociological challenge. Portals help bridge the gap because they are well known interfaces enabling access to a large variety of resources, services, applications, and tools for private, public, and commercial entities, while hiding the complexities of the underlying software systems to the user. This paper presents an overview of the current state-of-the-art in grid portals, based on a component approach that utilizes portlet frameworks and the most recent Grid standards, the Web Services Resource Framework and a summary of current DOE portal efforts.},
 author = {Thomas, M P and J Burruss and L Cinquini and G Fox and D Gannon and L Gilbert and von Laszewski, Gregor and K Jackson and D Middleton and R Moore and M Pierce and B Plale and A Rajasekar and R Regno and E Roberts and D Schissel and A Seth and W Schroeder},
 doi = {10.1088/1742-6596/16/1/083},
 journal = {Journal of Physics: Conference Series},
 month = {jan},
 pages = {596--600},
 publisher = {IOP Publishing},
 title = {Grid portal architectures for scientific applications},
 url = {https://laszewski.github.io/papers/las-05-portal-journal.pdf},
 urlother = {https://iopscience.iop.org/article/10.1088/1742-6596/16/1/083/pdf},
 volume = {16},
 year = {2005}
}


text:
include(FindPackageHandleStandardArgs)

set(CUDNN_ROOT_DIR ${PROJECT_SOURCE_DIR}/third_party/cudnn CACHE PATH "Folder contains NVIDIA cuDNN")

set(CUDNN_DIR ${CUDNN_ROOT_DIR} ${CUDA_TOOLKIT_ROOT_DIR} /usr /usr/local)

find_path(CUDNN_INCLUDE_DIRS
          NAMES cudnn.h
          PATHS ${CUDNN_DIR}
          PATH_SUFFIXES include include/x86_64 include/x64
          NO_DEFAULT_PATH)

find_library(CUDNN_LIBRARIES
             NAMES cudnn
             PATHS ${CUDNN_DIR}
             PATH_SUFFIXES lib lib64 lib/x86_64 lib/x64 lib/x86_64-linux-gnu lib/aarch64-linux-gnu
             NO_DEFAULT_PATH)

set(__looked_for CUDNN_INCLUDE_DIRS CUDNN_LIBRARIES)

find_package_handle_standard_args(CUDNN DEFAULT_MSG ${__looked_for})

if (CUDNN_FOUND)
  parse_header(${CUDNN_INCLUDE_DIRS}/cudnn.h
               CUDNN_MAJOR CUDNN_MINOR CUDNN_PATCHLEVEL)
  if (NOT CUDNN_MAJOR)
    set(CUDNN_VERSION "?")
  else ()
    set(CUDNN_VERSION "${CUDNN_MAJOR}.${CUDNN_MINOR}.${CUDNN_PATCHLEVEL}")
  endif ()
  if (NOT CUDNN_FIND_QUIETLY)
    message(STATUS "Found CUDNN: ${CUDNN_INCLUDE_DIRS}, ${CUDNN_LIBRARIES} (found version ${CUDNN_VERSION})")
  endif ()
  mark_as_advanced(CUDNN_ROOT_DIR ${__looked_for})
else ()
  if (CUDNN_FIND_REQUIRED)
    message(FATAL_ERROR "Could not find CUDNN")
  endif ()
endif ()

extension: cmake