text:
#
#   Copyright 2016 RIFT.IO 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.
#
# Author(s): Anil Gunturu
# Creation Date: 8/29/2013
#

# This module looks for gobject-introspection,
#  and sets the following variables
# RIFT_GLIB2_FOUND         - set to 1 if module(s) exist
# RIFT_GLIB2_LIBRARIES     - only the libraries (w/o the '-l')
# RIFT_GLIB2_LIBRARY_DIRS  - the paths of the libraries (w/o the '-L')
# RIFT_GLIB2_LDFLAGS       - all required linker flags
# RIFT_GLIB2_LDFLAGS_OTHER - all other linker flags
# RIFT_GLIB2_INCLUDE_DIRS  - the '-I' preprocessor flags (w/o the '-I')
# RIFT_GLIB2_CFLAGS        - all required cflags
# RIFT_GLIB2_CFLAGS_OTHER  - the other compiler flags

cmake_minimum_required(VERSION 2.8)

include(FindPkgConfig)

if(NOT PKG_CONFIG_FOUND)
  message(FATAL_ERROR "PKG CONFIG NOT FOUND")
endif()

# This cmake function searches the .pc files
# and sets the above mentioned varibales
pkg_check_modules(RIFT_GLIB2 glib-2.0)

set(DEBUG_FindRIFT_GLIB2 0)
if(DEBUG_FindRIFT_GLIB2)
  message("RIFT_GLIB2_FOUND = ${RIFT_GLIB2_FOUND}")
  message("RIFT_GLIB2_LIBRARIES = ${RIFT_GLIB2_LIBRARIES}")
  message("RIFT_GLIB2_LIBRARY_DIRS = ${RIFT_GLIB2_LIBRARY_DIRS}")
  message("RIFT_GLIB2_LDFLAGS = ${RIFT_GLIB2_LDFLAGS}")
  message("RIFT_GLIB2_LDFLAGS_OTHER = ${RIFT_GLIB2_LDFLAGS_OTHER}")
  message("RIFT_GLIB2_INCLUDE_DIRS = ${RIFT_GLIB2_INCLUDE_DIRS}")
  message("RIFT_GLIB2_CFLAGS = ${RIFT_GLIB2_CFLAGS}")
  message("RIFT_GLIB2_CFLAGS_OTHER = ${RIFT_GLIB2_CFLAGS_OTHER}")
endif()


text:
require recipes-devtools/quilt/${PN}_0.61.bb
FILESEXTRAPATHS_prepend = "${THISDIR}/files:${COREBASE}/meta/recipes-devtools/quilt/quilt:"

inherit debian-package
DEBIAN_SECTION = "vcs"

DPR = "0"

LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=94d55d512a9ba36caa9b7df079bae19f"

SRC_URI += " \
file://install.patch \
file://run-ptest \
file://Makefile \
"

# quilt-native also depends on native quilt command.
# This is a special overwritten to apply all patches in
# the quilt source without native quilt command.
debian_patch_quilt() {
	bbnote "applying all patches without quilt command"

	PATCH_DIR=${DEBIAN_UNPACK_DIR}/debian/patches
	if [ ! -s ${PATCH_DIR}/series ]; then
		bbfatal "no patch in series"
	fi
	for patch in $(sed "s@#.*@@" ${PATCH_DIR}/series); do
		bbnote "applying $patch"
		patch -p1 < ${PATCH_DIR}/${patch}
	done
}

#
# Debian Native Test
#
inherit debian-test

SRC_URI_DEBIAN_TEST = "\
        file://quilt-native-test/run_native_test_quilt \
	file://quilt-native-test/run_help_command \
	file://quilt-native-test/run_version_command \
	file://quilt-native-test/run_trace_command \
	file://quilt-native-test/run_series_command \
	file://quilt-native-test/run_top_command \
	file://quilt-native-test/run_pop_command \
	file://quilt-native-test/run_import_command \
	file://quilt-native-test/run_push_command \
	file://quilt-native-test/03_test \
	file://quilt-native-test/add.c \
"

DEBIAN_NATIVE_TESTS = "run_native_test_quilt"
TEST_DIR = "${B}/quilt-native-test"

license: MIT

repository: takuya-t/meta-debian

license_type: permissive

repo_name: takuya-t/meta-debian

branch_name: refs/heads/daisy

extension: bb


text:
package state

import (
	"github.com/pkg/errors"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"

	"github.com/pulumi/pulumi-terraform/sdk/v5/go/state/internal"
)

// ConsulArgs specifies the configuration options for a Terraform Remote State
// stored in the Consul backend
type ConsulArgs struct {
	// Path is the path in the Consul KV store
	Path pulumi.StringInput

	// AccessToken is the Consul Access Token. Sourced from `CONSUL_HTTP_TOKEN` in the environment, if unset.
	AccessToken pulumi.StringInput

	// Address is the DNS name and port of the Consul HTTP endpoint specified in the format `dnsname:port`. Defaults
	// to the local agent HTTP listener.
	Address pulumi.StringPtrInput

	// Scheme specifies which protocol to use when talking to the given address - either `http` or `https`. TLS
	// support can also be enabled by setting the environment variable `CONSUL_HTTP_SSL` to `true`.
	Schema pulumi.StringPtrInput

	// Datacenter is the datacenter to use. Defaults to that of the agent.
	Datacenter pulumi.StringPtrInput

	// HttpAuth is the HTTP Basic Authentication credentials to be used when communicating with Consul, in the
	// format of either `user` or `user:pass`. Sourced from `CONSUL_HTTP_AUTH`, if unset.
	HttpAuth pulumi.StringPtrInput

	// Gzip is whether to compress the state data using gzip. Set to `true` to compress the state data using gzip,
	// or `false` (default) to leave it uncompressed.
	Gzip pulumi.BoolPtrInput

	// CAFile is the path to a PEM-encoded certificate authority used to verify the remote agent's certificate.
	// Sourced from `CONSUL_CAFILE` in the environment, if unset.
	CAFile pulumi.StringPtrInput

	// CertFile is the path to a PEM-encoded certificate provided to the remote agent; requires use of key_file.
	// Sourced from `CONSUL_CLIENT_CERT` in the environment, if unset.
	CertFile pulumi.StringPtrInput

	// KeyFile is the path to a PEM-encoded private key, required if cert_file is specified. Sourced from
	// `CONSUL_CLIENT_KEY` in the environment, if unset.
	KeyFile pulumi.StringPtrInput

	// Workspace os the Terraform workspace from which to read state.
	Workspace pulumi.StringPtrInput
}

func (a *ConsulArgs) toInternalArgs() pulumi.Input {
	return internal.ConsulStateReferenceArgs{
		BackendType: pulumi.String("consul"),
		Path:        a.Path,
		AccessToken: a.AccessToken,
		Address:     a.Address,
		Scheme:      a.Schema,
		Datacenter:  a.Datacenter,
		HttpAuth:    a.HttpAuth,
		Gzip:        a.Gzip,
		CAFile:      a.CAFile,
		CertFile:    a.CertFile,
		KeyFile:     a.KeyFile,
		Workspace:   a.Workspace,
	}
}

func (l *ConsulArgs) validateArgs() error {
	if l.Path == pulumi.String("") || l.AccessToken == pulumi.String("") {
		return errors.New("`Path` and `Path` are required parameters")
	}
	return nil
}

repository: pulumi/pulumi-terraform

repo_name: pulumi/pulumi-terraform

branch_name: refs/heads/master

gha_language: Go

extension: go


text:
package bases

import (
	"regexp"
)

//返回需要读取的字符串列表
func ReadNum(text string) []string {
	//这里必须使用非贪婪模式
	reg := regexp.MustCompile(`\[([\w\W\d-]+?)\]`)
	data := reg.FindAllStringSubmatch(text, -1)

	var res []string
	for _, dt := range data {
		res = append(res, dt[1])
	}

	return res
}

//返回需要读取的文本文字
func ReadText(text string) string {
	//这里必须使用非贪婪模式
	reg := regexp.MustCompile(`\[([\w\W\d-]+?)\](.*)`)
	data := reg.FindAllStringSubmatch(text, -1)

	var res string
	for _, dt := range data {
		res = dt[2]
	}

	return res
}

repository: zjlwmz/office-parser

repo_name: zjlwmz/office-parser


text:
package main

import "fmt"

func main() {
	s1 := "aa"
	s2 := "bb"
	fmt.Println(s1<s2)
}

repository: hunanhfh/MyCodingNotes

repo_name: hunanhfh/MyCodingNotes


text:
require ${PN}.inc

SRC_URI = "${HANDHELDS_CVS};tag=${TAG};module=opie/core/${APPNAME} \
	   ${HANDHELDS_CVS};tag=${TAG};module=opie/core/apps/calibrate \
	   ${HANDHELDS_CVS};tag=${TAG};module=opie/core/launcher \
	   file://opie-session \
	   file://post-session \
	   file://pre-session \
	   file://opie-login.conf"


text:
@Article {ms-marco,
author = {Nguyen, Tri and Rosenberg, Mir and Song, Xia and Gao, Jianfeng and Tiwary, Saurabh and Majumder, Rangan and },
title = {MS MARCO: A Human Generated MAchine Reading COmprehension Dataset},
year = {2016},
month = {November},
}

gha_license_id: MIT

gha_language: Python

extension: bib


text:
package main

import (
    //"io"
    "net/http"
    "log"
    "os/exec"
    "encoding/json"
    "bytes"
    //"fmt"
    //"io/ioutil"
    "os"
)

func handleCors(w http.ResponseWriter) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
    w.Header().Set("Access-Control-Max-Age", "3600")
    w.Header().Set("Access-Control-Allow-Headers",
        "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
}

func runPython(w http.ResponseWriter, r *http.Request) {
    defer exec.Command("rm", "test.py").Start()

    handleCors(w)

    var code Code

    buf := new(bytes.Buffer)
    buf.ReadFrom(r.Body)
    json.Unmarshal(buf.Bytes(), &code)

    f, err := os.Create("./test.py")
    if err != nil {
        log.Fatal(err)
    }

    _, err = f.WriteString(code.Content)
    if err != nil {
        log.Fatal(err)
    }

    f.Sync()
    f.Close()

    cmd := exec.Command("python", "test.py")
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }
    stderr, err := cmd.StderrPipe()
    if err != nil {
        log.Fatal(err)
    }
    err = cmd.Start();
    if err != nil {
        log.Fatal(err)
    }

    stdoutbuf := new(bytes.Buffer)
    stdoutbuf.ReadFrom(stdout)
    stderrbuf := new(bytes.Buffer)
    stderrbuf.ReadFrom(stderr)
    out := STDOut{Language: "Python",
        Output: stdoutbuf.String(),
        Error: stderrbuf.String()}
    b, err := json.Marshal(out)
    w.Write(b)
}

func runGo(w http.ResponseWriter, r *http.Request) {
    defer exec.Command("rm", "test.go").Start()

    handleCors(w)

    var code Code

    buf := new(bytes.Buffer)
    buf.ReadFrom(r.Body)
    json.Unmarshal(buf.Bytes(), &code)
    f, err := os.Create("./test.go")
    if err != nil {
        log.Fatal(err)
    }

    _, err = f.WriteString(code.Content)
    if err != nil {
        log.Fatal(err)
    }

    f.Sync()
    f.Close()

    cmd := exec.Command("go", "run", "test.go")
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }
    stderr, err := cmd.StderrPipe()
    if err != nil {
        log.Fatal(err)
    }
    err = cmd.Start();
    if err != nil {
        log.Fatal(err)
    }

    stdoutbuf := new(bytes.Buffer)
    stdoutbuf.ReadFrom(stdout)
    stderrbuf := new(bytes.Buffer)
    stderrbuf.ReadFrom(stderr)
    out := STDOut{Language: "Go",
        Output: stdoutbuf.String(),
        Error: stderrbuf.String()}
    b, err := json.Marshal(out)
    w.Write(b)
}

func runPythonDocker(w http.ResponseWriter, r *http.Request) {
    handleCors(w);

    var code Code

    buf := new(bytes.Buffer)
    buf.ReadFrom(r.Body)
    json.Unmarshal(buf.Bytes(), &code)

    files := []File {
        File {
            name: "main.py",
            content: code.Content,
        },
    }

    out := STDOut{Language: "Python",
        Output: CreateContainer("python", files),
        Error: ""}
    b, err := json.Marshal(out);

    if err != nil {
        log.Fatal(err)
    }

    w.Write(b)
}

func runHaskellDocker(w http.ResponseWriter, r *http.Request) {
    handleCors(w);

    var code Code

    buf := new(bytes.Buffer)
    buf.ReadFrom(r.Body)
    json.Unmarshal(buf.Bytes(), &code)

    files := []File {
        File {
            name: "main.hs",
            content: code.Content,
        },
    }

    out := STDOut{Language: "Haskell",
        Output: CreateContainer("haskell", files),
        Error: ""}
    b, err := json.Marshal(out);

    if err != nil {
        log.Fatal(err)
    }

    w.Write(b)
}

func runGoDocker(w http.ResponseWriter, r *http.Request) {
    handleCors(w);

    var code Code

    buf := new(bytes.Buffer)
    buf.ReadFrom(r.Body)
    json.Unmarshal(buf.Bytes(), &code)

    files := []File {
        File {
            name: "main.go",
            content: code.Content,
        },
    }

    out := STDOut{Language: "Golang",
        Output: CreateContainer("golang", files),
        Error: ""}
    b, err := json.Marshal(out);

    if err != nil {
        log.Fatal(err)
    }

    w.Write(b)
}

func main() {
    hub := NewHub()
    go hub.Run()
    http.HandleFunc("/run/go", runGo)
    http.HandleFunc("/run/python", runPython)
    http.HandleFunc("/docker/run/python", runPythonDocker)
    http.HandleFunc("/docker/run/go", runGoDocker)
    http.HandleFunc("/docker/run/haskell", runHaskellDocker)
    http.HandleFunc("/share", func(w http.ResponseWriter, r *http.Request) {
        HandleCodeShare(hub, w, r)
    })
    err := http.ListenAndServe(":8000", nil)
    if err != nil {
        log.Println(err)
    }
}

repository: JGMorgan/Code-Cave

repo_name: JGMorgan/Code-Cave


text:
DEPENDS = "freetype"
DESCRIPTION = "TuxCom for dreambox 8000/32bit framebuffer"
MAINTAINER = "Sven Karschewski <seddi@i-have-a-dreambox.com>"

SRC_URI = "cvs://anoncvs@cvs.tuxbox.org/cvs/tuxbox;module=apps/tuxbox/plugins/tuxcom;method=ext \
	file://makefiles.diff \
	file://add_font.diff \
	file://32bpp.diff \
	file://add_e2_plugin.diff \
	file://add_advanced_rc.diff"

PV = "0.0+cvs${SRCDATE}"
PR = "r0"

PACKAGES = "${PN}-dbg ${PN}"

S = "${WORKDIR}/tuxcom"

CFLAGS_append = " -DHAVE_DREAMBOX_HARDWARE -DDREAMBOX"

inherit autotools pkgconfig

bindir = "/usr/bin"
sbindir = "/usr/sbin"

EXTRA_OECONF = "--with-target=native"

do_configure_prepend() {
	touch ${S}/python/__init__.py
}

do_install() {
	install -d ${D}/etc/tuxcom
	install -d ${D}/usr/plugins
	install -d ${D}/usr/share/fonts
	install -d ${D}/usr/lib/enigma2/python/Plugins/Extensions/Tuxcom

	install -m 0755 ${S}/tuxcom ${D}/usr/plugins/tuxcom
	install -m 0644 ${S}/tuxcom.cfg ${D}/etc/tuxcom/tuxcom.cfg
	install -m 0644 ${S}/font/pakenham.ttf ${D}/usr/share/fonts/pakenham.ttf
	install -m 0644 ${S}/python/__init__.py ${D}/usr/lib/enigma2/python/Plugins/Extensions/Tuxcom/__init__.py
	install -m 0644 ${S}/python/plugin.py ${D}/usr/lib/enigma2/python/Plugins/Extensions/Tuxcom/plugin.py
}

FILES_${PN}-dbg ="/usr/plugins/.debug"
FILES_${PN} = "/etc/tuxcom/tuxcom.cfg /usr/plugins/tuxcom /usr/share/fonts/pakenham.ttf /usr/lib/enigma2/python/Plugins/Extensions/Tuxcom/__init__.py \
		/usr/lib/enigma2/python/Plugins/Extensions/Tuxcom/plugin.py"

gha_language: C


text:
//nolint:golint
package cert_manager

import (
	"bytes"
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
	"net/http"
	"reflect"
	"strings"
	"sync"
	"time"

	"github.com/rekby/lets-proxy2/internal/domain"

	"github.com/rekby/lets-proxy2/internal/contexthelper"

	"github.com/rekby/lets-proxy2/internal/metrics"

	"github.com/prometheus/client_golang/prometheus"

	"golang.org/x/xerrors"

	"github.com/rekby/lets-proxy2/internal/cache"
	"go.uber.org/zap/zapcore"

	"github.com/rekby/lets-proxy2/internal/log"

	zc "github.com/rekby/zapcontext"
	"go.uber.org/zap"
	"golang.org/x/crypto/acme"
)

const (
	tlsAlpn01     = "tls-alpn-01"
	http01        = "http-01"
	httpWellKnown = "/.well-known/acme-challenge/"
)

var (
	insecureChipers map[uint16]struct{}
)

func init() {
	insecureChipersSlice := tls.InsecureCipherSuites()
	insecureChipers = make(map[uint16]struct{}, len(insecureChipersSlice))
	for _, chiper := range tls.InsecureCipherSuites() {
		insecureChipers[chiper.ID] = struct{}{}
	}
}

const domainKeyRSALength = 2048
const renewBeforeExpire = time.Hour * 24 * 30
const revokeAuthorizationTimeout = 5 * time.Minute
const cleanupTimeout = time.Minute

var errHaveNoCert = errors.New("have no certificate for domain") // may return for any internal error
var errRSADenied = xerrors.New("RSA certificate denied by config")
var errECDSADenied = xerrors.New("ECDSA certificate denied by config")
var errCertTypeUnknown = xerrors.New("unknown cert type")

type GetContext interface {
	GetContext() context.Context
}

type KeyType string

const KeyRSA KeyType = "rsa"
const KeyECDSA KeyType = "ecdsa"

func (t KeyType) Generate() (crypto.Signer, error) {
	switch t {
	case KeyRSA:
		return rsa.GenerateKey(rand.Reader, domainKeyRSALength)
	case KeyECDSA:
		return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	default:
		panic("Unexpected key type for generate: " + t.String())
	}
}

func (t KeyType) String() string {
	return string(t)
}

// Manager interface inspired to https://godoc.org/golang.org/x/crypto/acme/autocert#Manager but not compatible guarantee
type Manager struct {
	CertificateIssueTimeout time.Duration
	Cache                   cache.Bytes

	// Subdomains, auto-issued with main domain.
	// Every subdomain must have suffix dot. For example: "www."
	AutoSubdomains []string

	acmeClientManager       AcmeClientManager
	DomainChecker           DomainChecker
	EnableHTTPValidation    bool
	EnableTLSValidation     bool
	SaveJSONMeta            bool
	AllowECDSACert          bool
	AllowRSACert            bool
	AllowInsecureTLSChipers bool

	certForDomainAuthorize cache.Value

	certStateMu sync.Mutex
	certState   cache.Value

	httpTokens cache.Bytes

	// metrics
	handleCertStart, certRequestStart   metrics.ProcessStartFunc
	handleCertFinish, certRequestFinish metrics.ProcessFinishFunc
}

func New(acmeClientManager AcmeClientManager, c cache.Bytes, r prometheus.Registerer) *Manager {
	res := Manager{}
	res.acmeClientManager = acmeClientManager
	res.certForDomainAuthorize = cache.NewMemoryValueLRU("authcert")
	res.certState = cache.NewMemoryValueLRU("certstate")
	res.CertificateIssueTimeout = time.Minute
	res.httpTokens = cache.NewMemoryCache("Http validation tokens")
	res.Cache = c
	res.EnableTLSValidation = true
	res.DomainChecker = managerDefaults{}
	res.AllowRSACert = true
	res.AllowECDSACert = true

	res.initMetrics(r)
	return &res
}

// GetCertificate implements the tls.Config.GetCertificate hook.
func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (resultCert *tls.Certificate, err error) {
	m.handleCertStart()
	defer func() {
		m.handleCertFinish(err)
	}()
	ctx := hello.Conn.(GetContext).GetContext()

	logger := zc.L(ctx)

	m.filterTlsHello(ctx, hello)

	needDomain, err := domain.NormalizeDomain(hello.ServerName)
	log.DebugInfo(logger, err, "Domain name normalization", zap.String("original", hello.ServerName), domain.LogDomain(needDomain))
	if err != nil {
		return nil, errHaveNoCert
	}

	logger = logger.With(domain.LogDomain(needDomain))
	ctx = zc.WithLogger(ctx, logger)
	defer log.HandlePanic(logger)

	logger.Info("Get certificate", zap.String("original_domain", hello.ServerName))
	if isTLSALPN01Hello(hello) {
		return m.handleTLSALPN(ctx, needDomain)
	}

	certType := KeyRSA
	if supportsECDSA(hello) {
		certType = KeyECDSA
	}
	cert, err := m.getCertificate(ctx, needDomain, certType)
	log.DebugInfo(logger, err, "Got certificate", log.Cert(cert))
	if err == nil || certType == KeyRSA {
		return cert, err
	}

	logger.Info("ECDSA certificate was failed, try to get RSA certificate")
	ctx = zc.WithLogger(ctx, logger.With(zap.String("retry_type", "rsa")))
	return m.getCertificate(ctx, needDomain, KeyRSA)
}

//nolint:funlen,gocognit
func (m *Manager) getCertificate(ctx context.Context, needDomain domain.DomainName, certType KeyType) (resultCert *tls.Certificate, err error) {
	switch certType {
	case KeyRSA:
		if !m.AllowRSACert {
			return nil, errRSADenied
		}
	case KeyECDSA:
		if !m.AllowECDSACert {
			return nil, errECDSADenied
		}
	default:
		return nil, errCertTypeUnknown
	}

	certDescription := CertDescriptionFromDomain(needDomain, certType, m.AutoSubdomains)

	logger := zc.L(ctx).With(certDescription.ZapField())
	ctx = zc.WithLogger(ctx, zc.L(ctx).With(certDescription.ZapField()))

	now := time.Now()

	var locked = false
	var lockedChecked = false

	defer func() {
		if isNeedRenew(resultCert, now) {
			if !lockedChecked {
				locked, err = isCertLocked(ctx, m.Cache, certDescription)
				log.DebugError(logger, err, "Check locked before renew", zap.Bool("locked", locked))
				if err != nil {
					return
				}
			}
			if !locked {
				// handlepanic: in renewCertInBackground
				go m.renewCertInBackground(ctx, needDomain, certDescription)
			}
		}
	}()

	certState := m.certStateGet(ctx, certDescription)
	cert, err := certState.Cert()
	if cert != nil {
		logger.Debug("Got certificate from local state", log.Cert(cert))

		cert, err = validCertTLS(cert, []domain.DomainName{needDomain}, certState.GetUseAsIs(), now)
		logger.Debug("Validate certificate from local state", zap.Error(err))
		if err == nil {
			return cert, nil
		}
	}
	if err != nil {
		logLevel := zapcore.ErrorLevel
		if err == cache.ErrCacheMiss {
			logLevel = zapcore.DebugLevel
		}
		log.LevelParam(logger, logLevel, "Can't get certificate from local state", zap.Error(err))
		if logLevel == zapcore.ErrorLevel {
			return nil, errHaveNoCert
		}
	}

	locked, err = isCertLocked(ctx, m.Cache, certDescription)
	lockedChecked = true
	log.DebugDPanic(logger, err, "Check if certificate locked", zap.Bool("locked", locked))
	if err != nil {
		return nil, errHaveNoCert
	}

	cert, err = loadCertificateFromCache(ctx, m.Cache, certDescription)
	logLevel := zapcore.ErrorLevel
	if err == nil || err == cache.ErrCacheMiss {
		logLevel = zapcore.DebugLevel
	}
	log.LevelParam(logger, logLevel, "Load certificate from cache", zap.Error(err))

	if err == nil {
		cert, err = validCertDer([]domain.DomainName{needDomain}, cert.Certificate, cert.PrivateKey, locked, now)
		logger.Debug("Check if certificate ok", zap.Error(err))
		if err == nil {
			certState.CertSet(ctx, locked, cert)
			return cert, nil
		}
	}
	if err != cache.ErrCacheMiss && err != errCertExpired {
		return nil, errHaveNoCert
	}

	if locked {
		return nil, errHaveNoCert
	}

	return m.issueNewCert(ctx, needDomain, certDescription)
}

func (m *Manager) issueNewCert(ctx context.Context, needDomain domain.DomainName, cd CertDescription) (cert *tls.Certificate, err error) {
	m.certRequestStart()
	defer func() {
		m.certRequestFinish(err)
	}()
	logger := zc.L(ctx)

	allowed, err := m.DomainChecker.IsDomainAllowed(ctx, needDomain.ASCII())
	log.DebugError(logger, err, "Check if domain allowed for certificate", zap.Bool("allowed", allowed))
	if err != nil {
		return nil, errHaveNoCert
	}
	if !allowed {
		logger.Info("Deny certificate issue by filter")
		return nil, errHaveNoCert
	}
	certIssueContext, cancelFunc := context.WithTimeout(ctx, m.CertificateIssueTimeout)
	defer cancelFunc()

	domains := cd.DomainNames()
	domains, err = filterDomains(ctx, m.DomainChecker, domains, needDomain)
	log.DebugError(logger, err, "Filter domains", domain.LogDomains(domains))

	res, err := m.createCertificateForDomains(certIssueContext, cd, domains)
	if err == nil {
		logger.Info("Certificate issued.", log.Cert(res),
			zap.Time("expire", res.Leaf.NotAfter))
		return res, nil
	}
	logger.Warn("Can't issue certificate", zap.Error(err))
	return nil, errHaveNoCert
}

func (m *Manager) handleTLSALPN(ctx context.Context, needDomain domain.DomainName) (*tls.Certificate, error) {
	logger := zc.L(ctx)
	logger.Debug("It is tls-alpn-01 token request.")
	certInterface, err := m.certForDomainAuthorize.Get(ctx, needDomain.String())
	logger.Debug("Got authcert from cache", zap.Error(err))
	cert, _ := certInterface.(*tls.Certificate)
	if cert == nil {
		logger.Warn("Doesn't have token for request domain")
		return nil, errHaveNoCert
	}
	return cert, nil
}

func filterDomains(ctx context.Context, checker DomainChecker, originalDomains []domain.DomainName, needDomain domain.DomainName) ([]domain.DomainName, error) {
	logger := zc.L(ctx)
	logger.Debug("filter domains from certificate list", domain.LogDomains(originalDomains))
	var allowedDomains = make(chan domain.DomainName, len(originalDomains))
	var hasNeedDomain bool
	var wg sync.WaitGroup

	wg.Add(len(originalDomains))

	for _, d := range originalDomains {
		d := d // pin var

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

			allow, err := checker.IsDomainAllowed(ctx, d.ASCII())
			logger.Debug("Check domain", domain.LogDomain(d), zap.Bool("allowed", allow), zap.Error(err))
			if !allow {
				return
			}

			if d == needDomain {
				hasNeedDomain = true
			}

			allowedDomains <- d
		}()
	}

	wg.Wait()
	close(allowedDomains)

	if !hasNeedDomain {
		return nil, errors.New("need domain doesn't contained to cert list domains after filter")
	}

	res := make([]domain.DomainName, 0, len(allowedDomains))
	for domain := range allowedDomains {
		res = append(res, domain)
	}
	return res, nil
}

func (m *Manager) certStateGet(ctx context.Context, cd CertDescription) *certState {
	m.certStateMu.Lock()
	defer m.certStateMu.Unlock()

	resInterface, err := m.certState.Get(ctx, cd.String())
	if err == cache.ErrCacheMiss {
		err = nil
	}
	log.DebugFatalCtx(ctx, err, "Got cert state from cache", zap.Bool("is_empty", resInterface == nil))
	if resInterface == nil {
		resInterface = &certState{}
		err = m.certState.Put(ctx, cd.String(), resInterface)
		log.DebugFatalCtx(ctx, err, "Put empty cert state to cache")
	}
	return resInterface.(*certState)
}

func (m *Manager) createCertificateForDomains(ctx context.Context, cd CertDescription, domainNames []domain.DomainName) (res *tls.Certificate, err error) {
	logger := zc.L(ctx).With(domain.LogDomains(domainNames))
	certState := m.certStateGet(ctx, cd)

	if !certState.StartIssue(ctx) {
		waitTimeout, waitTimeoutCancel := context.WithTimeout(ctx, m.CertificateIssueTimeout)
		defer waitTimeoutCancel()

		logger.Debug("Certificate issue in process already - wait result")
		return certState.WaitFinishIssue(waitTimeout)
	}
	// outer func need for get argument values in defer time
	defer func() {
		certState.FinishIssue(ctx, res, err)
	}()

	logger.Debug("Start issue process")

	for {
		acmeClient, acmeClientDisableFunc, err := m.acmeClientManager.GetClient(ctx)
		log.DebugError(logger, err, "Get acme client")
		if err != nil {
			return nil, xerrors.Errorf("failed to get acme client: %w", err)
		}

		res, err := m.createOrderAndCertificate(ctx, acmeClient, cd, domainNames)
		switch {
		case err == nil:
			return res, nil
		case isErrTooManyOrders(err):
			logger.Info("Too many orders, try next client")
			acmeClientDisableFunc()
			continue
		default:
			return nil, err
		}
	}
}

func (m *Manager) createOrderAndCertificate(ctx context.Context, acmeClient AcmeClient, cd CertDescription, domainNames []domain.DomainName) (*tls.Certificate, error) {
	logger := zc.L(ctx)

	order, err := m.createOrderForDomains(ctx, acmeClient, domainNames...)
	log.DebugWarning(logger, err, "Domains authorized")
	if err != nil {
		return nil, errors.New("order authorization error")
	}

	res, err := m.issueCertificate(ctx, acmeClient, cd, order)
	log.DebugWarning(logger, err, "Issue certificate")
	return res, err
}

func (m *Manager) supportedChallenges() []string {
	var allowedChallenges []string
	if m.EnableTLSValidation {
		allowedChallenges = append(allowedChallenges, tlsAlpn01)
	}
	if m.EnableHTTPValidation {
		allowedChallenges = append(allowedChallenges, http01)
	}
	return allowedChallenges
}

// createOrderForDomains similar to func (m *Manager) verifyRFC(ctx context.Context, client *acme.Client, domain string) (*acme.Order, error)
// from acme/autocert
//
//nolint:funlen,gocognit
func (m *Manager) createOrderForDomains(ctx context.Context, acmeClient AcmeClient, domains ...domain.DomainName) (*acme.Order, error) {
	logger := zc.L(ctx)
	challengeTypes := m.supportedChallenges()
	logger.Debug("Start order authorization.")
	var order *acme.Order

	firstLoop := true
authorizeOrderLoop:
	for {
		if ctx.Err() != nil {
			return nil, xerrors.Errorf("context canceled: %w", ctx.Err())
		}

		if firstLoop {
			firstLoop = false
		} else {
			time.Sleep(time.Second)
		}
		authIDs := make([]acme.AuthzID, len(domains))
		for i := range domains {
			authIDs[i] = acme.AuthzID{Type: "dns", Value: domains[i].ASCII()}
		}
		var err error
		order, err = acmeClient.AuthorizeOrder(ctx, authIDs)
		log.DebugError(logger, err, "Create authorization order.", zap.Reflect("order", order))
		if err != nil {
			return nil, err
		}

		//noinspection GoDeferInLoop
		defer func(order *acme.Order) {
			go func(order *acme.Order) {
				defer log.HandlePanic(logger)

				revokeLogger := logger.Named("background_auth_revoker")

				revokeCtx, cancel := context.WithTimeout(context.Background(), revokeAuthorizationTimeout)
				defer cancel()

				revokeCtx = zc.WithLogger(revokeCtx, revokeLogger)
				m.deactivatePendingAuthz(revokeCtx, acmeClient, order.AuthzURLs)
			}(order)
		}(order)

		switch order.Status {
		case acme.StatusReady:
			logger.Debug("Authorization completed")
			break authorizeOrderLoop

		case acme.StatusPending:
		// pass
		default:
			logger.Error("Invalid new order status", zap.String("status", order.Status), zap.String("uri", order.URI))
			return nil, errors.New("invalid new order status")
		}

		logger.Debug("Start authorization step")

		// Satisfy all pending authorizations.
	authDomainLoop:
		for _, zurl := range order.AuthzURLs {
			z, err := acmeClient.GetAuthorization(ctx, zurl)

			log.DebugError(logger, err, "Get authorization object.", zap.Reflect("authorization", z))
			if err != nil {
				return nil, err
			}
			// force hide outer logger - for log specific domain on each iteration
			var logger = logger.With(domain.LogDomain(domain.DomainName(z.Identifier.Value)))

			hasCompatibleChallenge := false
		challengeTypeLoop:
			for _, challengeType := range challengeTypes {
				if z.Status != acme.StatusPending {
					// We are interested only in pending authorizations.
					logger.Debug("Skip authorize process", zap.String("status", z.Status))
					continue authDomainLoop
				}

				// Pick the next preferred challenge.
				var chal = pickChallenge(challengeType, z.Challenges)
				logger.Debug("Selected challenge", zap.Any("challenge", chal))
				if chal == nil {
					continue challengeTypeLoop
				}
				hasCompatibleChallenge = true

				// Respond to the challenge and wait for validation result.
				cleanup, err := m.fulfill(ctx, acmeClient, chal, domain.DomainName(z.Identifier.Value))
				log.DebugError(logger, err, "Write respond to challenge")
				if err != nil {
					continue authorizeOrderLoop
				}
				cleanupContext, cleanupContextCancel := context.WithTimeout(contexthelper.DropCancelContext(ctx), cleanupTimeout)
				//noinspection GoDeferInLoop
				defer cleanupContextCancel()
				//noinspection GoDeferInLoop
				defer cleanup(cleanupContext)

				authorizedChallenge, err := acmeClient.Accept(ctx, chal)
				log.DebugError(logger, err, "accept authorization", zap.Reflect("authorized_challenge", authorizedChallenge))
				if err != nil {
					continue authorizeOrderLoop
				}
				authorization, err := acmeClient.WaitAuthorization(ctx, z.URI)
				log.DebugError(logger, err, "wait authorization", zap.Reflect("authorization", authorization))
				if err != nil {
					continue authorizeOrderLoop
				}
			}
			if !hasCompatibleChallenge {
				logger.Error("No compatible challenges")
				return nil, fmt.Errorf("unable to satisfy %q for domain %q: no viable challenge type found", z.URI, z.Identifier.Value)
			}
		}

		// All authorizations are satisfied.
		// Wait for the CA to update the order status.
		order, err = acmeClient.WaitOrder(ctx, order.URI)
		log.DebugWarning(logger, err, "Wait order authorization.", zap.Reflect("order", order))
		if err == nil {
			break authorizeOrderLoop
		}
	}
	return order, nil
}

func (m *Manager) issueCertificate(ctx context.Context, acmeClient AcmeClient, cd CertDescription, order *acme.Order) (*tls.Certificate, error) {
	if len(order.Identifiers) == 0 {
		return nil, errors.New("no domains for issue certificate")
	}

	domains := make([]domain.DomainName, len(order.Identifiers))
	for i := range order.Identifiers {
		domains[i] = domain.DomainName(order.Identifiers[i].Value)
	}
	logger := zc.L(ctx).With(domain.LogDomains(domains))

	key, err := m.certKeyGetOrCreate(ctx, cd)
	log.DebugError(logger, err, "Get cert key")
	if err != nil {
		return nil, err
	}

	csr, err := createCertRequest(key, domains[0], domains...)
	log.DebugDPanic(logger, err, "Create certificate request")
	if err != nil {
		return nil, err
	}

	der, _, err := acmeClient.CreateOrderCert(ctx, order.FinalizeURL, csr, true)
	log.InfoError(logger, err, "Receive certificate from acme server")
	if err != nil {
		return nil, err
	}

	cert, err := validCertDer(domains, der, key, false, time.Now())
	log.DebugDPanic(logger, err, "Check certificate is valid")
	if err != nil {
		return nil, err
	}

	err = storeCertificate(ctx, m.Cache, cd, cert)
	log.DebugDPanic(logger, err, "Certificate stored")
	if err != nil {
		return nil, err
	}
	if m.SaveJSONMeta {
		err = storeCertificateMeta(ctx, m.Cache, cd, cert)
		if err != nil {
			return nil, err
		}
	}
	return cert, nil
}

func (m *Manager) renewCertInBackground(ctx context.Context, needDomain domain.DomainName, cd CertDescription) {
	// detach from request lifetime, but save log context
	logger := zc.L(ctx).Named("background")
	defer log.HandlePanic(logger)
	ctx, ctxCancel := context.WithTimeout(context.Background(), m.CertificateIssueTimeout)
	defer ctxCancel()

	logger.Debug("Start reissue certificate in background")

	ctx = zc.WithLogger(ctx, logger)
	_, err := m.issueNewCert(ctx, needDomain, cd)
	log.DebugError(logger, err, "Cert reissue in background finished")
}

func (m *Manager) deactivatePendingAuthz(ctx context.Context, acmeClient AcmeClient, uries []string) {
	logger := zc.L(ctx)

	for _, uri := range uries {
		localLogger := logger.With(zap.String("uri", uri))
		authorization, err := acmeClient.GetAuthorization(ctx, uri)
		log.DebugError(localLogger, err, "Get authorization", zap.Reflect("authorization", authorization))
		if err != nil {
			continue
		}
		if authorization.Status == acme.StatusPending {
			err := acmeClient.RevokeAuthorization(ctx, uri)
			log.DebugInfo(localLogger, err, "Revoke authorization", zap.String("uri", uri))
		} else {
			localLogger.Debug("Authorization not in pending state. Skip revoke.", zap.String("status", authorization.Status))
		}
	}
}

func (m *Manager) certKeyGetOrCreate(ctx context.Context, cd CertDescription) (crypto.Signer, error) {
	logger := zc.L(ctx)

	key, err := getCertificateKey(ctx, m.Cache, cd)
	logger.Debug("Got certificate key from cache and reuse old key", zap.Error(err))
	if err == nil {
		return key, nil
	}
	if err != cache.ErrCacheMiss {
		return nil, err
	}

	key, err = cd.KeyType.Generate()
	log.InfoError(logger, err, "Generate new key")
	return key, err
}

func (m *Manager) filterTlsHello(ctx context.Context, hello *tls.ClientHelloInfo) {
	if m.AllowInsecureTLSChipers {
		log.DebugCtx(ctx, "Disable filter chiper suites")
		return
	}

	newChipers := make([]uint16, 0, len(hello.CipherSuites))
	for _, chiper := range hello.CipherSuites {
		if _, insecure := insecureChipers[chiper]; insecure {
			log.DebugCtx(ctx, "Exclude insecure chiper from tls hello: %v", zap.Uint16("chiper_code", chiper))
			continue
		}
		newChipers = append(newChipers, chiper)
	}
	hello.CipherSuites = newChipers
}

func (m *Manager) fulfill(ctx context.Context, acmeClient AcmeClient, challenge *acme.Challenge, domain domain.DomainName) (func(context.Context), error) {
	logger := zc.L(ctx)

	switch challenge.Type {
	case tlsAlpn01:
		cert, err := acmeClient.TLSALPN01ChallengeCert(challenge.Token, domain.String())
		log.DebugError(logger, err, "Got TLSALPN01ChallengeCert", log.Cert(&cert))
		if err != nil {
			return nil, err
		}
		m.putCertToken(ctx, domain, &cert)
		return func(localContext context.Context) {
			// handlepanic: in deleteCertToken
			go m.deleteCertToken(localContext, domain)
		}, nil
	case http01:
		resp, err := acmeClient.HTTP01ChallengeResponse(challenge.Token)
		if err != nil {
			return nil, err
		}
		key := domain.ASCII() + "/" + challenge.Token
		err = m.httpTokens.Put(ctx, key, []byte(resp))
		log.DebugError(logger, err, "Put token for http-01", zap.String("key", key))
		if err == nil {
			return func(localContext context.Context) { _ = m.httpTokens.Delete(localContext, key) }, nil
		} else {
			return nil, err
		}
	default:
		logger.Error("Unknow challenge type", zap.Reflect("challenge", challenge))
		return nil, errors.New("unknown challenge type")
	}
}

func (m *Manager) initMetrics(r prometheus.Registerer) {
	m.handleCertStart, m.handleCertFinish = metrics.ToefCounters(r, "handle_cert", "handled certificates")
	m.certRequestStart, m.certRequestFinish = metrics.ToefCounters(r, "cert_request", "request certificates from lets-encrypt")
}

func (m *Manager) isHTTPValidationRequest(r *http.Request) bool {
	if r == nil || r.URL == nil {
		return false
	}
	if r.Method != http.MethodGet {
		return false
	}

	return strings.HasPrefix(r.URL.Path, httpWellKnown)
}

func (m *Manager) HandleHTTPValidation(w http.ResponseWriter, r *http.Request) bool {
	if !m.isHTTPValidationRequest(r) {
		return false
	}

	ctx := r.Context()
	logger := zc.L(ctx)

	token := strings.TrimPrefix(r.URL.Path, httpWellKnown)
	d, err := domain.NormalizeDomain(r.Host)
	log.DebugInfo(logger, err, "Domain normalization", zap.String("original", r.Host), domain.LogDomain(d))
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return true
	}
	resp, err := m.httpTokens.Get(ctx, d.ASCII()+"/"+token)
	logger.Debug("Get http token", zap.Error(err))
	if err == nil {
		w.WriteHeader(http.StatusOK)
		_, err = w.Write(resp)
		log.DebugInfo(logger, err, "Error write http token answer to response", domain.LogDomain(d), zap.String("token", token))
	} else {
		logger.Warn("Have no validation token", domain.LogDomain(d), zap.String("token", token), zap.Error(err))
	}
	return true
}

func (m *Manager) putCertToken(ctx context.Context, key domain.DomainName, certificate *tls.Certificate) {
	err := m.certForDomainAuthorize.Put(ctx, key.String(), certificate)
	log.DebugDPanicCtx(ctx, err, "Put cert token", zap.String("key", string(key)))
}

func (m *Manager) deleteCertToken(ctx context.Context, key domain.DomainName) {
	defer log.HandlePanicCtx(ctx)

	err := m.certForDomainAuthorize.Delete(ctx, key.String())
	log.DebugDPanicCtx(ctx, err, "Delete cert token", zap.String("key", key.String()))
}

// It isn't atomic syncronized - caller must not save two certificates with same name same time
func storeCertificate(ctx context.Context, cache cache.Bytes, cd CertDescription,
	cert *tls.Certificate) error {
	logger := zc.L(ctx)

	locked, err := isCertLocked(ctx, cache, cd)
	log.DebugError(logger, err, "Check if cert locked", zap.Bool("key_locked", locked))
	if locked {
		logger.DPanic("Logical error - try to save to locked certificate")
		return xerrors.New("Try save to locked certificate")
	}

	var keyType = getKeyType(cert)

	var certBuf bytes.Buffer

	for _, block := range cert.Certificate {
		err := pem.Encode(&certBuf, &pem.Block{Type: "CERTIFICATE", Bytes: block})
		if err != nil {
			logger.DPanic("Can't encode pem block of certificate", zap.Error(err), zap.Binary("block", block))
			return err
		}
	}

	var privateKeyBytes []byte

	switch keyType {
	case KeyRSA:
		privateKey := cert.PrivateKey.(*rsa.PrivateKey)
		keyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
		privateKeyBytes = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: keyBytes})
	case KeyECDSA:
		privateKey := cert.PrivateKey.(*ecdsa.PrivateKey)
		keyBytes, err := x509.MarshalECPrivateKey(privateKey)
		if err != nil {
			return err
		}
		privateKeyBytes = pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes})
	default:
		logger.DPanic("Unknow private key type", zap.String("type", reflect.TypeOf(cert.PrivateKey).String()))
		return errors.New("unknow private key type")
	}

	certKeyName := cd.CertStoreName()
	keyKeyName := cd.KeyStoreName()

	err = cache.Put(ctx, certKeyName, certBuf.Bytes())
	zc.InfoError(logger, err, "Store certificate file", zap.String("cert_key", certKeyName))
	if err != nil {
		return err
	}

	err = cache.Put(ctx, keyKeyName, privateKeyBytes)
	zc.InfoError(logger, err, "Store key file", zap.String("key_key", keyKeyName))
	if err != nil {
		_ = cache.Delete(ctx, certKeyName)
		return err
	}
	return nil
}

func storeCertificateMeta(ctx context.Context, storage cache.Bytes, cd CertDescription, certificate *tls.Certificate) error {
	info := struct {
		Domains    []string
		ExpireDate time.Time
	}{
		Domains:    certificate.Leaf.DNSNames,
		ExpireDate: certificate.Leaf.NotAfter,
	}
	infoBytes, _ := json.MarshalIndent(info, "", "    ")
	err := storage.Put(ctx, cd.MetaStoreName(), infoBytes)
	log.DebugDPanicCtx(ctx, err, "Save cert metadata")
	return err
}

func getKeyType(cert *tls.Certificate) KeyType {
	if cert == nil {
		panic("cert is nil")
	}
	switch cert.PrivateKey.(type) {
	case *rsa.PrivateKey:
		return KeyRSA
	case *ecdsa.PrivateKey:
		return KeyECDSA
	default:
		panic("unexexpected key type: " + reflect.TypeOf(cert.PrivateKey).PkgPath() + "." + reflect.TypeOf(cert.PrivateKey).Name())
	}
}

func loadCertificateFromCache(ctx context.Context, c cache.Bytes, cd CertDescription) (cert *tls.Certificate, err error) {
	logger := zc.L(ctx)
	logger.Debug("Check certificate in cache")
	defer func() {
		logger.Debug("Checked certificate in cache", log.Cert(cert), zap.Error(err))
	}()

	certCerName := cd.CertStoreName()

	certBytes, err := c.Get(ctx, certCerName)
	logLevel := zapcore.ErrorLevel
	if err == nil || err == cache.ErrCacheMiss {
		logLevel = zapcore.DebugLevel
	}
	log.LevelParam(logger, logLevel, "Get certificate from cache", zap.Error(err))

	if err != nil {
		return nil, err
	}

	keyBytes, err := getCertificateKeyBytes(ctx, c, cd)
	logLevel = zapcore.ErrorLevel
	if err == nil || err == cache.ErrCacheMiss {
		logLevel = zapcore.DebugLevel
	}
	log.LevelParam(logger, logLevel, "Get certificate key from cache")
	if err != nil {
		return nil, err
	}

	cert2, err := tls.X509KeyPair(certBytes, keyBytes)
	log.DebugError(logger, err, "Combine cert and key into pair")
	if err != nil {
		// logical error, may be system failure
		return nil, err
	}
	if len(cert2.Certificate) > 0 {
		cert2.Leaf, err = x509.ParseCertificate(cert2.Certificate[0])
		if err != nil {
			// logical error, may be system failure
			return nil, err
		}
	}
	locked, err := isCertLocked(ctx, c, cd)
	log.DebugError(logger, err, "Check if certificate locked")
	if err != nil {
		// logical error, may be system failure
		return nil, err
	}
	return validCertTLS(&cert2, nil, locked, time.Now())
}

func getCertificateKeyBytes(ctx context.Context, cache cache.Bytes, cd CertDescription) ([]byte, error) {
	keyKeyName := cd.KeyStoreName()
	return cache.Get(ctx, keyKeyName)
}

func getCertificateKey(ctx context.Context, cache cache.Bytes, cd CertDescription) (crypto.Signer, error) {
	certBytes, err := getCertificateKeyBytes(ctx, cache, cd)
	if err != nil {
		return nil, err
	}
	return parsePrivateKey(certBytes)
}

func parsePrivateKey(keyPEMBlock []byte) (crypto.Signer, error) {
	// extract from tls.go, standard lib. func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)
	// X509KeyPair parses a public/private key pair from a pair of
	// PEM encoded data. On successful return, Certificate.Leaf will be nil because
	// the parsed form of the certificate is not retained.
	fail := func(err error) (crypto.Signer, error) { return nil, err }

	var keyDERBlock *pem.Block
	var skippedBlockTypes []string

	for {
		keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
		if keyDERBlock == nil {
			return fail(fmt.Errorf("tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key "+
				"input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
		}
		if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
			break
		}

		skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
	}

	// bedge key bytes
	der := keyDERBlock.Bytes

	// copy from tls.go, standard lib. func parsePrivateKey(der []byte) (crypto.PrivateKey, error)
	//
	// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
	// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
	// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
	// func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
	if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
		return key, nil
	}
	if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
		switch key := key.(type) {
		// change from original. separate case need for allow return signer interface
		case *rsa.PrivateKey:
			return key, nil
		case *ecdsa.PrivateKey:
			return key, nil
		default:
			return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
		}
	}
	if key, err := x509.ParseECPrivateKey(der); err == nil {
		return key, nil
	}

	return nil, errors.New("tls: failed to parse private key")
}

func isNeedRenew(cert *tls.Certificate, now time.Time) bool {
	if cert == nil || cert.Leaf == nil {
		return false
	}
	return cert.Leaf.NotAfter.Add(-renewBeforeExpire).Before(now)
}

func isCertLocked(ctx context.Context, storage cache.Bytes, certName CertDescription) (bool, error) {
	lockName := certName.LockName()

	_, err := storage.Get(ctx, lockName)
	switch err {
	case cache.ErrCacheMiss:
		return false, nil
	case nil:
		return true, nil
	default:
		return false, err
	}
}

func isErrTooManyOrders(err error) bool {
	if err == nil {
		return false
	}
	return strings.Contains(err.Error(), "too many new orders recently")
}

// copy from golang.org/x/crypto/acme/autocert/autocert.go
// https://github.com/golang/crypto/blob/87dc89f01550277dc22b74ffcf4cd89fa2f40f4c/acme/autocert/autocert.go#L322
func supportsECDSA(hello *tls.ClientHelloInfo) bool {
	// The "signature_algorithms" extension, if present, limits the key exchange
	// algorithms allowed by the cipher suites. See RFC 5246, section 7.4.1.4.1.
	if hello.SignatureSchemes != nil {
		ecdsaOK := false
	schemeLoop:
		for _, scheme := range hello.SignatureSchemes {
			const tlsECDSAWithSHA1 tls.SignatureScheme = 0x0203 // constant added in Go 1.10
			switch scheme {
			case tlsECDSAWithSHA1, tls.ECDSAWithP256AndSHA256,
				tls.ECDSAWithP384AndSHA384, tls.ECDSAWithP521AndSHA512:
				ecdsaOK = true
				break schemeLoop
			}
		}
		if !ecdsaOK {
			return false
		}
	}
	if hello.SupportedCurves != nil {
		ecdsaOK := false
		for _, curve := range hello.SupportedCurves {
			if curve == tls.CurveP256 {
				ecdsaOK = true
				break
			}
		}
		if !ecdsaOK {
			return false
		}
	}
	for _, suite := range hello.CipherSuites {
		switch suite {
		case tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
			tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
			tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
			tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305:
			return true
		}
	}
	return false
}


text:
# - Try to find Portaudio
# Once done this will define
#
#  PORTAUDIO_FOUND - system has Portaudio
#  PORTAUDIO_INCLUDE_DIRS - the Portaudio include directory
#  PORTAUDIO_LIBRARIES - Link these to use Portaudio
#  PORTAUDIO_DEFINITIONS - Compiler switches required for using Portaudio
#  PORTAUDIO_VERSION - Portaudio version
#
#  Copyright (c) 2006 Andreas Schneider <mail@cynapses.org>
#
# Redistribution and use is allowed according to the terms of the New BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
#

# Use the libraries in the Jamoma tree
if(APPLE OR WIN32)
	find_path(PORTAUDIO_INCLUDE_DIRS portaudio.h
			  PATHS
			  ${CMAKE_CURRENT_LIST_DIR}/../../../DSP/extensions/AudioEngine/portaudio/include)
	if(APPLE)
		find_library(PORTAUDIO_LIBRARIES portaudio-jamoma
					 PATHS
					 ${CMAKE_CURRENT_LIST_DIR}/../../../DSP/extensions/AudioEngine/portaudio/)
		set(PORTAUDIO_LIBRARIES_DEBUG ${PORTAUDIO_LIBRARIES})
		set(PORTAUDIO_LIBRARIES_RELEASE ${PORTAUDIO_LIBRARIES})
	elseif(WIN32)
		find_library(PORTAUDIO_LIBRARIES_DEBUG PortAudio
					 PATHS
					 ${CMAKE_CURRENT_LIST_DIR}/../../../DSP/extensions/AudioEngine/portaudio/Debug)
		find_library(PORTAUDIO_LIBRARIES_RELEASE PortAudio
					 PATHS
					 ${CMAKE_CURRENT_LIST_DIR}/../../../DSP/extensions/AudioEngine/portaudio/Release)
		set(PORTAUDIO_LIBRARIES ${PORTAUDIO_LIBRARIES_DEBUG} ${PORTAUDIO_LIBRARIES_RELEASE})
	endif()

	include(FindPackageHandleStandardArgs)
	FIND_PACKAGE_HANDLE_STANDARD_ARGS(PORTAUDIO DEFAULT_MSG PORTAUDIO_LIBRARIES PORTAUDIO_INCLUDE_DIRS)
	return()
endif()

# Linux case
include(FindPkgConfig)
find_library(ASOUND_Library NAMES asound)
if("${ASOUND_Library}" STREQUAL "")
    message("Checking for Portaudio : libasound not found.")
    return()
endif()

pkg_check_modules(PORTAUDIO2 portaudio-2.0)
if(PORTAUDIO2_FOUND)
    set(PORTAUDIO_INCLUDE_DIRS ${PORTAUDIO2_INCLUDEDIR})
    set(PORTAUDIO_LIBRARIES ${PORTAUDIO2_LIBRARIES})
    set(PORTAUDIO_VERSION 19)
    set(PORTAUDIO_FOUND TRUE)
else ()
    find_path(PORTAUDIO_INCLUDE_DIR
      NAMES
        portaudio.h
      PATHS
        /usr/include
        /usr/local/include
        /opt/local/include
        /sw/include
    )

    find_library(PORTAUDIO_LIBRARY
      NAMES
        portaudio
      PATHS
        /usr/lib
        /usr/local/lib
        /opt/local/lib
        /sw/lib
    )

    find_path(PORTAUDIO_LIBRARY_DIR
      NAMES
        portaudio
      PATHS
        /usr/lib
        /usr/local/lib
        /opt/local/lib
        /sw/lib
    )

    set(PORTAUDIO_INCLUDE_DIRS
      ${PORTAUDIO_INCLUDE_DIR}
    )
    set(PORTAUDIO_LIBRARIES
      ${PORTAUDIO_LIBRARY}
    )

    set(PORTAUDIO_LIBRARY_DIRS
      ${PORTAUDIO_LIBRARY_DIR}
    )

    set(PORTAUDIO_VERSION
      19
    )
  endif()

# show the PORTAUDIO_INCLUDE_DIRS and PORTAUDIO_LIBRARIES variables only in the advanced view
mark_as_advanced(PORTAUDIO_INCLUDE_DIRS PORTAUDIO_LIBRARIES)

set(PORTAUDIO_LIBRARIES_DEBUG ${PORTAUDIO_LIBRARIES})
set(PORTAUDIO_LIBRARIES_RELEASE ${PORTAUDIO_LIBRARIES})

include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(PORTAUDIO DEFAULT_MSG PORTAUDIO_LIBRARIES PORTAUDIO_INCLUDE_DIRS)

extension: cmake


text:
package modelhelper

import (
	"fmt"
	"koding/db/models"

	"gopkg.in/mgo.v2"
)

func GetNameBySlug(slug string) (*models.Name, error) {
	name := &models.Name{}

	query := func(c *mgo.Collection) error {
		v := fmt.Sprintf("Activity\\/%s", slug)
		s := &Selector{"slug": v}
		return c.Find(s).One(&name)
	}

	err := Mongo.Run("jNames", query)

	return name, err
}

func UpdateName(name *models.Name) error {
	query := updateQuery(Selector{"name": name.Name}, name)
	return Mongo.Run("jNames", query)
}

repository: f/koding

repo_name: f/koding

gha_language: CoffeeScript


text:
#include "SceneScriptBase.h"

class SponzaScript : public SceneScript
{
public:
	virtual void InitScene(Scene *scene)
	{
		//std::wstring modelPath = L"C:\\Users\\wqxho_000\\Downloads\\SponzaPBR_Textures\\SponzaPBR_Textures\\Converted\\sponza_new.obj";
		//// std::wstring proxyModelPath = L"C:\\Users\\wqxho_000\\Downloads\\SponzaPBR_Textures\\SponzaPBR_Textures\\Converted\\sponza_unwrapped.fbx";
		//std::wstring proxyModelPath = L"C:\\Users\\wqxho_000\\Downloads\\SponzaPBR_Textures\\SponzaPBR_Textures\\Converted\\sponza_high_res_unwrapped.fbx";

		std::wstring modelPath = L"C:\\MyUnity513WS\\Converted\\sponza_new.obj";
		std::wstring proxyModelPath = L"C:\\MyUnity513WS\\Converted\\sponza_high_res_unwrapped.fbx";

		Model *model = scene->addModel(modelPath);
		scene->addStaticOpaqueObject(model, 0.03f, Float3(0, 0, 0), Quaternion());
		scene->setProxySceneObject(proxyModelPath, 0.03f, Float3(0, 0, 0), Quaternion());

		//// scene->fillPointLightsUniformGrid(50.0f, 100.0f);
		//// scene->fillPointLightsUniformGrid(1.3f, 3.0f, Float3(0, 0, 0));
		scene->getGlobalCameraPtr()->SetLookAt(Float3(0.0f, 2.5f, -10.0f), Float3(0.0f, 0.0f, 0.0f), Float3(0.0f, 1.0f, 0.0f));

		// set specular probes
		/*scene->getProbeManagerPtr()->AddProbe(Float3(0, 0, 0), Float3(2, 2, 2));
		scene->getProbeManagerPtr()->AddProbe(Float3(-1, 0, 0), Float3(2, 2, 2));*/
		scene->setProbeLength(6.0f);
		PointLight *l = scene->addPointLight();
		l->cRadius = 100.0f;
		l->cPos = Float3(0, 1, 0);
		l->cPos = Float3(1, 0, 0) * 40;

	//C:\MyUnity513WS\Converted
	}

	virtual void Update(Scene *scene, const SampleFramework11::Timer *timer)
	{

	}
};

extension: h


text:
SUMMARY = "WPE Framework User Interface"
DESCRIPTION = "WPE Framework User Interface web app"
HOMEPAGE = "https://github.com/rdkcentral/ThunderUI"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://LICENSE;md5=66fe57b27abb01505f399ce4405cfea0"

require include/wpeframework-plugins.inc

PV = "3.0+gitr${SRCPV}"
RECIPE_BRANCH ?= "master"

SRC_URI = "git://github.com/rdkcentral/ThunderUI.git;branch=${RECIPE_BRANCH};protocol=https"
SRCREV ?= "80c2bc4835e8cc0a8825b5f0d53d588ee8db59a0"

do_configure[noexec] = "1"
do_compile[noexec] = "1"

do_install() {
    rm -rf ${D}${datadir}/WPEFramework/Controller/UI/*
    mkdir -p ${D}${datadir}/WPEFramework/Controller/UI
    cp -r ${S}/src/* ${D}${datadir}/WPEFramework/Controller/UI
    cp -r ${S}/dist/* ${D}${datadir}/WPEFramework/Controller/UI
}

FILES_${PN} += "${datadir}/WPEFramework/Controller/UI/*"

repository: WebPlatformForEmbedded/meta-wpe

repo_name: WebPlatformForEmbedded/meta-wpe

branch_name: refs/heads/main

gha_language: BitBake


text:
@article{Aghayi2019Crowdsourced,
    title     = {Crowdsourced Behavior-Driven Development},
    author    = {Aghayi, Emad and LaToza, Thomas D. and Surendra, Paurav and Abolghasemi, Seyedmeysam},
    journal   = {Journal of Systems and Software (JSS)},
    year      = {2021},
    publisher = {Elsevier},
    volume    = {171},
    pages     = {110840},
    doi       = {10.1016/j.jss.2020.110840},
    url       = {https://arxiv.org/pdf/1903.01977.pdf},
    project   = {Microtask Programming}

}

@inproceedings{Saito2020MicroTaskProgramming,
    author    = {Saito, Shinobu and Iimura, Yukako and Aghayi, Emad and LaToza, Thomas D.},
    booktitle = {ACM Joint European Software Engineering Conference and Symposium on the Foundations of Software Engineering, Industry Papers Track (ESEC/FSE-IP)},
    title     = {Can microtask programming work in industry?},
    year      = {2020},
    pages     = {1263–1273},
    doi       = {10.1145/3368089.3417046},
    url       = {https://arxiv.org/abs/2009.05207},
    project   = {Microtask Programming}
}

@inproceedings{Mehrpour2020RulePad,
    author    = {Mehrpour, Sahar and LaToza, Thomas D. and Sarvari, Hamed},
    booktitle = {ACM Joint European Software Engineering Conference and Symposium on the Foundations of Software Engineering (ESEC/FSE)},
    title     = {RulePad: Interactive Authoring of Checkable Design Rules},
    year      = {2020},
    pages     = {386–397},
    doi       = {10.1145/3368089.3409751},
    url       = {https://arxiv.org/abs/2007.05046},
    project   = {Active Documentation}
}

@inproceedings{Alaboudi2020UsingHypotheses,
    author    = {Alaboudi, Abdulaziz and LaToza, Thomas D.},
    booktitle = {2020 IEEE Symposium on Visual Languages and Human-Centric Computing (VL/HCC)},
    title     = {Using Hypotheses as a Debugging Aid},
    year      = {2020},
    pages     = {1-9},
    doi       = {0.1109/VL/HCC50065.2020.9127273},
    url       = {https://arxiv.org/abs/2005.13652},
    project   = {Debugging Hypotheses}
}

@inproceedings{Aghayi2020FindUniqueUsages,
    author    = {Aghayi, Emad and Massey, Aaron and LaToza, Thomas D.},
    booktitle = {2020 IEEE Symposium on Visual Languages and Human-Centric Computing (VL/HCC)},
    title     = {Find Unique Usages: Helping Developers Understand Common Usages},
    year      = {2020},
    pages     = {1-8},
    doi       = {10.1109/VL/HCC50065.2020.9127285},
    url       = {https://arxiv.org/abs/2005.11474},
    project   = {Find Unique Usages}
}

@article{Latoza2020Explicit,
	title     = {Explicit programming strategies},
	volume    = {25},
	issn      = {1382-3256, 1573-7616},
	doi       = {10.1007/s10664-020-09810-1},
	number    = {4},
	journal   = {Empirical Software Engineering},
	author    = {LaToza, Thomas D. and Arab, Maryam and Loksa, Dastyni and Ko, Amy J.},
	month     = jul,
	year      = {2020},
	pages     = {2416--2449},
	project   = {Programming Strategies},
}

@inproceedings{Alaboudi2019ExploratoryStudy,
    author    = {Alaboudi, Abdulaziz and LaToza, Thomas D.},
    title     = {An Exploratory Study of Live-Streamed Programming},
    booktitle = {IEEE Symposium on Visual Languages and Human-Centric Computing (VL/HCC)},
    pages     = {5--13},
    year      = {2019},
    date      = {October 14-18, 2019},
    location  = {Memphis, Tennessee, USA},
    doi       = {10.1109/VLHCC.2019.8818832},
    project   = {Debugging Hypotheses},
}

@inproceedings{Chugh2019EditableAI,
    author    = {Chugh, Kartik and Solis, Andrea and LaToza, Thomas D.},
    booktitle = {IEEE Symposium on Visual Languages and Human-Centric Computing (VL/HCC)},
    title     = {Editable AI: Mixed Human-AI Authoring of Code Patterns},
    year      = {2019},
    date      = {October 14-18, 2019},
    location  = {Memphis, Tennessee, USA},
    pages     = {35-43},
    doi       = {10.1109/VLHCC.2019.8818871},
    project   = {None}
}

@inproceedings{Mehrpour2019ActiveDocumentation,
    author    = {Mehrpour, Sahar and LaToza, Thomas D. and Kindi, Rahul K.},
    booktitle = {IEEE Symposium on Visual Languages and Human-Centric Computing (VL/HCC)},
    title     = {Active Documentation: Helping Developers Follow Design Decisions},
    year      = {2019},
    date      = {October 14-18, 2019},
    location  = {Memphis, Tennessee, USA},
    pages     = {87-96},
    doi       = {10.1109/VLHCC.2019.8818816},
    project   = {Active Documentation}
}

@inproceedings{Alaboudi2019SupportingSoftware,
    author    = {Alaboudi, Abdulaziz and LaToza, Thomas D.},
    title     = {Supporting Software Engineering Research and Education by Annotating Public Videos of Developers Programming},
    year      = {2019},
    publisher = {IEEE Press},
    doi       = {10.1109/CHASE.2019.00035},
    booktitle = {International Workshop on Cooperative and Human Aspects of Software Engineering (CHASE)},
    pages     = {117–118},
    numpages  = {2},
    keywords  = {software engineering theories, software engineering strategies, screencasting, social software development},
    location  = {Montreal, Quebec, Canada},
    series    = {CHASE ’19},
    url       = {https://arxiv.org/abs/1905.11366},
    project   = {Debugging Hypotheses}
}

gha_language: HTML


text:
SUMMARY = "A free software percussion synthesizer"
HOMEPAGE = "https://gitlab.com/iurie-sw/geonkick"
LICENSE = "GPL-3.0-only"
LIC_FILES_CHKSUM = "file://LICENSE;md5=84dcc94da3adb52b53ae4fa38fe49e5d"

inherit cmake pkgconfig mime mime-xdg gtk-icon-cache

DEPENDS += " \
    libsndfile1 \
    rapidjson \
    jack \
    lv2 \
"

SRC_URI = "git://gitlab.com/iurie-sw/geonkick;protocol=https;branch=main"
SRCREV = "ce95f97363de78cc0cc0f0830f965ecced59195d"
PV = "2.9.1"
S = "${WORKDIR}/git"

EXTRA_OECMAKE = " \
    -DCMAKE_BUILD_TYPE=RelWithDebInfo \
    -DGKICK_ARCHITECTURE=${TARGET_ARCH} \
"

FILES:${PN} += " \
    ${datadir}/mime \
    ${libdir}/lv2 \
"

repository: schnitzeltony/meta-musicians

repo_name: schnitzeltony/meta-musicians


text:
package middleman

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestCors(t *testing.T) {
	h := func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "Hello World!")
	}

	// add middleware
	handler := CORS([]string{"http://example.com", "https://example.com"}, http.HandlerFunc(h))

	// do request
	req := httptest.NewRequest("GET", "http://example.com/foo", nil)
	req.Header.Add("Origin", "http://example.com")

	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)

	// response
	resp := w.Result()

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Log(err.Error())
	}
	resp.Body.Close()

	println(string(b))
	fmt.Println(resp.Header)

	if acao := resp.Header["Access-Control-Allow-Origin"]; acao != nil && acao[0] != "http://example.com" {
		t.Fail()
		t.Logf(`Wanted "Access-Control-Allow-Origin" to be "http://example.com", got: %q`, acao)
	}

	if vary := resp.Header["Vary"]; vary != nil && vary[0] != "Origin" {
		t.Fail()
		t.Logf(`Wanted Header["Vary"] == "Origin", got: %q`, vary)
	}

}

repository: aerth/middleman

repo_name: aerth/middleman


text:
DESCRIPTION = "Libretro Nintendo Dual Screen (DS) cores"

inherit retro-packagegroup

LIBRETRO_NDS_CORES ?= " \
  ${@bb.utils.contains('DISTRO_FEATURES', 'x11', 'desmume-libretro desmume2015-libretro', '', d)} \
"

RRECOMMENDS:${PN} = "${LIBRETRO_NDS_CORES}"


text:
package main

import (
	"net"
	"sync"

	"fmt"

	"math/rand"

	"time"

	"reflect"

	"crypto/tls"

	"github.com/xiaonanln/goworld/engine/common"
	"github.com/xiaonanln/goworld/engine/config"
	"github.com/xiaonanln/goworld/engine/consts"
	"github.com/xiaonanln/goworld/engine/entity"
	"github.com/xiaonanln/goworld/engine/gwioutil"
	"github.com/xiaonanln/goworld/engine/gwlog"
	"github.com/xiaonanln/goworld/engine/netutil"
	"github.com/xiaonanln/goworld/engine/post"
	"github.com/xiaonanln/goworld/engine/proto"
	"github.com/xtaci/kcp-go"
	"golang.org/x/net/websocket"
)

const _SPACE_ENTITY_TYPE = "__space__"

var (
	tlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}
)

// ClientBot is  a client bot representing a game client
type ClientBot struct {
	sync.Mutex

	id int

	waiter             *sync.WaitGroup
	conn               *proto.GoWorldConnection
	entities           map[common.EntityID]*clientEntity
	player             *clientEntity
	currentSpace       *ClientSpace
	logined            bool
	startedDoingThings bool
	syncPosTime        time.Time
	useKCP             bool
	useWebSocket       bool
	noEntitySync       bool
	packetQueue        chan proto.Message
}

func newClientBot(id int, useWebSocket bool, useKCP bool, noEntitySync bool, waiter *sync.WaitGroup) *ClientBot {
	return &ClientBot{
		id:           id,
		waiter:       waiter,
		entities:     map[common.EntityID]*clientEntity{},
		useKCP:       useKCP,
		useWebSocket: useWebSocket,
		noEntitySync: noEntitySync,
		packetQueue:  make(chan proto.Message),
	}
}

func (bot *ClientBot) String() string {
	return fmt.Sprintf("ClientBot<%d>", bot.id)
}

func (bot *ClientBot) run() {
	defer bot.waiter.Done()

	gwlog.Infof("%s is running ...", bot)

	gateIDs := config.GetGateIDs()
	// choose a random gateid
	gateid := gateIDs[rand.Intn(len(gateIDs))]
	gwlog.Debugf("%s is connecting to gate %d", bot, gateid)
	cfg := config.GetGate(gateid)

	var netconn net.Conn
	var err error
	for { // retry for ever
		netconn, err = bot.connectServer(cfg)
		if err != nil {
			gwlog.Errorf("Connect failed: %s", err)
			time.Sleep(time.Second * time.Duration(1+rand.Intn(10)))
			continue
		}
		// connected , ok
		break
	}

	gwlog.Infof("connected: %s", netconn.RemoteAddr())
	if cfg.EncryptConnection && !bot.useWebSocket {
		netconn = tls.Client(netconn, tlsConfig)
	}
	bot.conn = proto.NewGoWorldConnection(netutil.NewBufferedConnection(netutil.NetConnection{netconn}), cfg.CompressConnection, cfg.CompressFormat)
	defer bot.conn.Close()

	if bot.useKCP {
		gwlog.Infof("Notify KCP connected ...")
		bot.conn.SetHeartbeatFromClient()
	}

	go bot.recvLoop()
	bot.loop()
}

func (bot *ClientBot) connectServer(cfg *config.GateConfig) (net.Conn, error) {
	if bot.useWebSocket {
		return bot.connectServerByWebsocket(cfg)
	} else if bot.useKCP {
		return bot.connectServerByKCP(cfg)
	}
	// just use tcp
	conn, err := netutil.ConnectTCP(serverHost, cfg.Port)
	if err == nil {
		conn.(*net.TCPConn).SetWriteBuffer(64 * 1024)
		conn.(*net.TCPConn).SetReadBuffer(64 * 1024)
	}
	return conn, err
}

func (bot *ClientBot) connectServerByKCP(cfg *config.GateConfig) (net.Conn, error) {
	serverAddr := fmt.Sprintf("%s:%d", serverHost, cfg.Port)
	conn, err := kcp.DialWithOptions(serverAddr, nil, 10, 3)
	if err != nil {
		return nil, err
	}
	conn.SetReadBuffer(64 * 1024)
	conn.SetWriteBuffer(64 * 1024)
	conn.SetNoDelay(consts.KCP_NO_DELAY, consts.KCP_INTERNAL_UPDATE_TIMER_INTERVAL, consts.KCP_ENABLE_FAST_RESEND, consts.KCP_DISABLE_CONGESTION_CONTROL)
	conn.SetStreamMode(consts.KCP_SET_STREAM_MODE)
	conn.SetWriteDelay(consts.KCP_SET_WRITE_DELAY)
	conn.SetACKNoDelay(consts.KCP_SET_ACK_NO_DELAY)
	return conn, err
}

func (bot *ClientBot) connectServerByWebsocket(cfg *config.GateConfig) (net.Conn, error) {
	originProto := "http"
	wsProto := "ws"
	if cfg.EncryptConnection {
		originProto = "https"
		wsProto = "wss"
	}
	origin := fmt.Sprintf("%s://%s:%d/", originProto, serverHost, cfg.HTTPPort)
	wsaddr := fmt.Sprintf("%s://%s:%d/ws", wsProto, serverHost, cfg.HTTPPort)

	if cfg.EncryptConnection {
		dialCfg, err := websocket.NewConfig(wsaddr, origin)
		if err != nil {
			return nil, err
		}
		dialCfg.TlsConfig = &tls.Config{
			InsecureSkipVerify: true,
		}
		return websocket.DialConfig(dialCfg)
	} else {
		return websocket.Dial(wsaddr, "", origin)
	}
}

func (bot *ClientBot) recvLoop() {
	var msgtype proto.MsgType

	for {
		pkt, err := bot.conn.Recv(&msgtype)
		if pkt != nil {
			//fmt.Fprintf(os.Stderr, "P")
			bot.packetQueue <- proto.Message{msgtype, pkt}
		} else if err != nil && !gwioutil.IsTimeoutError(err) {
			// bad error
			gwlog.Errorf("Client recv packet failed: %v", err)
			break
		}
	}
}

func (bot *ClientBot) loop() {
	ticker := time.Tick(time.Millisecond * 100)
	for {
		select {
		case item := <-bot.packetQueue:
			//fmt.Fprintf(os.Stderr, "p")
			bot.handlePacket(item.MsgType, item.Packet)
			item.Packet.Release()
			break
		case <-ticker:
			//fmt.Fprintf(os.Stderr, "|")
			if !bot.noEntitySync {
				if bot.player != nil && bot.player.TypeName == "Avatar" {
					now := time.Now()
					if now.Sub(bot.syncPosTime) > time.Millisecond*100 {
						player := bot.player
						const moveRange = 0.01
						if rand.Float32() < 0.5 { // let the posibility of avatar moving to be 50%
							player.pos.X += entity.Coord(-moveRange + moveRange*2*rand.Float32())
							player.pos.Z += entity.Coord(-moveRange + moveRange*rand.Float32())
							//gwlog.Infof("move to %f, %f", player.pos.X, player.pos.Z)
							player.yaw = entity.Yaw(rand.Float32() * 3.14)
							bot.conn.SendSyncPositionYawFromClient(player.ID, float32(player.pos.X), float32(player.pos.Y), float32(player.pos.Z), float32(player.yaw))
						}

						bot.syncPosTime = now
					}
				}

			}
			bot.conn.Flush("ClientBot")
			post.Tick()
			break
		}
	}
}

func (bot *ClientBot) handlePacket(msgtype proto.MsgType, packet *netutil.Packet) {
	defer func() {
		err := recover()
		if err != nil {
			gwlog.TraceError("handle packet faild: %v", err)
		}
	}()

	bot.Lock()
	defer bot.Unlock()

	//gwlog.Infof("client handle packet: msgtype=%v, payload=%v", msgtype, packet.Payload())

	if msgtype >= proto.MT_REDIRECT_TO_GATEPROXY_MSG_TYPE_START && msgtype <= proto.MT_REDIRECT_TO_GATEPROXY_MSG_TYPE_STOP {
		_ = packet.ReadUint16()
		_ = packet.ReadClientID() // TODO: strip these two fields ? seems a little difficult, maybe later.
	}

	if msgtype == proto.MT_NOTIFY_MAP_ATTR_CHANGE_ON_CLIENT {
		entityID := packet.ReadEntityID()
		var path []interface{}
		packet.ReadData(&path)
		key := packet.ReadVarStr()
		var val interface{}
		packet.ReadData(&val)
		if !quiet {
			gwlog.Debugf("Entity %s Attribute %v: set %s=%v", entityID, path, key, val)
		}
		bot.applyMapAttrChange(entityID, path, key, val)
	} else if msgtype == proto.MT_NOTIFY_MAP_ATTR_DEL_ON_CLIENT {
		entityID := packet.ReadEntityID()
		var path []interface{}
		packet.ReadData(&path)
		key := packet.ReadVarStr()
		if !quiet {
			gwlog.Debugf("Entity %s Attribute %v deleted %s", entityID, path, key)
		}
		bot.applyMapAttrDel(entityID, path, key)
	} else if msgtype == proto.MT_NOTIFY_LIST_ATTR_CHANGE_ON_CLIENT {
		entityID := packet.ReadEntityID()
		var path []interface{}
		packet.ReadData(&path)
		index := packet.ReadUint32()
		var val interface{}
		packet.ReadData(&val)
		//gwlog.Infof("Entity %s Attribute %v: set [%d]=%v", entityID, path, index, val)
		bot.applyListAttrChange(entityID, path, int(index), val)
	} else if msgtype == proto.MT_NOTIFY_LIST_ATTR_APPEND_ON_CLIENT {
		entityID := packet.ReadEntityID()
		var path []interface{}
		packet.ReadData(&path)
		var val interface{}
		packet.ReadData(&val)
		//gwlog.Infof("Entity %s Attribute %v: append %v", entityID, path, val)
		bot.applyListAttrAppend(entityID, path, val)
	} else if msgtype == proto.MT_NOTIFY_LIST_ATTR_POP_ON_CLIENT {
		entityID := packet.ReadEntityID()
		var path []interface{}
		packet.ReadData(&path)
		//gwlog.Infof("Entity %s Attribute %v: pop", entityID, path)
		bot.applyListAttrPop(entityID, path)
	} else if msgtype == proto.MT_CREATE_ENTITY_ON_CLIENT {
		isPlayer := packet.ReadBool()
		entityID := packet.ReadEntityID()
		typeName := packet.ReadVarStr()

		x := entity.Coord(packet.ReadFloat32())
		y := entity.Coord(packet.ReadFloat32())
		z := entity.Coord(packet.ReadFloat32())
		yaw := entity.Yaw(packet.ReadFloat32())
		//gwlog.Infof("Create e %s.%s: isPlayer=%v", typeName, entityID, isPlayer)
		var clientData map[string]interface{}
		packet.ReadData(&clientData)

		if typeName == _SPACE_ENTITY_TYPE {
			// this is a space
			bot.createSpace(entityID, clientData)
		} else {
			// this is a e
			bot.createEntity(typeName, entityID, isPlayer, clientData, x, y, z, yaw)
		}
	} else if msgtype == proto.MT_DESTROY_ENTITY_ON_CLIENT {
		typeName := packet.ReadVarStr()
		entityID := packet.ReadEntityID()
		if !quiet {
			gwlog.Debugf("Destroy e %s.%s", typeName, entityID)
		}
		if typeName == _SPACE_ENTITY_TYPE {
			bot.destroySpace(entityID)
		} else {
			bot.destroyEntity(typeName, entityID)
		}
	} else if msgtype == proto.MT_CALL_ENTITY_METHOD_ON_CLIENT {
		entityID := packet.ReadEntityID()
		method := packet.ReadVarStr()
		args := packet.ReadArgs()
		if !quiet {
			gwlog.Debugf("Call e %s.%s(%v)", entityID, method, args)
		}
		bot.callEntityMethod(entityID, method, args)
	} else if msgtype == proto.MT_CALL_FILTERED_CLIENTS {
		_ = packet.ReadOneByte() // ignore op
		_ = packet.ReadVarStr()  // ignore key
		_ = packet.ReadVarStr()  // ignore val
		method := packet.ReadVarStr()
		args := packet.ReadArgs()
		if bot.player == nil {
			gwlog.Warnf("Player not found while calling filtered client")
			return
		}

		bot.callEntityMethod(bot.player.ID, method, args)
	} else if msgtype == proto.MT_SYNC_POSITION_YAW_ON_CLIENTS {
		for packet.HasUnreadPayload() {
			entityID := packet.ReadEntityID()
			x := entity.Coord(packet.ReadFloat32())
			y := entity.Coord(packet.ReadFloat32())
			z := entity.Coord(packet.ReadFloat32())
			yaw := entity.Yaw(packet.ReadFloat32())
			bot.updateEntityPosition(entityID, entity.Vector3{x, y, z})
			bot.updateEntityYaw(entityID, yaw)
		}
		//} else if msgtype == proto.MT_SET_CLIENT_CLIENTID {
		//	clientid := packet.ReadClientID()
		//	bot.setClientID(clientid)
	} else {
		gwlog.Panicf("unknown msgtype: %v", msgtype)
	}
}

func (bot *ClientBot) updateEntityPosition(entityID common.EntityID, position entity.Vector3) {
	//gwlog.Debugf("updateEntityPosition %s => %s", entityID, position)
	if bot.entities[entityID] == nil {
		//gwlog.Warnf("updateEntityPosition: entity %s not found", entityID)
		return
	}
	entity := bot.entities[entityID]
	entity.pos = position
}

func (bot *ClientBot) updateEntityYaw(entityID common.EntityID, yaw entity.Yaw) {
	//gwlog.Debugf("updateEntityYaw %s => %s", entityID, yaw)
	if bot.entities[entityID] == nil {
		//gwlog.Warnf("updateEntityYaw: entity %s not found", entityID)
		return
	}
	entity := bot.entities[entityID]
	entity.yaw = yaw
}

func (bot *ClientBot) applyMapAttrChange(entityID common.EntityID, path []interface{}, key string, val interface{}) {
	//gwlog.Infof("SET ATTR %s.%v: set %s=%v", entityID, path, key, val)
	if bot.entities[entityID] == nil {
		gwlog.Errorf("entity %s not found", entityID)
		return
	}
	entity := bot.entities[entityID]
	entity.applyMapAttrChange(path, key, val)
}

func (bot *ClientBot) applyMapAttrDel(entityID common.EntityID, path []interface{}, key string) {
	//gwlog.Infof("DEL ATTR %s.%v: del %s", entityID, path, key)
	if bot.entities[entityID] == nil {
		gwlog.Errorf("entity %s not found", entityID)
		return
	}
	entity := bot.entities[entityID]
	entity.applyMapAttrDel(path, key)
}

func (bot *ClientBot) applyListAttrChange(entityID common.EntityID, path []interface{}, index int, val interface{}) {
	if bot.entities[entityID] == nil {
		gwlog.Errorf("entity %s not found", entityID)
		return
	}
	entity := bot.entities[entityID]
	entity.applyListAttrChange(path, index, val)
}

func (bot *ClientBot) applyListAttrAppend(entityID common.EntityID, path []interface{}, val interface{}) {
	if bot.entities[entityID] == nil {
		gwlog.Errorf("entity %s not found", entityID)
		return
	}
	entity := bot.entities[entityID]
	entity.applyListAttrAppend(path, val)
}

func (bot *ClientBot) applyListAttrPop(entityID common.EntityID, path []interface{}) {
	if bot.entities[entityID] == nil {
		gwlog.Errorf("entity %s not found", entityID)
		return
	}
	entity := bot.entities[entityID]
	entity.applyListAttrPop(path)
}

func (bot *ClientBot) createEntity(typeName string, entityID common.EntityID, isPlayer bool, clientData map[string]interface{}, x, y, z entity.Coord, yaw entity.Yaw) {
	if bot.entities[entityID] == nil {
		e := newClientEntity(bot, typeName, entityID, isPlayer, clientData, x, y, z, yaw)
		bot.entities[entityID] = e
		if isPlayer {
			if bot.player != nil {
				gwlog.TraceError("%s.createEntity: creating player %S, but player is already set to %s", bot, e, bot.player)
			}
			bot.player = e
		}
	}
}

func (bot *ClientBot) destroyEntity(typeName string, entityID common.EntityID) {
	entity := bot.entities[entityID]
	if entity != nil {
		entity.Destroy()
		if entity == bot.player {
			bot.player = nil
		}
		delete(bot.entities, entityID)
	}
}

func (bot *ClientBot) createSpace(spaceID common.EntityID, data map[string]interface{}) {
	if bot.currentSpace != nil {
		gwlog.TraceError("%s.createSpace: duplicate space: %s and %s", bot, bot.currentSpace, spaceID)
		oldSpace := bot.currentSpace
		bot.currentSpace = nil
		bot.OnLeaveSpace(oldSpace)
	}
	space := newClientSpace(bot, spaceID, data)
	bot.currentSpace = space
	gwlog.Debugf("%s current space change to %s", bot, space)
	bot.OnEnterSpace()
}

func (bot *ClientBot) destroySpace(spaceID common.EntityID) {
	if bot.currentSpace == nil || bot.currentSpace.ID != spaceID {
		gwlog.TraceError("%s.destroySpace: space %s not exists, current space is %s", bot, spaceID, bot.currentSpace)
		return
	}
	oldSpace := bot.currentSpace
	bot.currentSpace = nil
	gwlog.Debugf("%s: leave current space %s", bot, spaceID)
	bot.OnLeaveSpace(oldSpace)
}

func (bot *ClientBot) callEntityMethod(entityID common.EntityID, method string, args [][]byte) {
	entity := bot.entities[entityID]
	if entity == nil {
		gwlog.Warnf("Entity %s is not found while calling method %s(%v)", entityID, method, args)
		return
	}

	methodVal := reflect.ValueOf(entity).MethodByName(method)
	if !methodVal.IsValid() {
		gwlog.Errorf("Client method %s is not found", method)
		return
	}

	methodType := methodVal.Type()
	in := make([]reflect.Value, len(args))

	for i, arg := range args {
		argType := methodType.In(i)
		argValPtr := reflect.New(argType)
		netutil.MSG_PACKER.UnpackMsg(arg, argValPtr.Interface())
		in[i] = reflect.Indirect(argValPtr)
	}
	methodVal.Call(in)
}

func (bot *ClientBot) username() string {
	return fmt.Sprintf("test%d", bot.id)
}

func (bot *ClientBot) password() string {
	return "123456"
}

// CallServer calls server method of target e
func (bot *ClientBot) CallServer(id common.EntityID, method string, args []interface{}) {
	if !quiet {
		gwlog.Debugf("%s call server: %s.%s%v", bot, id, method, args)
	}
	bot.conn.SendCallEntityMethodFromClient(id, method, args)
}

// OnEnterSpace is called when player enters space
func (bot *ClientBot) OnEnterSpace() {
	gwlog.Debugf("%s.OnEnterSpace, player=%s", bot, bot.player)
	player := bot.player
	if !bot.startedDoingThings {
		bot.startedDoingThings = true
		player.doSomethingLater()
	} else {
		player.notifyThingDone("DoEnterRandomSpace")
	}
}

// OnLeaveSpace is called when player leaves space
func (bot *ClientBot) OnLeaveSpace(oldSpace *ClientSpace) {
	gwlog.Debugf("%s.OnLeaveSpace, player=%s", bot, bot.player)
}

repository: MrGru/goworld

repo_name: MrGru/goworld


text:
// Copyright 2020 Phyronnaz

#pragma once

#include "CoreMinimal.h"

template<typename T>
using TVoxelSharedRef = TSharedRef<T, ESPMode::ThreadSafe>;
template<typename T>
using TVoxelSharedPtr = TSharedPtr<T, ESPMode::ThreadSafe>;
template<typename T>
using TVoxelWeakPtr = TWeakPtr<T, ESPMode::ThreadSafe>;
template<typename T>
using TVoxelSharedFromThis = TSharedFromThis<T, ESPMode::ThreadSafe>;

template<typename CastToType, typename CastFromType>
inline TVoxelSharedRef<CastToType> StaticCastVoxelSharedRef(const TVoxelSharedRef<CastFromType>& InSharedRef)
{
	return StaticCastSharedRef<CastToType, CastFromType, ESPMode::ThreadSafe>(InSharedRef);
}

template<typename CastToType, typename CastFromType>
inline TVoxelSharedPtr<CastToType> StaticCastVoxelSharedPtr(const TVoxelSharedPtr<CastFromType>& InSharedPtr)
{
	return StaticCastSharedPtr<CastToType, CastFromType, ESPMode::ThreadSafe>(InSharedPtr);
}

template<typename T, typename... InArgTypes>
inline TVoxelSharedRef<T> MakeVoxelShared(InArgTypes&&... Args)
{
	return MakeShared<T, ESPMode::ThreadSafe>(Forward<InArgTypes>(Args)...);
}

template<typename T, template<class, ESPMode> class TPtr>
inline TVoxelWeakPtr<T> MakeVoxelWeakPtr(const TPtr<T, ESPMode::ThreadSafe>& Ptr)
{
	return TVoxelWeakPtr<T>(Ptr);
}
template<typename T>
inline TVoxelWeakPtr<T> MakeVoxelWeakPtr(T* Ptr)
{
	return TVoxelWeakPtr<T>(StaticCastVoxelSharedRef<T>(Ptr->AsShared()));
}

template<typename T, template<class, ESPMode> class TPtr>
inline TWeakPtr<T> MakeWeakPtr(const TPtr<T, ESPMode::Fast>& Ptr)
{
	return TWeakPtr<T>(Ptr);
}
template<typename T>
inline TWeakPtr<T> MakeWeakPtr(T* Ptr)
{
	return TWeakPtr<T>(StaticCastSharedRef<T>(Ptr->AsShared()));
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

template<class Lambda>
struct TLambdaConditionalForward : TLambdaConditionalForward<decltype(&Lambda::operator())>
{
};

template<typename TReturnType, typename TClass, typename... TArgs>
struct TLambdaConditionalForward<TReturnType(TClass::*)(TArgs...) const> : TLambdaConditionalForward<TReturnType(TClass::*)(TArgs...)>
{

};

template<typename TReturnType, typename TClass, typename... TArgs>
struct TLambdaConditionalForward<TReturnType(TClass::*)(TArgs...)>
{
	template<typename TLambda, typename TGetCondition, typename TCheckCondition>
	static auto Create(TLambda Lambda, TGetCondition GetCondition, TCheckCondition CheckCondition)
	{
		return [=](TArgs... Args)
		{
			// Could be a shared pointer, or a bool
			auto&& Condition = GetCondition();
			if (CheckCondition(Condition))
			{
				Lambda(Forward<TArgs>(Args)...);
			}
		};
	}
};

template<typename T, typename TLambda>
inline auto MakeWeakPtrLambda(const T& Ptr, TLambda Lambda)
{
	return TLambdaConditionalForward<TLambda>::Create(Lambda, [WeakPtr = MakeWeakPtr(Ptr)]() { return WeakPtr.Pin(); }, [](const auto& Ptr) { return Ptr.IsValid(); });
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

template<class Lambda>
struct TDelegateFromLambda : TDelegateFromLambda<decltype(&Lambda::operator())>
{
};

template<typename TReturnType, typename TClass, typename... TArgs>
struct TDelegateFromLambda<TReturnType(TClass::*)(TArgs...) const> : TDelegateFromLambda<TReturnType(TClass::*)(TArgs...)>
{

};

template<typename TReturnType, typename TClass, typename... TArgs>
struct TDelegateFromLambda<TReturnType(TClass::*)(TArgs...)>
{
	template<typename TLambda>
	static auto Create(TLambda Lambda)
	{
		return TBaseDelegate<TReturnType, TArgs...>::CreateLambda(Lambda);
	}
};

template<typename TLambda>
inline auto MakeLambdaDelegate(TLambda Lambda)
{
	return TDelegateFromLambda<TLambda>::Create(Lambda);
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

template<typename T, typename TLambda>
inline auto MakeWeakPtrDelegate(const T& Ptr, TLambda Lambda)
{
	return MakeLambdaDelegate(MakeWeakPtrLambda(Ptr, Lambda));
}


text:
PD = "Library for applications dealing with netlink sockets"
PV = "3.4.0"

HOMEPAGE = "https://github.com/thom311/libnl/"
LICENSE = "GPL"

SRC_URI = " \
  https://github.com/thom311/libnl/releases/download/${P}${@d.getVar('PV').replace('.','_')}/${S}.tar.gz;md5sum=8f71910c03db363b41e2ea62057a4311 \
  file://0001-musl-workaround.patch \
"

HOST_DEPENDS = "flex bison"
DEPENDS = "crosstool-ng"

step_build() {
  cd "${SRCDIR}"/${S}

  patch -Np1 -i "${SRCDIR}"/0001-musl-workaround.patch

  ./configure \
    --host=${TARGET_SYS} \
    --prefix=${SDK_SYSROOT}/usr \
    --sysconfdir=${SDK_SYSROOT}/etc \
    --disable-static

  make
}

step_install() {
  cd "${SRCDIR}"/${S}
  make DESTDIR="${FILES_DEV}" install

  cd "${FILES_DEV}"/${SDK_SYSROOT}
  find usr/lib -name "*.so*" -exec cp --parents {} "${FILES_PKG}" \;

  install_license "${SRCDIR}"/${S}/COPYING "${FILES_PKG}"
}

repository: typedivision/pacstage

repo_name: typedivision/pacstage


text:
@ARTICLE{example,
  author  = {Other, Anthony Norman},
  title   = {Some things I did},
  year    = {2014},
  journal = {J.~Irrep. Res.},
  volume  = {1},
  number  = {1},
  pages   = {1-10}
}

repository: bhishanpdl/Programming

repo_name: bhishanpdl/Programming


text:
inherit esw_examples features_check

REQUIRED_MACHINE_FEATURES = "nandpsu"

ESW_COMPONENT_SRC = "/XilinxProcessorIPLib/drivers/nandpsu/examples/"

repository: Xilinx/meta-xilinx

repo_name: Xilinx/meta-xilinx


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

package get

import (
	"io"

	antctlOutput "antrea.io/antrea/pkg/antctl/output"
)

func output(resources interface{}, single bool, outputFormat string, output io.Writer,
	transform func(r interface{}, single bool) (interface{}, error)) error {
	switch outputFormat {
	case "json":
		if err := antctlOutput.JsonOutput(resources, output); err != nil {
			return err
		}
	case "yaml":
		if err := antctlOutput.YamlOutput(resources, output); err != nil {
			return err
		}
	default:
		obj, err := transform(resources, single)
		if err != nil {
			return err
		}
		err = antctlOutput.TableOutputForGetCommands(obj, output)
		if err != nil {
			return err
		}
	}

	return nil
}

repository: tnqn/antrea

repo_name: tnqn/antrea


text:
/*
Copyright (c) 2018 Uber Technologies, 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.
*/

#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_op_kernel.h"
#include "tensorflow/core/framework/queue_interface.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "persistent_tensor_ex.h"
#include "tensorflow/core/util/batch_util.h"
#include "tensor_handlers.h"

using namespace tensorflow;
using namespace std;

Status PersistentTensorEx::CopyToSlice(OpKernelContext* ctx, Tensor* slice, int64 index) {
    if(index_ == -1)
        // Copy element
        return batch_util::CopyElementToSlice(*AccessTensor(ctx), slice, index);
    return batch_util::CopySliceToSlice(*AccessTensor(ctx), index_, slice, index);
}

Status PersistentTensorEx::CopyToElement(OpKernelContext* ctx, Tensor* element) {
    if(index_ == -1) {
        // Copy element
        *element = *AccessTensor(ctx);
        return Status::OK();
    }
    TF_RETURN_IF_ERROR(ctx->allocate_temp(
        type_, shape_, element));
    return batch_util::CopySliceToElement(*AccessTensor(ctx), element, index_);
}

repository: laket/ape-x

repo_name: laket/ape-x

extension: cpp


text:
@inproceedings{10.1145/3406601.3406613,
author = {Ruenin, Pisol and Bootkrajang, Jakramate and Chawachat, Jakarin},
title = {A System to Estimate the Amount and Calories of Food That Elderly People in the Hospital Consume},
year = {2020},
isbn = {9781450377591},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
url = {https://doi.org/10.1145/3406601.3406613},
doi = {10.1145/3406601.3406613},
articleno = {8},
numpages = {7},
keywords = {Machine learning, Food classification, Food estimation, Image recognition, CNN},
location = {Bangkok, Thailand},
series = {IAIT2020}
}

repository: pisol-ruenin/calorie-model

repo_name: pisol-ruenin/calorie-model


text:
@article{article,
author = {Su, Xiaoquan and Jing, Gongchao and Mcdonald, Daniel and Wang, Honglei and Wang, Zengbin and Gonzalez, Antonio and Sun, Zheng and Huang, Shi and Navas, Jose and Knight, Rob and Xu, Jian},
year = {2018},
month = {11},
pages = {},
title = {Identifying and Predicting Novelty in Microbiome Studies},
volume = {9},
journal = {mBio},
doi = {10.1128/mBio.02099-18}
}

@article{10.1093/bioinformatics/btz910,
    author = {Jing, Gongchao and Zhang, Yufeng and Yang, Ming and Liu, Lu and Xu, Jian and Su, Xiaoquan},
    title = "{Dynamic Meta-Storms enables comprehensive taxonomic and phylogenetic comparison of shotgun metagenomes at the species level}",
    journal = {Bioinformatics},
    year = {2019},
    month = {12},
    abstract = "{An accurate and reliable distance (or dissimilarity) among shotgun metagenomes is fundamental to deducing the beta-diversity of microbiomes. To compute the distance at the species level, current methods either ignore the evolutionary relationship among species or fail to account for unclassified organisms that cannot be mapped to definite tip nodes in the phylogenic tree, thus can produce erroneous beta-diversity pattern.To solve these problems, we propose the Dynamic Meta-Storms (DMS) algorithm to enable the comprehensive comparison of metagenomes on the species level with both taxonomy and phylogeny profiles. It compares the identified species of metagenomes with phylogeny, and then dynamically places the unclassified species to the virtual nodes of the phylogeny tree via their higher-level taxonomy information. Its high speed and low memory consumption enable pairwise comparison of 100 000 metagenomes (synthesized from 3688 bacteria) within 6.4 h on a single computing node.An optimized implementation of DMS is available on GitHub (https://github.com/qibebt-bioinfo/dynamic-meta-storms) under a GNU GPL license. It takes the species-level profiles of metagenomes as input, and generates their pairwise distance matrix. The bacterial species-level phylogeny tree and taxonomy information of MetaPhlAn2 have been integrated into this implementation, while customized tree and taxonomy are also supported.Supplementary data are available at Bioinformatics online.}",
    issn = {1367-4803},
    doi = {10.1093/bioinformatics/btz910},
    url = {https://doi.org/10.1093/bioinformatics/btz910},
    note = {btz910},
    eprint = {https://academic.oup.com/bioinformatics/advance-article-pdf/doi/10.1093/bioinformatics/btz910/31574827/btz910.pdf},
}


text:
// Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 access

import (
	"encoding/json"

	"github.com/go-logr/logr"
	"github.com/gophercloud/gophercloud"
)

// following https://github.com/terraform-provider-openstack/terraform-provider-openstack/blob/cec35ae29769b4de7d84980b1335a2b723ffb15f/openstack/networking_v2_shared.go

type neutronErrorWrap struct {
	NeutronError neutronError
}

type neutronError struct {
	Message string `json:"message"`
	Type    string `json:"type"`
	Detail  string `json:"detail"`
}

func retryOnError(log logr.Logger, err error) bool {
	switch err := err.(type) {
	case gophercloud.ErrDefault409:
		neutronError, e := decodeNeutronError(err.ErrUnexpectedResponseCode.Body)
		if e != nil {
			// retry, when error type cannot be detected
			log.V(4).Info("[DEBUG] failed to decode a neutron error", "error", e)
			return true
		}
		if neutronError.Type == "IpAddressGenerationFailure" {
			return true
		}

		// don't retry on quota or other errors
		return false
	case gophercloud.ErrDefault400:
		neutronError, e := decodeNeutronError(err.ErrUnexpectedResponseCode.Body)
		if e != nil {
			// retry, when error type cannot be detected
			log.V(4).Info("[DEBUG] failed to decode a neutron error", "error", e)
			return true
		}
		if neutronError.Type == "ExternalIpAddressExhausted" {
			return true
		}

		// don't retry on quota or other errors
		return false
	case gophercloud.ErrDefault404: // this case is handled mostly for functional tests
		return true
	}

	return false
}

func decodeNeutronError(body []byte) (*neutronError, error) {
	e := &neutronErrorWrap{}
	if err := json.Unmarshal(body, e); err != nil {
		return nil, err
	}

	return &e.NeutronError, nil
}

gha_license_id: NOASSERTION