text:
inherit pypi python_setuptools_build_meta

SUMMARY = "Jupyter notebook"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://COPYING.md;md5=d235895c780fa844e875697e16e5787b"

SRC_URI[sha256sum] = "6f6ead433b0534909df789ea64f0a14cdf9b6b2360757756f08182be4b9e431b"

RDEPENDS:${PN} += " \
        ${PYTHON_PN}-ipykernel \
        ${PYTHON_PN}-ipython \
        ${PYTHON_PN}-jupyter-client \
        ${PYTHON_PN}-pygments \
        "

PYPI_PACKAGE = "jupyter_console"

do_install:append() {
        # Make sure we use /usr/bin/env python
        for PYTHSCRIPT in `grep -rIl '^#!.*python' ${D}`; do
                sed -i -e '1s|^#!.*|#!/usr/bin/env ${PYTHON_PN}|' $PYTHSCRIPT
        done
}

RDEPENDS:${PN} += " \
	${PYTHON_PN}-prompt-toolkit \
	"

license: MIT

repository: Xilinx/meta-jupyter

license_type: permissive

repo_name: Xilinx/meta-jupyter

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: BitBake

extension: bb


text:
// Copyright 2014-2015 Apptimist, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"encoding/binary"
	"io"
	"math"
	"time"
)

type AnonymousNBOReader io.Reader
type AnonymousNBOWriter io.Writer
type NBOReader struct{ AnonymousNBOReader }
type NBOWriter struct{ AnonymousNBOWriter }

// ReadNBO is an io.Reader wrapper that reads; then converts the Network Byte
// Order number before storing at the given pointer. This returns the number of
// bytes read along with any errors.
//
// Usage:
//	var u unit64
//	var f float64
//	(NBOReader{r}).ReadNBO(&u)
//	(NBOReader{r}).ReadNBO(&f)
func (r NBOReader) ReadNBO(v interface{}) (n int, err error) {
	b := []byte{0, 0, 0, 0, 0, 0, 0, 0}
	switch t := v.(type) {
	case *uint8:
		if n, err = r.Read(b[:1]); err == nil {
			*t = b[0]
		}
	case *int8:
		if n, err = r.Read(b[:1]); err == nil {
			*t = int8(b[0])
		}
	case *uint16:
		if n, err = r.Read(b[:2]); err == nil {
			*t = binary.BigEndian.Uint16(b[:2])
		}
	case *int16:
		if n, err = r.Read(b[:1]); err == nil {
			*t = int16(binary.BigEndian.Uint16(b[:2]))
		}
	case *uint32:
		if n, err = r.Read(b[:4]); err == nil {
			*t = binary.BigEndian.Uint32(b[:4])
		}
	case *int32:
		if n, err = r.Read(b[:4]); err == nil {
			*t = int32(binary.BigEndian.Uint32(b[:4]))
		}
	case *uint64:
		if n, err = r.Read(b[:8]); err == nil {
			*t = binary.BigEndian.Uint64(b[:8])
		}
	case *int64:
		if n, err = r.Read(b[:1]); err == nil {
			*t = int64(binary.BigEndian.Uint64(b[:8]))
		}
	case *float64:
		if n, err = r.Read(b[:8]); err == nil {
			bits := binary.BigEndian.Uint64(b[:8])
			*t = math.Float64frombits(bits)
		}
	case *time.Time:
		if n, err = r.Read(b[:8]); err == nil {
			nanoepoch := int64(binary.BigEndian.Uint64(b[:8]))
			isec := int64(time.Second)
			*t = time.Unix(nanoepoch/isec, nanoepoch%isec)
		}
	}
	return
}

// WriteNBO is an io.Writer wrapper that converts the given number to Network
// Byte Order before writing to the associated writer.  This returns the number
// of bytes writen along with any errors.
//
// Usage:
//	(NBOWriter{w}).WriteNBO(uint64(0x1234))
//	(NBOWriter{w}).WriteNBO(98.6)
//	...
func (w NBOWriter) WriteNBO(v interface{}) (n int, err error) {
	b := []byte{0, 0, 0, 0, 0, 0, 0, 0}
	switch t := v.(type) {
	case uint8:
		b[0] = t
		n, err = w.Write(b[:1])
	case int8:
		b[0] = uint8(t)
		n, err = w.Write(b[:1])
	case uint16:
		binary.BigEndian.PutUint16(b[:2], t)
		n, err = w.Write(b[:2])
	case int16:
		u := uint16(t)
		binary.BigEndian.PutUint16(b[:2], u)
		n, err = w.Write(b[:2])
	case uint32:
		binary.BigEndian.PutUint32(b[:4], t)
		n, err = w.Write(b[:4])
	case int32:
		u := uint32(t)
		binary.BigEndian.PutUint32(b[:4], u)
		n, err = w.Write(b[:4])
	case uint64:
		binary.BigEndian.PutUint64(b[:8], t)
		n, err = w.Write(b[:8])
	case int64:
		u := uint64(t)
		binary.BigEndian.PutUint64(b[:8], u)
		n, err = w.Write(b[:8])
	case float64:
		binary.BigEndian.PutUint64(b[:8], math.Float64bits(t))
		n, err = w.Write(b[:8])
	case time.Time:
		binary.BigEndian.PutUint64(b[:8], uint64(t.UnixNano()))
		n, err = w.Write(b[:8])
	}
	return
}

repository: digideskio/asn

repo_name: digideskio/asn

extension: go


text:
package graphqlobjects

import (
  "github.com/graphql-go/graphql"

  "github.com/ccleung/playground/dataobjects"
)

var(
  Organization *graphql.Object
  User *graphql.Object
)

func init() {
   User = graphql.NewObject(graphql.ObjectConfig{
    Name: "User",
    Fields: graphql.Fields{
     "id": &graphql.Field{
       Type: graphql.String,
     },
     "name": &graphql.Field{
       Type: graphql.String,
     },
   },
  })

  Organization = graphql.NewObject(graphql.ObjectConfig{
    Name: "Organization",
    Fields: graphql.Fields{
      "user": &graphql.Field{
        Type: User,
        Resolve: func(p graphql.ResolveParams) (interface{}, error) {
          return p.Source.(*dataobjects.Organization).User, nil
        },
      },
    },
  })
}

repository: ccleung/playground

repo_name: ccleung/playground


text:
SUMMARY = "Random number generator daemon"
DESCRIPTION = "Check and feed random data from hardware device to kernel"
AUTHOR = "Philipp Rumpf, Jeff Garzik <jgarzik@pobox.com>, \
          Henrique de Moraes Holschuh <hmh@debian.org>"
HOMEPAGE = "https://github.com/nhorman/rng-tools"
BUGTRACKER = "https://github.com/nhorman/rng-tools/issues"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=b234ee4d69f5fce4486a80fdaf4a4263"
DEPENDS = "sysfsutils"

SRC_URI = "\
    git://github.com/nhorman/rng-tools.git \
    file://init \
    file://default \
    file://rngd.service \
"
SRCREV = "9fc873c5af0e392632e6b736938b811f7ca97251"

S = "${WORKDIR}/git"

inherit autotools update-rc.d systemd pkgconfig

PACKAGECONFIG ??= "libgcrypt libjitterentropy"
PACKAGECONFIG:libc-musl = "libargp libjitterentropy"

PACKAGECONFIG[libargp] = "--with-libargp,--without-libargp,argp-standalone,"
PACKAGECONFIG[libgcrypt] = "--with-libgcrypt,--without-libgcrypt,libgcrypt,"
PACKAGECONFIG[libjitterentropy] = "--enable-jitterentropy,--disable-jitterentropy,libjitterentropy"
PACKAGECONFIG[libp11] = "--with-pkcs11,--without-pkcs11,libp11 openssl"
PACKAGECONFIG[nistbeacon] = "--with-nistbeacon,--without-nistbeacon,curl libxml2 openssl"

INITSCRIPT_NAME = "rng-tools"
INITSCRIPT_PARAMS = "start 03 2 3 4 5 . stop 30 0 6 1 ."

SYSTEMD_SERVICE:${PN} = "rngd.service"

# Refer autogen.sh in rng-tools
do_configure:prepend() {
    cp ${S}/README.md ${S}/README
}

do_install:append() {
    install -Dm 0644 ${WORKDIR}/default ${D}${sysconfdir}/default/rng-tools
    install -Dm 0755 ${WORKDIR}/init ${D}${sysconfdir}/init.d/rng-tools
    install -Dm 0644 ${WORKDIR}/rngd.service \
                     ${D}${systemd_system_unitdir}/rngd.service
    sed -i \
        -e 's,@SYSCONFDIR@,${sysconfdir},g' \
        -e 's,@SBINDIR@,${sbindir},g' \
        ${D}${sysconfdir}/init.d/rng-tools \
        ${D}${systemd_system_unitdir}/rngd.service
}

repository: Intel-BMC/openbmc

repo_name: Intel-BMC/openbmc

gha_license_id: NOASSERTION

gha_language: Python


text:
require xorg-util-common.inc
inherit native

DESCRIPTION = "create dependencies in makefiles"
DEPENDS = "xproto-native util-macros-native"
PR = "r2"
PE = "1"

XORG_PN = "makedepend"


text:
@unpublished{clav,
    author = {Alexandra Lourenço and José Carlos Ramalho and Maria Rita Gago and Pedro Penteado},
	title = {{Plataforma CLAV: contributo para a disponibilização de dados abertos da Administração Pública em Portugal}},
	url = {http://eprints.rclis.org/38643/1/Plantilla_EDICIC2019Barcelona-PT-COM_Penteado_v08.pdf},
    note = {Acedido a 2019-11-20},
    month = 7,
    year = 2019
}

@misc{authgov,
  author = {AMA},
  title = {{Autenticação.gov}},
  url = {https://autenticacao.gov.pt/fa/Default.aspx},
  year = 2019,
  note = {Acedido a 2019-11-20}
}

@book{elojs,
  author = {Marijn Haverbeke},
  title = {{Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming}},
  publisher = {No Starch Press},
  edition = {3rd},
  year = 2018,
  month = 12,
  isbn = {978-1-59327-950-9}
}

@book{restws,
  author = {Leonard Richardson and Sam Ruby},
  title = {{RESTful Web Services}},
  publisher = {O'Reilly},
  edition = {1st},
  year = 2007,
  month = 5,
  isbn = {978-0-596-52926-0}
}

@manual{agov,
  author = {AMA},
  title = {{Autenticação.gov - Fornecedor de autenticação da Administração Pública Portuguesa}},
  edition = {1.5.1},
  year = 2018,
  month = 12
}

@manual{agov2,
  author = {AMA},
  title = {{Autenticação.gov - Fornecedor de autenticação da Administração Pública Portuguesa}},
  edition = {1.5.3},
  year = 2020,
  month = 02
}

@book{lsparql,
  author = {Bob DuCharme},
  title = {{Learning SPARQL}},
  publisher = {O'Reilly},
  edition = {1st},
  year = 2011,
  month = 7,
  isbn = {978-1-449-30659-5}
}

@book{bontology,
  author = {Robert Arp and Barry Smith and Andrew Spear},
  title = {{Building Ontologies with Basic Formal Ontology}},
  publisher = {MIT Press},
  edition = {1st},
  year = 2015,
  month = 7,
  isbn = {978-0-262-52781-1}
}

@misc{ontologyProt,
  author = {Natalya F. Noy and Deborah L. McGuinness},
  title = {{Ontology Development 101: A Guide to Creating Your First Ontology}},
  url = {https://protege.stanford.edu/publications/ontology_development/ontology101-noy-mcguinness.html},
  year = 2000,
  note = {Acedido a 2020-05-01}
}

@book{udocker,
  author = {Adrian Mouat},
  title = {{Using Docker}},
  publisher = {O'Reilly},
  edition = {1st},
  year = 2015,
  month = 12,
  isbn = {978-1-491-91576-9}
}

@book{wdmongo,
  author = {Mithun Satheesh and Mithun Satheesh and Jason Krol},
  title = {{Web Development with MongoDB and NodeJS}},
  publisher = {Packt Publishing},
  edition = {2nd},
  year = 2015,
  month = 10,
  isbn = {978-1-78528-752-7}
}

@book{nginxcook,
  author = {Derek DeJonghe},
  title = {{NGINX Cookbook}},
  publisher = {O'Reilly},
  edition = {1st},
  year = 2018,
  month = 11,
  isbn = {978-1-491-96893-2},
  note = {Second Release}
}

@misc{clavwebpage,
  author = {DGLAB},
  title = {{CLAV - Classificação e Avaliação da Informação Pública}},
  url = {http://clav.dglab.gov.pt},
  year = 2019,
  note = {Acedido a 2019-12-15}
}

@misc{passport,
  author = {Passport.js},
  title = {{Overview}},
  url = {http://www.passportjs.org/docs/},
  year = 2019,
  note = {Acedido a 2019-12-17}
}

@misc{jwtio,
  author = {Auth0},
  title = {{Introduction to JSON Web Tokens}},
  url = {https://jwt.io/introduction/},
  year = 2019,
  note = {Acedido a 2019-12-19}
}

@book{jwthandbook,
  author = {Sebastián E. Peyrott},
  title = {{The JWT Handbook}},
  edition = {0.14.1},
  publisher = {Auth0 Inc},
  year = 2018
}

@misc{jwtvuln,
  author = {Tim McLean},
  title = {{Critical vulnerabilities in JSON Web Token libraries}},
  url = {https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/},
  year = 2015,
  month = 3,
  note = {Acedido a 2019-12-22}
}

@misc{branca,
  author = {Mika Tuupola},
  title = {{Branca as an Alternative to JWT?}},
  url = {https://appelsiini.net/2017/branca-alternative-to-jwt/},
  year = 2017,
  month = 8,
  note = {Acedido a 2019-12-22}
}

@manual{sam2man,
  author = {Hal Lockhart and Thomas Wisniewski and Prateek Mishra and Nick Ragouzis},
  title = {{Security Assertion Markup Language(SAML) V2.0 Technical Overview}},
  organization = {OASIS},
  year = 2005,
  month = 7
}

@misc{wisaml,
  author = {Jeff Petters},
  title = {{What is SAML and How Does it Work?}},
  url = {https://www.varonis.com/blog/what-is-saml/},
  year = 2018,
  month = 8,
  note = {Acedido a 2019-12-26}
}

@misc{wiswagger,
  author = {Swagger},
  title = {{What is Swagger?}},
  url = {https://swagger.io/tools/open-source/getting-started/},
  year = 2019,
  note = {Acedido a 2019-12-27}
}

@misc{swaggerVSoas,
  author = {Ryan Pinkham},
  title = {{What Is the Difference Between Swagger and OpenAPI?}},
  url = {https://swagger.io/blog/api-strategy/difference-between-swagger-and-openapi/},
  year = 2017,
  month = 10,
  note = {Acedido a 2019-12-27}
}

@misc{swaggerNode,
  author = {Ivan Vasiljevic},
  title = {{Adding Swagger To Existing Node.js Project}},
  url = {https://blog.cloudboost.io/adding-swagger-to-existing-node-js-project-92a6624b855b},
  year = 2017,
  month = 8,
  note = {Acedido a 2019-12-28}
}

@misc{specsComp,
  author = {Kristopher Sandoval},
  title = {{Top Specification Formats for REST APIs}},
  url = {https://nordicapis.com/top-specification-formats-for-rest-apis/},
  year = 2016,
  month = 3,
  note = {Acedido a 2019-12-31}
}

@misc{graphdbArch,
  author = {Ontotext},
  title = {{Architecture \& Components}},
  url = {http://graphdb.ontotext.com/documentation/free/architecture-components.html},
  year = 2019,
  month = 12,
  note = {Acedido a 2020-01-09}
}

@misc{graphdbAbout,
  author = {Ontotext},
  title = {{About GraphDB}},
  url = {http://graphdb.ontotext.com/documentation/free/about-graphdb.html},
  year = 2020,
  month = 1,
  note = {Acedido a 2020-01-09}
}

@misc{apiGatInfo,
  author = {Guy Levin},
  title = {{The Role of API Gateways in API Security}},
  url = {https://dzone.com/articles/the-role-of-api-gateways-in-api-security},
  year = 2018,
  month = 8,
  note = {Acedido a 2020-05-11}
}

@misc{apiGatInfo2,
  author = {Rolando Santamaria Maso},
  title = {{A faster Node.js API Gateway for the masses (update 02/06/2019)}},
  url = {https://medium.com/sharenowtech/k-fastify-gateway-a-node-js-api-gateway-that-you-control-e7388c229b21},
  year = 2019,
  month = 6,
  note = {Acedido a 2020-05-11}
}

@misc{nginxPvsKong,
  author = {Faisal Memon},
  title = {{NGINX Controller API Management Module vs. Kong: Performance Comparison}},
  url = {https://www.nginx.com/blog/nginx-controller-api-management-module-vs-kong-performance-comparison/},
  year = 2019,
  month = 5,
  note = {Acedido a 2020-05-14}
}

@misc{nginxP,
  author = {Karthik Krishnaswamy},
  title = {{Introducing NGINX API Management: Manage NGINX Plus API Gateways with NGINX Controller}},
  url = {https://www.nginx.com/blog/introducing-nginx-api-management-api-gateways-with-nginx-controller/},
  year = 2018,
  month = 10,
  note = {Acedido a 2020-05-14}
}

@misc{compAPIGat,
  author = {Mahesh Mahadevan},
  title = {{My experiences with API gateways…}},
  url = {https://medium.com/@mahesh.mahadevan/my-experiences-with-api-gateways-8a93ad17c4c4},
  year = 2019,
  month = 4,
  note = {Acedido a 2020-05-14}
}

@misc{moleculerAPIG,
  author = {MoleculerJS},
  title = {{API Gateway}},
  url = {https://moleculer.services/docs/0.14/moleculer-web.html},
  year = 2020,
  month = 4,
  note = {Acedido a 2020-05-15}
}

@misc{apiGatInfo3,
  author = {Marcus Schiesser},
  title = {{What is an API Gateway?}},
  url = {https://glasnostic.com/blog/what-is-an-api-gateway-aws-express-kong},
  year = 2019,
  month = 1,
  note = {Acedido a 2020-05-15}
}

@misc{tyk,
  author = {LunchBadger},
  title = {{API Gateway: Express Gateway vs Tyk}},
  url = {https://www.lunchbadger.com/vs-tyk-api-gateway-express-pricing/},
  year = 2018,
  month = 10,
  note = {Acedido a 2020-05-16}
}

@misc{kong,
  author = {LunchBadger},
  title = {{API Gateway Comparison Guide}},
  url = {https://www.lunchbadger.com/api-gateway-comparison-kong-enterprise-pricing-vs-express-gateway/},
  year = 2018,
  month = 10,
  note = {Acedido a 2020-05-16}
}

@misc{kongDBLess,
  author = {Kong},
  title = {{DB-less and Declarative Configuration}},
  url = {https://docs.konghq.com/2.0.x/db-less-and-declarative-config/},
  year = 2020,
  note = {Acedido a 2020-05-16}
}

@misc{kongArch,
  author = {Kong},
  title = {{Getting Started Guide}},
  url = {https://docs.konghq.com/getting-started-guide/latest/overview/},
  year = 2020,
  note = {Acedido a 2020-05-16}
}

@misc{kongRateLimiting,
  author = {Kong},
  title = {{Rate Limiting}},
  url = {https://docs.konghq.com/hub/kong-inc/rate-limiting/},
  year = 2020,
  note = {Acedido a 2020-05-28}
}

@misc{kongCORS,
  author = {Kong},
  title = {{CORS}},
  url = {https://docs.konghq.com/hub/kong-inc/cors/},
  year = 2020,
  note = {Acedido a 2020-05-28}
}

@misc{kongProxyCache,
  author = {Kong},
  title = {{Proxy Cache}},
  url = {https://docs.konghq.com/hub/kong-inc/proxy-cache/},
  year = 2020,
  note = {Acedido a 2020-05-28}
}

@misc{kongResponseTransformer,
  author = {Kong},
  title = {{Response Transformer}},
  url = {https://docs.konghq.com/hub/kong-inc/response-transformer/},
  year = 2020,
  note = {Acedido a 2020-05-28}
}

@misc{kongACME,
  author = {Kong},
  title = {{ACME}},
  url = {https://docs.konghq.com/hub/kong-inc/acme/},
  year = 2020,
  note = {Acedido a 2020-05-29}
}

@misc{procNeg,
  author = {Maria Celeste Pereira and Alexandra Lourenço},
  title = {{Apresentação de novo processo de negócio para integração na Lista Consolidada}},
  url = {http://arquivos.dglab.gov.pt/wp-content/uploads/sites/16/2017/08/FT3_Novo-PN.pdf},
  year = 2016,
  month = 12,
  note = {Acedido a 2020-06-01},
  edition = {1}
}

@misc{pca,
  author = {Zélia Gomes and Alexandra Lourenço},
  title = {{Boas práticas de eliminação de documentos}},
  url = {http://arquivos.dglab.gov.pt/wp-content/uploads/sites/16/2019/08/FT9_Eliminacao_2019-08-20.pdf.pdf},
  year = 2019,
  note = {Acedido a 2020-06-01},
  edition = {1}
}

@misc{lc,
  author = {Clara Viegas and Alexandra Lourenço},
  title = {{O que é a Lista Consolidada}},
  url = {http://arquivos.dglab.gov.pt/wp-content/uploads/sites/16/2017/08/FT2_LC.pdf},
  year = 2016,
  month = 12,
  note = {Acedido a 2020-06-01},
  edition = {1}
}

@misc{ts,
  author = {Filipa Carvalho and Helena Neves and Rita Gago and Alexandra Lourenço},
  title = {{Aplicação de uma tabela de seleção}},
  url = {http://arquivos.dglab.gov.pt/wp-content/uploads/sites/16/2017/08/FT5_Aplicacao-TS.pdf},
  year = 2016,
  note = {Acedido a 2020-06-01},
  edition = {1}
}

@misc{tsDef,
  author = {Clara Viegas and Alexandra Lourenço},
  title = {{Tabelas de seleção: aplicação no tempo}},
  url = {http://arquivos.dglab.gov.pt/wp-content/uploads/sites/16/2019/08/FT10_TS_Aplica%C3%A7%C3%A3o-no-tempo_2019-07-25.pdf},
  year = 2019,
  note = {Acedido a 2020-06-01},
  edition = {1}
}

@misc{clavClass,
  author = {Alexandra Lourenço},
  title = {{Aplicação do destino final: O papel do dono e do participante}},
  url = {http://arquivos.dglab.gov.pt/wp-content/uploads/sites/16/2019/08/FT8_Aplica%C3%A7%C3%A3o-DF-Dono-Participante_2019-07-25.pdf},
  year = 2019,
  note = {Acedido a 2020-06-01},
  edition = {1}
}

@article{finInit,
  author = {Henttonen, Pekka and Kettunen, Kimmo},
  year = {2011},
  month = {07},
  pages = {86-103},
  title = {{Functional classification of records and organisational structure}},
  volume = {21},
  journal = {Records Management Journal},
  doi = {10.1108/09565691111152035}
}

@misc{uniInit,
  author = {Victoria University},
  title = {{Classification}},
  url = {https://library.vicu.utoronto.ca/archives/records_management/recordkeeping_manual/recordkeeping_101/classification_how_organize_your},
  year = 2014,
  month = 12,
  note = {Acedido a 2020-06-03}
}

@misc{rada,
  author = {Maria José Chaves and Alexandra Lourenço},
  title = {{Elaboração de Relatórios de Avaliação de Documentação Acumulada}},
  url = {http://arquivos.dglab.gov.pt/wp-content/uploads/sites/16/2017/08/FT1_RADA.pdf},
  year = 2016,
  month = 12,
  note = {Acedido a 2020-06-03}
}

@misc{certsTypes,
  author = {Cloudflare},
  title = {{Types of SSL Certificates | SSL Certificate Types Explained}},
  url = {https://www.cloudflare.com/learning/ssl/types-of-ssl-certificates/},
  year = 2020,
  note = {Acedido a 2020-06-03}
}

@misc{letEnc,
  author = {Let's Encrypt},
  title = {{Getting Started}},
  url = {https://letsencrypt.org/getting-started/},
  year = 2020,
  note = {Acedido a 2020-06-03}
}

@misc{domainValidation,
  author = {Let's Encrypt},
  title = {{How It Works}},
  url = {https://letsencrypt.org/how-it-works/},
  year = 2019,
  month = 10,
  note = {Acedido a 2020-06-04}
}

@misc{LErateLimits,
  author = {Let's Encrypt},
  title = {{Rate Limits}},
  url = {https://letsencrypt.org/docs/rate-limits/},
  year = 2020,
  month = 3,
  note = {Acedido a 2020-06-06}
}

@mastersthesis{otavioTese,
  author  = {Octávio José Azevedo Maia},
  title   = {{CLAV: Autenticação e integração na plataforma iAP}},
  school  = {{Universidade do Minho}},
  year    = 2019,
  month   = 12
}

@misc{installDocker,
  author = {Docker},
  title = {{Install Docker Engine on Ubuntu}},
  url = {https://docs.docker.com/engine/install/ubuntu/},
  year = 2020,
  note = {Acedido a 2020-06-12}
}

@misc{installDC,
  author = {Docker},
  title = {{Install Docker Compose}},
  url = {https://docs.docker.com/compose/install/},
  year = 2020,
  note = {Acedido a 2020-06-12}
}

@misc{hsts2,
  author = {The HTTPS-Only Standard},
  title = {{HTTP Strict Transport Security}},
  url = {https://https.cio.gov/hsts/},
  year = 2020,
  note = {Acedido a 2020-06-12}
}

@misc{hsts,
  author = {CheatSheets Series Team},
  title = {{HTTP Strict Transport Security Cheat Sheet}},
  url = {https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Strict_Transport_Security_Cheat_Sheet.html},
  year = 2020,
  note = {Acedido a 2020-06-12}
}

@misc{helmet,
  author = {Helmet},
  title = {{Docs}},
  url = {https://helmetjs.github.io/docs/},
  year = 2020,
  note = {Acedido a 2020-06-12}
}

@misc{letEnA+,
  author = {Alives},
  title = {{HOWTO: A+ with all 100\%'s on SSL Labs test using apache2.4 (READ WARNINGS)}},
  url = {https://community.letsencrypt.org/t/howto-a-with-all-100-s-on-ssl-labs-test-using-apache2-4-read-warnings/2436},
  year = 2015,
  month = 10,
  note = {Acedido a 2020-06-12}
}

@misc{dhparams,
  author = {Melroy van den Berg},
  title = {{Let’s Encrypt – Is your website secure?}},
  url = {https://blog.melroy.org/2016/lets-encrypt/},
  year = 2016,
  month = 12,
  note = {Acedido a 2020-06-12}
}

@misc{secExpress,
  author = {Express},
  title = {{Production Best Practices: Security}},
  url = {https://expressjs.com/en/advanced/best-practice-security.html},
  year = 2017,
  note = {Acedido a 2020-06-12}
}

@misc{helmetCSP,
  author = {Helmet},
  title = {{Content Security Policy}},
  url = {https://helmetjs.github.io/docs/csp/},
  year = 2020,
  note = {Acedido a 2020-06-12}
}

@misc{csp,
  author = {Foundeo Inc},
  title = {{Content Security Policy Reference}},
  url = {https://content-security-policy.com/},
  year = 2020,
  note = {Acedido a 2020-06-12}
}

@misc{strongSSL,
  author = {Remy van Elst},
  title = {{Strong SSL Security on nginx}},
  url = {https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html},
  year = 2015,
  month = 06,
  note = {Acedido a 2020-06-12}
}

extension: bib


text:
# Distributed under the MIT License.
# See LICENSE.txt for details.

find_package(BLAS REQUIRED)
message(STATUS "BLAS libs: " ${BLAS_LIBRARIES})
file(APPEND
  "${CMAKE_BINARY_DIR}/BuildInfo.txt"
  "BLAS_LIBRARIES: ${BLAS_LIBRARIES}\n"
  )

add_library(Blas INTERFACE IMPORTED)
set_property(TARGET Blas
  APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${BLAS_LIBRARIES})

set_property(
  GLOBAL APPEND PROPERTY SPECTRE_THIRD_PARTY_LIBS
  Blas
  )

# Check if we have found OpenBLAS and can disable its multithreading, since it
# conflicts with Charm++ parallelism. Details:
# https://github.com/xianyi/OpenBLAS/wiki/Faq#multi-threaded
# We use `execute_process` instead of `try_compile` to avoid potentially slow
# disk IO.
set(
  CHECK_DISABLE_OPENBLAS_MULTITHREADING_SOURCE
  "extern \"C\" { void openblas_set_num_threads(int); }\n\
int main() { openblas_set_num_threads(1); }"
  )
string(REPLACE ";" " " BLAS_LIBRARIES_JOINED_WITH_SPACES "${BLAS_LIBRARIES}")
execute_process(
  COMMAND
  bash -c
  "${CMAKE_CXX_COMPILER} ${BLAS_LIBRARIES_JOINED_WITH_SPACES} -x c++ - <<< $'\
${CHECK_DISABLE_OPENBLAS_MULTITHREADING_SOURCE}' -o /dev/null"
  RESULT_VARIABLE CHECK_DISABLE_OPENBLAS_MULTITHREADING_RESULT
  ERROR_VARIABLE CHECK_DISABLE_OPENBLAS_MULTITHREADING_ERROR
  OUTPUT_QUIET
  )
if(${CHECK_DISABLE_OPENBLAS_MULTITHREADING_RESULT} EQUAL 0)
  set(DISABLE_OPENBLAS_MULTITHREADING ON)
  add_definitions(-DDISABLE_OPENBLAS_MULTITHREADING)
  message(STATUS "Disabled OpenBLAS multithreading")
else()
  message(STATUS "BLAS vendor is probably not OpenBLAS. Make sure it doesn't "
    "try to do multithreading that might conflict with Charm++ parallelism.")
endif()

repository: sxs-collaboration/spectre

repo_name: sxs-collaboration/spectre

branch_name: refs/heads/develop

extension: cmake


text:
@article{wye_effectiveness_2017,
 abstract = {© 2017 The Author(s). Background: Despite clinical practice guidelines recommending the routine provision of nicotine dependence treatment to smokers in inpatient psychiatric facilities, the prevalence of such treatment provision is low. The aim of this study was to examine the effectiveness of a clinical practice change intervention in increasing clinician recorded provision of nicotine dependence treatment to patients in inpatient psychiatric facilities. Methods: We undertook an interrupted time series analysis of nicotine dependence treatment provision before, during and after a clinical practice change intervention to increase clinician recorded provision of nicotine dependence treatment for all hospital discharges (aged \textgreater18 years, N = 4175) over a 19 month period in two inpatient adult psychiatric facilities in New South Wales, Australia. The clinical practice change intervention comprised six key strategies: leadership and consensus, enabling systems and procedures, training and education, information and resources, audit and feedback and an on-site practice change support officer. Systematic medical record audit and segmented logistic regression was used to determine differences in proportions for each nicotine dependence treatment outcome measure between the 'pre', 'during' and 'post-intervention' periods. Results: The prevalence of all five outcome measures increased significantly between the pre and post-intervention periods, including clinician recorded: assessment of patient smoking status (36.43 to 51.95%; adjusted odds ratio [AOR] = 2.39, 99% Confidence Interval [CI]: 1.23 to 4.66); assessment of patient nicotine dependence status (4.74 to 11.04%; AOR = 109.67, 99% CI: 35.35 to 340.22); provision of brief advice to quit (0.85 to 8.81%; AOR = 97.43, 99% CI: 31.03 to 306.30); provision of nicotine replacement therapy (8.06 to 26.25%; AOR = 19.59, 99% CI: 8.17 to 46.94); and provision of nicotine dependence treatment on discharge (8.82 to 13.45%, AOR = 12.36; 99% CI: 6.08 to 25.14). Conclusions: This is the first study to provide evidence that a clinical practice change intervention may increase clinician recorded provision of nicotine dependence treatment in inpatient psychiatric settings. The intervention offers a mechanism for psychiatric facilities to increase the provision of nicotine dependence treatment in accordance with clinical guidelines.},
 author = {Wye, P.M. and Stockings, E.A. and Bowman, J.A. and Oldmeadow, C. and Wiggers, J.H.},
 doi = {10.1186/s12888-017-1220-7},
 issn = {1471-244X},
 journal = {BMC Psychiatry},
 keywords = {implementation},
 month = {February},
 number = {1},
 title = {Effectiveness of a clinical practice change intervention in increasing the provision of nicotine dependence treatment in inpatient psychiatric facilities: An implementation trial},
 volume = {17},
 year = {2017}
}

repository: ChrisOldmeadow/academic-kickstart

repo_name: ChrisOldmeadow/academic-kickstart


text:
@article{Uddin-2020-Mining,
    title = "Mining API usage scenarios from stack overflow",
    author = "Uddin, Gias  and
      Khomh, Foutse  and
      Roy, Chanchal K",
    journal = "Information and Software Technology, Volume 122",
    volume = "122",
    year = "2020",
    publisher = "Elsevier BV",
    url = "https://aclanthology.org/G20-139001",
    doi = "10.1016/j.infsof.2020.106277",
    pages = "106277",
    abstract = "Abstract Context APIs play a central role in software development. The seminal research of Carroll et~al.~[15] on minimal manual and subsequent studies by Shull et~al.~[79] showed that developers prefer task-based API documentation instead of traditional hierarchical official documentation (e.g., Javadoc). The Q{\&}A format in Stack Overflow offers developers an interface to ask and answer questions related to their development tasks. Objective With a view to produce API documentation, we study automated techniques to mine API usage scenarios from Stack Overflow. Method We propose a framework to mine API usage scenarios from Stack Overflow. Each task consists of a code example, the task description, and the reactions of developers towards the code example. First, we present an algorithm to automatically link a code example in a forum post to an API mentioned in the textual contents of the forum post. Second, we generate a natural language description of the task by summarizing the discussions around the code example. Third, we automatically associate developers reactions (i.e., positive and negative opinions) towards the code example to offer information about code quality. Results We evaluate the algorithms using three benchmarks. We compared the algorithms against seven baselines. Our algorithms outperformed each baseline. We developed an online tool by automatically mining API usage scenarios from Stack Overflow. A user study of 31 software developers shows that the participants preferred the mined usage scenarios in Opiner over API official documentation. The tool is available online at: http://opiner.polymtl.ca/ . Conclusion With a view to produce API documentation, we propose a framework to automatically mine API usage scenarios from Stack Overflow, supported by three novel algorithms. We evaluated the algorithms against a total of eight state of the art baselines. We implement and deploy the framework in our proof-of-concept online tool, Opiner.",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

branch_name: refs/heads/main


text:
// Defines non-block movable objects such as arrows in flight, boats and
// minecarts.

package gamerules

import (
	"io"
	"os"

	"chunkymonkey/physics"
	"chunkymonkey/proto"
	. "chunkymonkey/types"
	"nbt"
)

// TODO Object sub-types?

type Object struct {
	EntityId
	ObjTypeId
	physics.PointObject
	orientation OrientationBytes
}

func NewObject(objType ObjTypeId) (object *Object) {
	object = &Object{
		// TODO: proper orientation
		orientation: OrientationBytes{0, 0, 0},
	}
	object.ObjTypeId = objType
	return
}

func (object *Object) ReadNbt(tag nbt.ITag) (err os.Error) {
	if err = object.PointObject.ReadNbt(tag); err != nil {
		return
	}

	var typeName string
	if entityObjectId, ok := tag.Lookup("id").(*nbt.String); !ok {
		return os.NewError("missing object type id")
	} else {
		typeName = entityObjectId.Value
	}

	var ok bool
	if object.ObjTypeId, ok = ObjTypeByName[typeName]; !ok {
		return os.NewError("unknown object type id")
	}

	// TODO load orientation

	return
}

func (object *Object) WriteNbt() nbt.ITag {
	objTypeName, ok := ObjNameByType[object.ObjTypeId]
	if !ok {
		return nil
	}
	tag := &nbt.Compound{map[string]nbt.ITag{
		"id": &nbt.String{objTypeName},
		// TODO unknown fields
	}}
	object.PointObject.WriteIntoNbt(tag)
	return tag
}

func (object *Object) SendSpawn(writer io.Writer) (err os.Error) {
	// TODO: Send non-nil ObjectData (is there any?)
	err = proto.WriteObjectSpawn(writer, object.EntityId, object.ObjTypeId, &object.PointObject.LastSentPosition, nil)
	if err != nil {
		return
	}

	err = proto.WriteEntityVelocity(writer, object.EntityId, &object.PointObject.LastSentVelocity)
	return
}

func (object *Object) SendUpdate(writer io.Writer) (err os.Error) {
	if err = proto.WriteEntity(writer, object.EntityId); err != nil {
		return
	}

	// TODO: Should this be the Rotation information?
	err = object.PointObject.SendUpdate(writer, object.EntityId, &LookBytes{0, 0})

	return
}

func NewBoat() INonPlayerEntity {
	return NewObject(ObjTypeIdBoat)
}

func NewMinecart() INonPlayerEntity {
	return NewObject(ObjTypeIdMinecart)
}

func NewStorageCart() INonPlayerEntity {
	return NewObject(ObjTypeIdStorageCart)
}

func NewPoweredCart() INonPlayerEntity {
	return NewObject(ObjTypeIdPoweredCart)
}

func NewActivatedTnt() INonPlayerEntity {
	return NewObject(ObjTypeIdActivatedTnt)
}

func NewArrow() INonPlayerEntity {
	return NewObject(ObjTypeIdArrow)
}

func NewThrownSnowball() INonPlayerEntity {
	return NewObject(ObjTypeIdThrownSnowball)
}

func NewThrownEgg() INonPlayerEntity {
	return NewObject(ObjTypeIdThrownEgg)
}

func NewFallingSand() INonPlayerEntity {
	return NewObject(ObjTypeIdFallingSand)
}

func NewFallingGravel() INonPlayerEntity {
	return NewObject(ObjTypeIdFallingGravel)
}

func NewFishingFloat() INonPlayerEntity {
	return NewObject(ObjTypeIdFishingFloat)
}

repository: jnwhiteh/chunkymonkey

repo_name: jnwhiteh/chunkymonkey


text:
# base recipe: meta/recipes-connectivity/libnss-mdns/libnss-mdns_0.10.bb
# base branch: warrior
# base commit: f6a00e069589fc53411d8f504805f5fc541531a1

SUMMARY = "Name Service Switch module for Multicast DNS (zeroconf) name resolution"
HOMEPAGE = "http://0pointer.de/lennart/projects/nss-mdns/"
SECTION = "libs"

LICENSE = "LGPLv2.1+"
LIC_FILES_CHKSUM = "file://LICENSE;md5=2d5025d4aa3495befef8f17206a5b0a1"

DEPENDS = "avahi libcheck"
PR = "r7"
PV = "0.14.1"

inherit autotools pkgconfig debian-package
require recipes-debian/sources/nss-mdns.inc

DEBIAN_PATCH_TYPE = 'quilt'
DEBIAN_UNPACK_DIR = "${WORKDIR}/nss-mdns-${PV}"

localstatedir = "/"

EXTRA_OECONF = "--libdir=${base_libdir}"

# suppress warning, but don't bother with autonamer
LEAD_SONAME = "libnss_mdns.so"
DEBIANNAME_${PN} = "libnss-mdns"

RDEPENDS_${PN} = "avahi-daemon"

pkg_postinst_${PN} () {
	sed '
		/^hosts:/ !b
		/\<mdns\(4\|6\)\?\(_minimal\)\?\>/ b
		s/\([[:blank:]]\+\)dns\>/\1mdns4_minimal [NOTFOUND=return] dns/g
		' -i $D${sysconfdir}/nsswitch.conf
}

pkg_prerm_${PN} () {
	sed '
		/^hosts:/ !b
		s/[[:blank:]]\+mdns\(4\|6\)\?\(_minimal\( \[NOTFOUND=return\]\)\?\)\?//g
		' -i $D${sysconfdir}/nsswitch.conf
}

repository: miraclelinux/meta-debian-extended

repo_name: miraclelinux/meta-debian-extended

branch_name: refs/heads/warrior


text:
package kube

import (
	"encoding/json"
	"fmt"
	"reflect"

	kapi "k8s.io/api/core/v1"
)

// Annotator represents the exported methods for handling node annotations
type Annotator interface {
	Set(key string, value interface{}) error
	SetWithFailureHandler(key string, value interface{}, failFn FailureHandlerFn) error
	Delete(key string)
	Run() error
}

// FailureHandlerFn is a function called when adding an annotation fails
type FailureHandlerFn func(obj interface{}, key string, val interface{})

type action struct {
	key     string
	val     string
	origVal interface{}
	failFn  FailureHandlerFn
}

type nodeAnnotator struct {
	kube Interface
	node *kapi.Node

	changes map[string]*action
}

// NewNodeAnnotator returns a new annotator for Node objects
func NewNodeAnnotator(kube Interface, node *kapi.Node) Annotator {
	return &nodeAnnotator{
		kube:    kube,
		node:    node,
		changes: make(map[string]*action),
	}
}

func (na *nodeAnnotator) Set(key string, val interface{}) error {
	return na.SetWithFailureHandler(key, val, nil)
}

func (na *nodeAnnotator) SetWithFailureHandler(key string, val interface{}, failFn FailureHandlerFn) error {
	act := &action{
		key:     key,
		origVal: val,
		failFn:  failFn,
	}
	if val != nil {
		// Annotations must be either a valid string value or nil; coerce
		// any non-empty values to string
		if reflect.TypeOf(val).Kind() == reflect.String {
			act.val = val.(string)
		} else {
			bytes, err := json.Marshal(val)
			if err != nil {
				return fmt.Errorf("failed to marshal %q value %v to string: %v", key, val, err)
			}
			act.val = string(bytes)
		}
	}
	na.changes[key] = act
	return nil
}

func (na *nodeAnnotator) Delete(key string) {
	na.changes[key] = &action{key: key}
}

func (na *nodeAnnotator) Run() error {
	annotations := make(map[string]interface{})
	for k, act := range na.changes {
		// Ignore annotations that already exist with the same value
		if existing, ok := na.node.Annotations[k]; existing != act.val || !ok {
			if act.origVal != nil {
				// Annotation should be updated to new value
				annotations[k] = act.val
			} else {
				// Annotation should be deleted
				annotations[k] = nil
			}
		}
	}
	if len(annotations) == 0 {
		return nil
	}

	err := na.kube.SetAnnotationsOnNode(na.node, annotations)
	if err != nil {
		// Let failure handlers clean up
		for _, act := range na.changes {
			if act.failFn != nil {
				act.failFn(na.node, act.key, act.origVal)
			}
		}
	}
	return err
}

// NewPodAnnotator returns a new annotator for Pod objects
func NewPodAnnotator(kube Interface, pod *kapi.Pod) Annotator {
	return &podAnnotator{
		kube:    kube,
		pod:     pod,
		changes: make(map[string]*action),
	}
}

type podAnnotator struct {
	kube Interface
	pod  *kapi.Pod

	changes map[string]*action
}

func (pa *podAnnotator) Set(key string, val interface{}) error {
	return pa.SetWithFailureHandler(key, val, nil)
}

func (pa *podAnnotator) SetWithFailureHandler(key string, val interface{}, failFn FailureHandlerFn) error {
	act := &action{
		key:     key,
		origVal: val,
		failFn:  failFn,
	}
	if val != nil {
		// Annotations must be either a valid string value or nil; coerce
		// any non-empty values to string
		if reflect.TypeOf(val).Kind() == reflect.String {
			act.val = val.(string)
		} else {
			bytes, err := json.Marshal(val)
			if err != nil {
				return fmt.Errorf("failed to marshal %q value %v to string: %v", key, val, err)
			}
			act.val = string(bytes)
		}
	}
	pa.changes[key] = act
	return nil
}

func (pa *podAnnotator) Delete(key string) {
	pa.changes[key] = &action{key: key}
}

func (pa *podAnnotator) Run() error {
	annotations := make(map[string]string)
	for k, act := range pa.changes {
		// Ignore annotations that already exist with the same value
		if existing, ok := pa.pod.Annotations[k]; existing != act.val || !ok {
			if act.origVal != nil {
				// Annotation should be updated to new value
				annotations[k] = act.val
			} else {
				// Annotation should be deleted
				annotations[k] = ""
			}
		}
	}
	if len(annotations) == 0 {
		return nil
	}

	err := pa.kube.SetAnnotationsOnPod(pa.pod, annotations)
	if err != nil {
		// Let failure handlers clean up
		for _, act := range pa.changes {
			if act.failFn != nil {
				act.failFn(pa.pod, act.key, act.origVal)
			}
		}
	}
	return err
}

// NewNamespaceAnnotator returns a new annotator for Namespace objects
func NewNamespaceAnnotator(kube Interface, namespace *kapi.Namespace) Annotator {
	return &namespaceAnnotator{
		kube:      kube,
		namespace: namespace,
		changes:   make(map[string]*action),
	}
}

type namespaceAnnotator struct {
	kube      Interface
	namespace *kapi.Namespace

	changes map[string]*action
}

func (na *namespaceAnnotator) Set(key string, val interface{}) error {
	return na.SetWithFailureHandler(key, val, nil)
}

func (na *namespaceAnnotator) SetWithFailureHandler(key string, val interface{}, failFn FailureHandlerFn) error {
	act := &action{
		key:     key,
		origVal: val,
		failFn:  failFn,
	}
	if val != nil {
		// Annotations must be either a valid string value or nil; coerce
		// any non-empty values to string
		if reflect.TypeOf(val).Kind() == reflect.String {
			act.val = val.(string)
		} else {
			bytes, err := json.Marshal(val)
			if err != nil {
				return fmt.Errorf("failed to marshal %q value %v to string: %v", key, val, err)
			}
			act.val = string(bytes)
		}
	}
	na.changes[key] = act
	return nil
}

func (na *namespaceAnnotator) Delete(key string) {
	na.changes[key] = &action{key: key}
}

func (na *namespaceAnnotator) Run() error {
	annotations := make(map[string]string)
	for k, act := range na.changes {
		// Ignore annotations that already exist with the same value
		if existing, ok := na.namespace.Annotations[k]; existing != act.val || !ok {
			if act.origVal != nil {
				// Annotation should be updated to new value
				annotations[k] = act.val
			} else {
				// Annotation should be deleted
				annotations[k] = ""
			}
		}
	}
	if len(annotations) == 0 {
		return nil
	}

	err := na.kube.SetAnnotationsOnNamespace(na.namespace, annotations)
	if err != nil {
		// Let failure handlers clean up
		for _, act := range na.changes {
			if act.failFn != nil {
				act.failFn(na.namespace, act.key, act.origVal)
			}
		}
	}
	return err
}

repository: dave-tucker/ovn-kubernetes

repo_name: dave-tucker/ovn-kubernetes

gha_language: Go


text:
% Encoding: UTF-8
@Article{,
  language = {english}
}

@Comment{jabref-meta: databaseType:bibtex;}

repository: JabRef/jabref

repo_name: JabRef/jabref

gha_language: Java


text:
package login

import (
	"github.com/jinzhu/gorm"
)

// LoginRepository ...
type LoginRepository struct {
	DB *gorm.DB
}

// NewLoginRepository ...
func NewLoginRepository(db *gorm.DB) LoginRepository {
	return LoginRepository{DB: db}
}

// FindAll ...
func (p *LoginRepository) FindAll() ([]Login, error) {
	logins := []Login{}
	err := p.DB.Find(&logins).Error
	return logins, err
}

// Search ...
func (p *LoginRepository) Search(keyword string) ([]Login, error) {
	logins := []Login{}
	err := p.DB.Where("url LIKE ? OR username LIKE ?", "%"+keyword+"%", "%"+keyword+"%").Find(&logins).Error
	return logins, err
}

// FindByID ...
func (p *LoginRepository) FindByID(id uint) (Login, error) {
	login := Login{}
	err := p.DB.Where(`id = ?`, id).First(&login).Error
	return login, err
}

// Save ...
func (p *LoginRepository) Save(login Login) (Login, error) {
	err := p.DB.Save(&login).Error
	return login, err
}

// Delete ...
func (p *LoginRepository) Delete(id uint) error {
	err := p.DB.Delete(&Login{ID: id}).Error
	return err
}

// Migrate ...
func (p *LoginRepository) Migrate() {
	err := p.DB.AutoMigrate(&Login{}).Error
	CheckErr(err)
}

// func (p *Repository) List(offset, limit int) ([]*Login, error) {
// 	var l []*Login
// 	err := p.DB.Offset(offset).Limit(limit).Find(&l).Error
// 	return l, err
// }

repository: mehmetka/passwall-api

repo_name: mehmetka/passwall-api


text:
package main

import (
	"log"

	"github.com/gocolly/colly/v2"
	"github.com/gocolly/colly/v2/queue"
	"github.com/gocolly/colly/v2/redisstorage"
)

func main() {
	urls := []string{
		"http://httpbin.org/",
		"http://httpbin.org/ip",
		"http://httpbin.org/cookies/set?a=b&c=d",
		"http://httpbin.org/cookies",
	}

	c := colly.NewCollector()

	// create the redis storage
	storage := &redisstorage.Storage{
		Address:  "127.0.0.1:6379",
		Password: "",
		DB:       0,
		Prefix:   "httpbin_test",
	}

	// add storage to the collector
	// 关键，配置后端持久化
	err := c.SetStorage(storage)
	if err != nil {
		panic(err)
	}

	// delete previous data from storage
	if err := storage.Clear(); err != nil {
		log.Fatal(err)
	}

	// close redis client
	defer storage.Client.Close()

	// create a new request queue with redis storage backend
	q, _ := queue.New(2, storage)

	c.OnResponse(func(r *colly.Response) {
		log.Println("Cookies:", c.Cookies(r.Request.URL.String()))
	})

	// add URLs to the queue
	for _, u := range urls {
		q.AddURL(u)
	}
	// consume requests
	q.Run(c)
}

repository: yifengyou/go-colly

repo_name: yifengyou/go-colly


text:
/*
Copyright 2017 The Kubernetes 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 cmd

import (
	"bytes"
	"strings"
	"testing"

	"github.com/jpbetz/auger/pkg/encoding"
)

const (
	dbFile            = "testdata/boltdb/db"
	dbWithHistoryFile = "testdata/boltdb/db-with-history"
)

func TestListKeys(t *testing.T) {
	out := new(bytes.Buffer)
	if err := printKeySummaries(dbFile, "", 0, []string{"key"}, out); err != nil {
		t.Fatal(err)
	}
	assertMatchesFile(t, out, "testdata/boltdb/keys.txt")
}

func TestListKeySummaries(t *testing.T) {
	out := new(bytes.Buffer)
	if err := printKeySummaries(dbWithHistoryFile, "", 0, []string{"key", "version-count", "value-size", "all-versions-value-size"}, out); err != nil {
		t.Fatal(err)
	}
	assertMatchesFile(t, out, "testdata/boltdb/keys-with-history.txt")
}

func TestListKeyVersions(t *testing.T) {
	out := new(bytes.Buffer)
	if err := printVersions(dbFile, "/registry/jobs/default/pi", out); err != nil {
		t.Fatal(err)
	}
	s := strings.Trim(out.String(), " \n")
	if s != "3" {
		t.Errorf("got %s, want 3", s)
	}
}

func TestExtractByKey(t *testing.T) {
	out := new(bytes.Buffer)
	if err := printValue(dbFile, "/registry/jobs/default/pi", "3", false, encoding.YamlMediaType, out); err != nil {
		t.Fatal(err)
	}
	assertMatchesFile(t, out, "testdata/yaml/job.yaml")
}

func TestExtractKeyFromLeaf(t *testing.T) {
	kv := readTestFileAsKv(t, "testdata/boltdb/page2item1.bin")
	out := new(bytes.Buffer)
	if err := printLeafItemKey(kv, out); err != nil {
		t.Fatal(err)
	}
	assertMatchesFile(t, out, "testdata/boltdb/page2item1-key.txt")
}

func TestExtractSummaryFromLeaf(t *testing.T) {
	kv := readTestFileAsKv(t, "testdata/boltdb/page2item1.bin")
	out := new(bytes.Buffer)
	if err := printLeafItemSummary(kv, out); err != nil {
		t.Fatal(err)
	}
	assertMatchesFile(t, out, "testdata/boltdb/page2item1-summary.txt")
}

// TODO: run a permutation grid of tests
func TestExtractValueFromLeaf(t *testing.T) {
	kv := readTestFileAsKv(t, "testdata/boltdb/page2item1.bin")
	out := new(bytes.Buffer)
	if err := printLeafItemValue(kv, encoding.YamlMediaType, out); err != nil {
		t.Fatal(err)
	}
	assertMatchesFile(t, out, "testdata/yaml/pod.yaml")
}

repository: jpbetz/auger

repo_name: jpbetz/auger


text:
// Copyright (C) 2021 Gridworkz Co., Ltd.
// KATO, Application Management Platform

// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package service

import (
	"errors"
	"fmt"
	"os"
	"sort"
	"strconv"
	"time"

	"github.com/gridworkz/kato/cmd/node/option"
	"github.com/gridworkz/kato/event"
	"github.com/gridworkz/kato/node/api/model"
	"github.com/gridworkz/kato/node/kubecache"
	"github.com/gridworkz/kato/node/masterserver/node"
	"github.com/gridworkz/kato/node/nodem/client"
	"github.com/gridworkz/kato/node/utils"
	"github.com/gridworkz/kato/util"
	ansibleUtil "github.com/gridworkz/kato/util/ansible"
	etcdutil "github.com/gridworkz/kato/util/etcd"
	licutil "github.com/gridworkz/kato/util/license"
	"github.com/sirupsen/logrus"
	"github.com/twinj/uuid"
)

//NodeService
type NodeService struct {
	c           *option.Conf
	nodecluster *node.Cluster
	kubecli     kubecache.KubeClient
}

//CreateNodeService
func CreateNodeService(c *option.Conf, nodecluster *node.Cluster, kubecli kubecache.KubeClient) *NodeService {
	etcdClientArgs := &etcdutil.ClientArgs{
		Endpoints:   c.EtcdEndpoints,
		CaFile:      c.EtcdCaFile,
		CertFile:    c.EtcdCertFile,
		KeyFile:     c.EtcdKeyFile,
		DialTimeout: c.EtcdDialTimeout,
	}
	if err := event.NewManager(event.EventConfig{
		EventLogServers: c.EventLogServer,
		DiscoverArgs:    etcdClientArgs,
	}); err != nil {
		logrus.Errorf("create event manager faliure")
	}
	return &NodeService{
		c:           c,
		nodecluster: nodecluster,
		kubecli:     kubecli,
	}
}

//AddNode
func (n *NodeService) AddNode(node *client.APIHostNode) (*client.HostNode, *utils.APIHandleError) {
	if n.nodecluster == nil {
		return nil, utils.CreateAPIHandleError(400, fmt.Errorf("this node can not support this api"))
	}

	nodes, err := n.GetAllNode()
	if err != nil {
		return nil, utils.CreateAPIHandleError(400, fmt.Errorf("error listing all nodes: %v", err))
	}
	if !licutil.VerifyNodes(n.c.LicPath, n.c.LicSoPath, len(nodes)) {
		return nil, utils.CreateAPIHandleError(400, fmt.Errorf("invalid license"))
	}

	if err := node.Role.Validation(); err != nil {
		return nil, utils.CreateAPIHandleError(400, err)
	}
	if node.ID == "" {
		node.ID = uuid.NewV4().String()
	}
	if node.InternalIP == "" {
		return nil, utils.CreateAPIHandleError(400, fmt.Errorf("node internal ip can not be empty"))
	}
	if node.RootPass != "" && node.Privatekey != "" {
		return nil, utils.CreateAPIHandleError(400, fmt.Errorf("options private-key and root-pass are conflicting"))
	}
	existNode := n.nodecluster.GetAllNode()
	for _, en := range existNode {
		if node.InternalIP == en.InternalIP {
			return nil, utils.CreateAPIHandleError(400, fmt.Errorf("node internal ip %s is exist", node.InternalIP))
		}
	}
	rbnode := node.Clone()
	rbnode.CreateTime = time.Now()
	n.nodecluster.UpdateNode(rbnode)
	return rbnode, nil
}

//InstallNode
func (n *NodeService) InstallNode(node *client.HostNode) *utils.APIHandleError {
	node.Status = client.Installing
	node.NodeStatus.Status = client.Installing
	node.Labels["event_id"] = util.NewUUID()
	n.nodecluster.UpdateNode(node)
	go n.AsynchronousInstall(node, node.Labels["event_id"])
	return nil
}

// check install scripts exists or not, if more than one master node has install scripts, choose one master node do it
func (n *NodeService) beforeInstall() (flag bool, err error) {
	// ansible file must exists
	// if ok, _ := util.FileExists("/opt/kato/kato-ansible/scripts/node.sh"); !ok {
	// 	// TODO Create tasks through etcd?
	// 	return false, nil
	// }

	// TODO If there is a task, lock it (etcd global lock) so that you can execute it. If the lock fails, it will not be executed.

	return true, nil
}

// write ansible hosts file
func (n *NodeService) writeHostsFile() error {
	hosts, err := n.GetAllNode()
	if err != nil {
		return err.Err
	}
	// use the value of environment if it is empty use default value
	hostsFilePath := os.Getenv("HOSTS_FILE_PATH")
	if hostsFilePath == "" {
		hostsFilePath = "/opt/kato/kato-ansible/inventory/hosts"
	}
	installConfPath := os.Getenv("INSTALL_CONF_PATH")
	if installConfPath == "" {
		installConfPath = "/opt/kato/kato-ansible/scripts/installer/global.sh"
	}
	erro := ansibleUtil.WriteHostsFile(hostsFilePath, installConfPath, hosts)
	if erro != nil {
		return err
	}
	return nil
}

//UpdateNodeStatus
func (n *NodeService) UpdateNodeStatus(nodeID, status string) *utils.APIHandleError {
	node := n.nodecluster.GetNode(nodeID)
	if node == nil {
		return utils.CreateAPIHandleError(400, errors.New("node can not be found"))
	}
	if status != client.Installing && status != client.InstallFailed && status != client.InstallSuccess {
		return utils.CreateAPIHandleError(400, fmt.Errorf("node can not set status is %s", status))
	}
	node.Status = status
	node.NodeStatus.Status = status
	n.nodecluster.UpdateNode(node)
	return nil
}

//AsynchronousInstall
func (n *NodeService) AsynchronousInstall(node *client.HostNode, eventID string) {
	// write ansible hosts file
	err := n.writeHostsFile()
	if err != nil {
		logrus.Error("write hosts file error ", err.Error())
		return
	}
	// start add node script
	logrus.Infof("Begin install node %s", node.ID)
	// write log to event log
	logger := event.GetManager().GetLogger(eventID)
	option := ansibleUtil.NodeInstallOption{
		HostRole:   node.Role.String(),
		HostName:   node.HostName,
		InternalIP: node.InternalIP,
		RootPass:   node.RootPass,
		KeyPath:    node.KeyPath,
		NodeID:     node.ID,
		Stdin:      nil,
		Stdout:     logger.GetWriter("node-install", "info"),
		Stderr:     logger.GetWriter("node-install", "err"),
	}

	err = ansibleUtil.RunNodeInstallCmd(option)
	if err != nil {
		logrus.Error("Error executing shell script : ", err)
		node.Status = client.InstallFailed
		node.NodeStatus.Status = client.InstallFailed
		n.nodecluster.UpdateNode(node)
		return
	}
	node.Status = client.InstallSuccess
	node.NodeStatus.Status = client.InstallSuccess
	n.nodecluster.UpdateNode(node)
	logrus.Infof("Install node %s successful", node.ID)
}

//DeleteNode
//only node status is offline and node can be deleted
func (n *NodeService) DeleteNode(nodeID string) *utils.APIHandleError {
	node := n.nodecluster.GetNode(nodeID)
	if node == nil {
		return utils.CreateAPIHandleError(404, fmt.Errorf("node is not found"))
	}
	if node.Status == "running" {
		return utils.CreateAPIHandleError(401, fmt.Errorf("node is running, you must closed node process in node %s", nodeID))
	}
	n.nodecluster.RemoveNode(node.ID)
	_, err := node.DeleteNode()
	if err != nil {
		return utils.CreateAPIHandleErrorFromDBError("delete node", err)
	}
	return nil
}

//GetNode info
func (n *NodeService) GetNode(nodeID string) (*client.HostNode, *utils.APIHandleError) {
	node := n.nodecluster.GetNode(nodeID)
	if node == nil {
		return nil, utils.CreateAPIHandleError(404, fmt.Errorf("node no found"))
	}
	return node, nil
}

//GetAllNode
func (n *NodeService) GetAllNode() ([]*client.HostNode, *utils.APIHandleError) {
	if n.nodecluster == nil {
		return nil, utils.CreateAPIHandleError(400, fmt.Errorf("this node can not support this api"))
	}
	nodes := n.nodecluster.GetAllNode()
	sort.Sort(client.NodeList(nodes))
	return nodes, nil
}

//GetServicesHealthy
func (n *NodeService) GetServicesHealthy() (map[string][]map[string]string, *utils.APIHandleError) {
	if n.nodecluster == nil {
		return nil, utils.CreateAPIHandleError(400, fmt.Errorf("this node can not support this api"))
	}
	StatusMap := make(map[string][]map[string]string, 30)
	nodes := n.nodecluster.GetAllNode()
	for _, n := range nodes {
		for _, v := range n.NodeStatus.Conditions {
			status, ok := StatusMap[string(v.Type)]
			if !ok {
				StatusMap[string(v.Type)] = []map[string]string{map[string]string{"type": string(v.Type), "status": string(v.Status), "message": string(v.Message), "hostname": n.HostName}}
			} else {
				list := status
				list = append(list, map[string]string{"type": string(v.Type), "status": string(v.Status), "message": string(v.Message), "hostname": n.HostName})
				StatusMap[string(v.Type)] = list
			}

		}
	}
	return StatusMap, nil
}

//CordonNode set node as unscheduler
func (n *NodeService) CordonNode(nodeID string, unschedulable bool) *utils.APIHandleError {
	hostNode, apierr := n.GetNode(nodeID)
	if apierr != nil {
		return apierr
	}
	if !hostNode.Role.HasRule(client.ComputeNode) {
		return utils.CreateAPIHandleError(400, fmt.Errorf("this node can not support this api"))
	}
	k8snode := hostNode.NodeStatus.KubeNode
	hostNode.Unschedulable = unschedulable
	//update k8s node unshcedulable status
	if k8snode != nil {
		node, err := n.kubecli.CordonOrUnCordon(hostNode.ID, unschedulable)
		if err != nil {
			return utils.CreateAPIHandleError(500, fmt.Errorf("set node schedulable info error,%s", err.Error()))
		}
		hostNode.UpdateK8sNodeStatus(*node)
	}
	n.nodecluster.UpdateNode(hostNode)
	return nil
}

// GetNodeLabels returns node labels, including system labels and custom labels
func (n *NodeService) GetNodeLabels(nodeID string) (*model.LabelsResp, *utils.APIHandleError) {
	node, err := n.GetNode(nodeID)
	if err != nil {
		return nil, err
	}
	labels := &model.LabelsResp{
		SysLabels:    node.Labels,
		CustomLabels: node.CustomLabels,
	}
	return labels, nil
}

//PutNodeLabel update node label
func (n *NodeService) PutNodeLabel(nodeID string, labels map[string]string) (map[string]string, *utils.APIHandleError) {
	hostNode, apierr := n.GetNode(nodeID)
	if apierr != nil {
		return nil, apierr
	}
	// api can only upate or create custom labels
	if hostNode.CustomLabels == nil {
		hostNode.CustomLabels = make(map[string]string)
	}
	for k, v := range labels {
		hostNode.CustomLabels[k] = v
	}
	if hostNode.Role.HasRule(client.ComputeNode) && hostNode.NodeStatus.KubeNode != nil {
		labels := hostNode.MergeLabels()
		node, err := n.kubecli.UpdateLabels(nodeID, labels)
		if err != nil {
			return nil, utils.CreateAPIHandleError(500, fmt.Errorf("update k8s node labels error,%s", err.Error()))
		}
		hostNode.UpdateK8sNodeStatus(*node)
	}
	n.nodecluster.UpdateNode(hostNode)
	return hostNode.CustomLabels, nil
}

//DeleteNodeLabel
func (n *NodeService) DeleteNodeLabel(nodeID string, labels map[string]string) (map[string]string, *utils.APIHandleError) {
	hostNode, apierr := n.GetNode(nodeID)
	if apierr != nil {
		return nil, apierr
	}

	newLabels := make(map[string]string)
	for k, v := range hostNode.CustomLabels {
		if _, ok := labels[k]; !ok {
			newLabels[k] = v
		}
	}
	hostNode.CustomLabels = newLabels
	if hostNode.Role.HasRule(client.ComputeNode) && hostNode.NodeStatus.KubeNode != nil {
		labels := hostNode.MergeLabels()
		node, err := n.kubecli.UpdateLabels(nodeID, labels)
		if err != nil {
			return nil, utils.CreateAPIHandleError(500, fmt.Errorf("update k8s node labels error,%s", err.Error()))
		}
		hostNode.UpdateK8sNodeStatus(*node)
	}
	n.nodecluster.UpdateNode(hostNode)
	return hostNode.CustomLabels, nil
}

//DownNode
func (n *NodeService) DownNode(nodeID string) (*client.HostNode, *utils.APIHandleError) {
	hostNode, apierr := n.GetNode(nodeID)
	if apierr != nil {
		return nil, apierr
	}
	// add the node from k8s if type is compute
	if hostNode.Role.HasRule(client.ComputeNode) && hostNode.NodeStatus.KubeNode != nil {
		err := n.kubecli.DownK8sNode(hostNode.ID)
		if err != nil {
			logrus.Error("Failed to down node: ", err)
			return nil, utils.CreateAPIHandleError(500, fmt.Errorf("k8s node down error,%s", err.Error()))
		}
	}
	hostNode.Status = client.Offline
	hostNode.NodeStatus.Status = client.Offline
	n.nodecluster.UpdateNode(hostNode)
	return hostNode, nil
}

//UpNode
func (n *NodeService) UpNode(nodeID string) (*client.HostNode, *utils.APIHandleError) {
	hostNode, apierr := n.GetNode(nodeID)
	if apierr != nil {
		return nil, apierr
	}
	hostNode.Unschedulable = false
	// add the node to k8s if type is compute
	if hostNode.Role.HasRule(client.ComputeNode) {
		if k8snode, _ := n.kubecli.GetNode(hostNode.ID); k8snode == nil {
			node, err := n.kubecli.UpK8sNode(hostNode)
			if err != nil {
				return nil, utils.CreateAPIHandleError(500, fmt.Errorf("k8s node up error,%s", err.Error()))
			}
			hostNode.UpdateK8sNodeStatus(*node)
		}
	}
	hostNode.Status = client.Running
	hostNode.NodeStatus.Status = client.Running
	n.nodecluster.UpdateNode(hostNode)
	return hostNode, nil
}

//GetNodeResource
func (n *NodeService) GetNodeResource(nodeUID string) (*model.NodePodResource, *utils.APIHandleError) {
	node, err := n.GetNode(nodeUID)
	if err != nil {
		return nil, err
	}
	if !node.Role.HasRule("compute") {
		return nil, utils.CreateAPIHandleError(401, fmt.Errorf("node is not compute node"))
	}
	ps, error := n.kubecli.GetPodsByNodes(nodeUID)
	if error != nil {
		return nil, utils.CreateAPIHandleError(404, err)
	}
	var cpuTotal = node.AvailableCPU
	var memTotal = node.AvailableMemory
	var cpuLimit int64
	var cpuRequest int64
	var memLimit int64
	var memRequest int64
	for _, v := range ps {
		for _, v := range v.Spec.Containers {
			lc := v.Resources.Limits.Cpu().MilliValue()
			cpuLimit += lc
		}
		for _, v := range v.Spec.Containers {
			lm := v.Resources.Limits.Memory().Value()
			memLimit += lm
		}
		for _, v := range v.Spec.Containers {
			rc := v.Resources.Requests.Cpu().MilliValue()
			cpuRequest += rc
		}
		for _, v := range v.Spec.Containers {
			rm := v.Resources.Requests.Memory().Value()
			memRequest += rm
		}
	}
	var res model.NodePodResource
	res.CPULimits = cpuLimit
	//logrus.Infof("node %s cpu limit is %v",cpuLimit)
	res.CPURequests = cpuRequest
	res.CPU = int(cpuTotal)
	res.MemR = int(memTotal / 1024 / 1024)
	res.CPULimitsR = strconv.FormatFloat(float64(res.CPULimits*100)/float64(res.CPU*1000), 'f', 2, 64)
	res.CPURequestsR = strconv.FormatFloat(float64(res.CPURequests*100)/float64(res.CPU*1000), 'f', 2, 64)
	res.MemoryLimits = memLimit / 1024 / 1024
	res.MemoryLimitsR = strconv.FormatFloat(float64(res.MemoryLimits*100)/float64(res.MemR), 'f', 2, 64)
	res.MemoryRequests = memRequest / 1024 / 1024
	res.MemoryRequestsR = strconv.FormatFloat(float64(res.MemoryRequests*100)/float64(res.MemR), 'f', 2, 64)
	return &res, nil
}

//CheckNode install status
func (n *NodeService) CheckNode(nodeUID string) (*model.InstallStatus, *utils.APIHandleError) {

	return nil, nil
}

//DeleteNodeCondition
func (n *NodeService) DeleteNodeCondition(nodeUID string, condition client.NodeConditionType) (*client.HostNode, *utils.APIHandleError) {
	node, err := n.GetNode(nodeUID)
	if err != nil {
		return nil, err
	}
	node.DeleteCondition(condition)
	n.nodecluster.UpdateNode(node)
	return node, nil
}

repository: sitedata/kato

repo_name: sitedata/kato


text:
vtk_module(vtkRenderingParallelLIC
  IMPLEMENTS
    vtkRenderingLIC
  DEPENDS
    vtkRenderingOpenGL
    vtkParallelMPI
    vtkIOLegacy
  KIT
    vtkParallel
  )

repository: ashray/VTK-EVM

repo_name: ashray/VTK-EVM

branch_name: refs/heads/yiq


text:
package boomer

import (
	"crypto/md5"
	"fmt"
	"io"
	"math"
	"os"
	"runtime/pprof"
	"strings"
	"time"

	"github.com/rs/zerolog/log"
	uuid "github.com/satori/go.uuid"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
	"github.com/shirou/gopsutil/process"
)

func round(val float64, roundOn float64, places int) (newVal float64) {
	var round float64
	pow := math.Pow(10, float64(places))
	digit := pow * val
	_, div := math.Modf(digit)
	if div >= roundOn {
		round = math.Ceil(digit)
	} else {
		round = math.Floor(digit)
	}
	newVal = round / pow
	return
}

// genMD5 returns the md5 hash of strings.
func genMD5(slice ...string) string {
	h := md5.New()
	for _, v := range slice {
		io.WriteString(h, v)
	}
	return fmt.Sprintf("%x", h.Sum(nil))
}

// startMemoryProfile starts memory profiling and save the results in file.
func startMemoryProfile(file string, duration time.Duration) (err error) {
	f, err := os.Create(file)
	if err != nil {
		return err
	}

	log.Info().Dur("duration", duration).Msg("Start memory profiling")
	time.AfterFunc(duration, func() {
		err := pprof.WriteHeapProfile(f)
		if err != nil {
			log.Error().Err(err).Msg("failed to write memory profile")
		}
		f.Close()
		log.Info().Dur("duration", duration).Msg("Stop memory profiling")
	})
	return nil
}

// startCPUProfile starts cpu profiling and save the results in file.
func startCPUProfile(file string, duration time.Duration) (err error) {
	f, err := os.Create(file)
	if err != nil {
		return err
	}

	log.Info().Dur("duration", duration).Msg("Start CPU profiling")
	err = pprof.StartCPUProfile(f)
	if err != nil {
		f.Close()
		return err
	}

	time.AfterFunc(duration, func() {
		pprof.StopCPUProfile()
		f.Close()
		log.Info().Dur("duration", duration).Msg("Stop CPU profiling")
	})
	return nil
}

// generate a random nodeID like locust does, using the same algorithm.
func getNodeID() (nodeID string) {
	hostname, _ := os.Hostname()
	id := strings.Replace(uuid.NewV4().String(), "-", "", -1)
	nodeID = fmt.Sprintf("%s_%s", hostname, id)
	return
}

// GetCurrentPidCPUUsage get current pid CPU usage
func GetCurrentPidCPUUsage() float64 {
	currentPid := os.Getpid()
	p, err := process.NewProcess(int32(currentPid))
	if err != nil {
		log.Error().Err(err).Msg(fmt.Sprintf("failed to get CPU percent\n"))
		return 0.0
	}
	percent, err := p.CPUPercent()
	if err != nil {
		log.Error().Err(err).Msg(fmt.Sprintf("failed to get CPU percent\n"))
		return 0.0
	}
	return percent
}

// GetCurrentPidCPUPercent get the percentage of current pid cpu used
func GetCurrentPidCPUPercent() float64 {
	currentPid := os.Getpid()
	p, err := process.NewProcess(int32(currentPid))
	if err != nil {
		log.Error().Err(err).Msg(fmt.Sprintf("failed to get CPU percent\n"))
		return 0.0
	}
	percent, err := p.Percent(time.Second)
	if err != nil {
		log.Error().Err(err).Msg(fmt.Sprintf("failed to get CPU percent\n"))
		return 0.0
	}
	return percent
}

// GetCurrentCPUPercent get the percentage of current cpu used
func GetCurrentCPUPercent() float64 {
	percent, _ := cpu.Percent(time.Second, false)
	return percent[0]
}

// GetCurrentMemoryPercent get the percentage of current memory used
func GetCurrentMemoryPercent() float64 {
	memInfo, _ := mem.VirtualMemory()
	return memInfo.UsedPercent
}

// GetCurrentPidMemoryUsage get current Memory usage
func GetCurrentPidMemoryUsage() float64 {
	currentPid := os.Getpid()
	p, err := process.NewProcess(int32(currentPid))
	if err != nil {
		log.Error().Err(err).Msg(fmt.Sprintf("failed to get CPU percent\n"))
		return 0.0
	}
	percent, err := p.MemoryPercent()
	if err != nil {
		log.Error().Err(err).Msg(fmt.Sprintf("failed to get CPU percent\n"))
		return 0.0
	}
	return float64(percent)
}


text:
DESCRIPTION = "Task to install headers and libraries related to addons into the SDK"
LICENSE = "MIT"
PR = "r2"

inherit packagegroup

PACKAGE_ARCH = "${MACHINE_ARCH}"

UTILS = ""

UTILS_append_omap3 = " canutils-dev"
UTILS_append_ti33x = " canutils-dev"

RDEPENDS_${PN} = "\
    ${UTILS} \
"


text:
SUMMARY = "Framework sample qt components over QTwayland"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COREBASE}/meta/files/common-licenses/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

inherit packagegroup features_check

REQUIRED_DISTRO_FEATURES = "wayland"

RDEPENDS:${PN} = "\
    packagegroup-framework-sample-qt    \
    \
    qtwayland                           \
    qtwayland-plugins                   \
    openstlinux-qt-wayland              \
    "

repository: STMicroelectronics/meta-st-openstlinux

repo_name: STMicroelectronics/meta-st-openstlinux

branch_name: refs/heads/kirkstone

gha_language: C


text:
package cachemanager

import (
	"context"
	"fmt"
	"sync"
	"time"

	"github.com/open-policy-agent/frameworks/constraint/pkg/types"
	"github.com/open-policy-agent/gatekeeper/v3/pkg/cachemanager/aggregator"
	"github.com/open-policy-agent/gatekeeper/v3/pkg/controller/config/process"
	"github.com/open-policy-agent/gatekeeper/v3/pkg/metrics"
	"github.com/open-policy-agent/gatekeeper/v3/pkg/readiness"
	"github.com/open-policy-agent/gatekeeper/v3/pkg/syncutil"
	"github.com/open-policy-agent/gatekeeper/v3/pkg/target"
	"github.com/open-policy-agent/gatekeeper/v3/pkg/watch"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/wait"
	"sigs.k8s.io/controller-runtime/pkg/client"
	logf "sigs.k8s.io/controller-runtime/pkg/log"
)

const RegistrarName = "cachemanager"

var (
	log     = logf.Log.WithName("cache-manager")
	backoff = wait.Backoff{
		Duration: time.Second,
		Factor:   2,
		Jitter:   0.1,
		Steps:    3,
	}
)

type Config struct {
	CfClient         CFDataClient
	SyncMetricsCache *syncutil.MetricsCache
	Tracker          *readiness.Tracker
	ProcessExcluder  *process.Excluder
	Registrar        *watch.Registrar
	GVKAggregator    *aggregator.GVKAgreggator
	Reader           client.Reader
}

type CacheManager struct {
	watchedSet            *watch.Set
	processExcluder       *process.Excluder
	gvksToSync            *aggregator.GVKAgreggator
	needToList            bool
	gvksToDeleteFromCache *watch.Set
	excluderChanged       bool
	// mu guards access to any of the fields above
	mu sync.RWMutex

	cfClient                   CFDataClient
	syncMetricsCache           *syncutil.MetricsCache
	tracker                    *readiness.Tracker
	registrar                  *watch.Registrar
	backgroundManagementTicker time.Ticker
	reader                     client.Reader
}

// CFDataClient is an interface for caching data.
type CFDataClient interface {
	AddData(ctx context.Context, data interface{}) (*types.Responses, error)
	RemoveData(ctx context.Context, data interface{}) (*types.Responses, error)
}

func NewCacheManager(config *Config) (*CacheManager, error) {
	if config.Registrar == nil {
		return nil, fmt.Errorf("registrar must be non-nil")
	}
	if config.ProcessExcluder == nil {
		return nil, fmt.Errorf("processExcluder must be non-nil")
	}
	if config.Tracker == nil {
		return nil, fmt.Errorf("tracker must be non-nil")
	}
	if config.Reader == nil {
		return nil, fmt.Errorf("reader must be non-nil")
	}

	if config.GVKAggregator == nil {
		config.GVKAggregator = aggregator.NewGVKAggregator()
	}

	cm := &CacheManager{
		cfClient:                   config.CfClient,
		syncMetricsCache:           config.SyncMetricsCache,
		tracker:                    config.Tracker,
		processExcluder:            config.ProcessExcluder,
		registrar:                  config.Registrar,
		watchedSet:                 watch.NewSet(),
		reader:                     config.Reader,
		gvksToSync:                 config.GVKAggregator,
		backgroundManagementTicker: *time.NewTicker(3 * time.Second),
		gvksToDeleteFromCache:      watch.NewSet(),
	}

	return cm, nil
}

func (c *CacheManager) Start(ctx context.Context) error {
	go c.manageCache(ctx)

	<-ctx.Done()
	return nil
}

// UpsertSource adjusts the watched set of gvks according to the newGVKs passed in
// for a given sourceKey. Callers are responsible for retrying on error.
func (c *CacheManager) UpsertSource(ctx context.Context, sourceKey aggregator.Key, newGVKs []schema.GroupVersionKind) error {
	c.mu.Lock()
	defer c.mu.Unlock()

	if len(newGVKs) > 0 {
		if err := c.gvksToSync.Upsert(sourceKey, newGVKs); err != nil {
			return fmt.Errorf("internal error adding source: %w", err)
		}
	} else {
		if err := c.gvksToSync.Remove(sourceKey); err != nil {
			return fmt.Errorf("internal error removing source: %w", err)
		}
	}

	// as a result of upserting the new gvks for the source key, some gvks
	// may become unreferenced and need to be deleted; this will be handled async
	// in the manageCache loop.

	if err := c.replaceWatchSet(ctx); err != nil {
		return fmt.Errorf("error watching new gvks: %w", err)
	}

	return nil
}

// replaceWatchSet looks at the gvksToSync and makes changes to the registrar's watch set.
// Assumes caller has lock. On error, actual watch state may not align with intended watch state.
func (c *CacheManager) replaceWatchSet(ctx context.Context) error {
	newWatchSet := watch.NewSet()
	newWatchSet.Add(c.gvksToSync.GVKs()...)

	diff := c.watchedSet.Difference(newWatchSet)
	c.removeStaleExpectations(diff)

	c.gvksToDeleteFromCache.AddSet(diff)

	var innerError error
	c.watchedSet.Replace(newWatchSet, func() {
		// *Note the following steps are not transactional with respect to admission control

		// Important: dynamic watches update must happen *after* updating our watchSet.
		// Otherwise, the sync controller will drop events for the newly watched kinds.
		innerError = c.registrar.ReplaceWatch(ctx, newWatchSet.Items())
	})

	return innerError
}

// removeStaleExpectations stops tracking data for any resources that are no longer watched.
func (c *CacheManager) removeStaleExpectations(stale *watch.Set) {
	for _, gvk := range stale.Items() {
		c.tracker.CancelData(gvk)
	}
}

// RemoveSource removes the watches of the GVKs for a given aggregator.Key. Callers are responsible for retrying on error.
func (c *CacheManager) RemoveSource(ctx context.Context, sourceKey aggregator.Key) error {
	c.mu.Lock()
	defer c.mu.Unlock()

	if err := c.gvksToSync.Remove(sourceKey); err != nil {
		return fmt.Errorf("internal error removing source: %w", err)
	}

	if err := c.replaceWatchSet(ctx); err != nil {
		return fmt.Errorf("error removing watches for source %v: %w", sourceKey, err)
	}

	return nil
}

// ExcludeProcesses swaps the current process excluder with the new *process.Excluder.
// It's a no-op if the two excluders are equal.
func (c *CacheManager) ExcludeProcesses(newExcluder *process.Excluder) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if c.processExcluder.Equals(newExcluder) {
		return
	}

	c.processExcluder.Replace(newExcluder)
	// there is a new excluder which means we need to schedule a wipe for any
	// previously watched GVKs to be re-added to get a chance to be evaluated
	// for this new process excluder.
	c.excluderChanged = true
}

// DoForEach runs fn for each GVK that is being watched by the cache manager.
// This is handy when we want to take actions while holding the lock on the watched.Set.
func (c *CacheManager) DoForEach(fn func(gvk schema.GroupVersionKind) error) error {
	c.mu.RLock()
	defer c.mu.RUnlock()

	err := c.watchedSet.DoForEach(fn)
	return err
}

func (c *CacheManager) watchesGVK(gvk schema.GroupVersionKind) bool {
	c.mu.RLock()
	defer c.mu.RUnlock()

	return c.watchedSet.Contains(gvk)
}

func (c *CacheManager) AddObject(ctx context.Context, instance *unstructured.Unstructured) error {
	gvk := instance.GroupVersionKind()

	isNamespaceExcluded, err := c.processExcluder.IsNamespaceExcluded(process.Sync, instance)
	if err != nil {
		return fmt.Errorf("error while excluding namespaces for gvk: %+v: %w", gvk, err)
	}

	if isNamespaceExcluded {
		c.tracker.ForData(instance.GroupVersionKind()).CancelExpect(instance)
		return nil
	}

	syncKey := syncutil.GetKeyForSyncMetrics(instance.GetNamespace(), instance.GetName())
	if c.watchesGVK(gvk) {
		_, err = c.cfClient.AddData(ctx, instance)
		if err != nil {
			c.syncMetricsCache.AddObject(
				syncKey,
				syncutil.Tags{
					Kind:   instance.GetKind(),
					Status: metrics.ErrorStatus,
				},
			)

			return err
		}

		c.syncMetricsCache.AddObject(syncKey, syncutil.Tags{
			Kind:   instance.GetKind(),
			Status: metrics.ActiveStatus,
		})
		c.syncMetricsCache.AddKind(instance.GetKind())
	}

	c.tracker.ForData(instance.GroupVersionKind()).Observe(instance)

	return nil
}

func (c *CacheManager) RemoveObject(ctx context.Context, instance *unstructured.Unstructured) error {
	if _, err := c.cfClient.RemoveData(ctx, instance); err != nil {
		return err
	}

	// only delete from metrics map if the data removal was successful
	c.syncMetricsCache.DeleteObject(syncutil.GetKeyForSyncMetrics(instance.GetNamespace(), instance.GetName()))
	c.tracker.ForData(instance.GroupVersionKind()).CancelExpect(instance)

	return nil
}

func (c *CacheManager) wipeData(ctx context.Context) error {
	if _, err := c.cfClient.RemoveData(ctx, target.WipeData()); err != nil {
		return err
	}

	// reset sync cache before sending the metric
	c.syncMetricsCache.ResetCache()
	c.syncMetricsCache.ReportSync()

	return nil
}

func (c *CacheManager) ReportSyncMetrics() {
	c.syncMetricsCache.ReportSync()
}

func (c *CacheManager) syncGVK(ctx context.Context, gvk schema.GroupVersionKind) error {
	u := &unstructured.UnstructuredList{}
	u.SetGroupVersionKind(schema.GroupVersionKind{
		Group:   gvk.Group,
		Version: gvk.Version,
		Kind:    gvk.Kind + "List",
	})

	var err error
	func() {
		c.mu.RLock()
		defer c.mu.RUnlock()

		// only call List if we are still watching the gvk.
		if c.watchedSet.Contains(gvk) {
			err = c.reader.List(ctx, u)
		}
	}()

	if err != nil {
		return fmt.Errorf("listing data for %+v: %w", gvk, err)
	}

	for i := range u.Items {
		if err := c.AddObject(ctx, &u.Items[i]); err != nil {
			return fmt.Errorf("adding data for %+v: %w", gvk, err)
		}
	}

	return nil
}

func (c *CacheManager) manageCache(ctx context.Context) {
	// relistStopChan is used to stop any list operations still in progress
	relistStopChan := make(chan struct{})

	for {
		select {
		case <-ctx.Done():
			return
		case <-c.backgroundManagementTicker.C:
			func() {
				c.mu.Lock()
				defer c.mu.Unlock()

				c.wipeCacheIfNeeded(ctx)

				if !c.needToList {
					// this means that there are no changes needed
					// such that any gvks need to be relisted.
					// any in flight goroutines can finish relisiting.
					return
				}

				// otherwise, spin up new goroutines to relist gvks as there has been a wipe

				// stop any goroutines that were relisting before
				// as we may no longer be interested in those gvks
				close(relistStopChan)

				// assume all gvks need to be relisted
				// and while under lock, make a copy of
				// all gvks so we can pass it in the goroutine
				// without needing to read lock this data
				gvksToRelist := c.gvksToSync.GVKs()

				// clean state
				c.needToList = false
				relistStopChan = make(chan struct{})

				go c.replayGVKs(ctx, gvksToRelist, relistStopChan)
			}()
		}
	}
}

func (c *CacheManager) replayGVKs(ctx context.Context, gvksToRelist []schema.GroupVersionKind, stopCh <-chan struct{}) {
	gvksSet := watch.NewSet()
	gvksSet.Add(gvksToRelist...)

	for gvksSet.Size() != 0 {
		gvkItems := gvksSet.Items()

		for _, gvk := range gvkItems {
			select {
			case <-ctx.Done():
				return
			case <-stopCh:
				return
			default:
				operation := func() (bool, error) {
					if err := c.syncGVK(ctx, gvk); err != nil {
						return false, err
					}
					return true, nil
				}

				if err := wait.ExponentialBackoff(backoff, operation); err != nil {
					log.Error(err, "internal: error listings gvk cache data", "gvk", gvk)
				} else {
					gvksSet.Remove(gvk)
				}
			}
		}

		c.ReportSyncMetrics()
	}
}

// wipeCacheIfNeeded performs a cache wipe if there are any gvks needing to be removed
// from the cache or if the excluder has changed. It also marks which gvks need to be
// re listed again in the cf data cache after the wipe. Assumes the caller has lock.
func (c *CacheManager) wipeCacheIfNeeded(ctx context.Context) {
	// remove any gvks not needing to be synced anymore
	// or re evaluate all if the excluder changed.
	if c.gvksToDeleteFromCache.Size() > 0 || c.excluderChanged {
		if err := c.wipeData(ctx); err != nil {
			log.Error(err, "internal: error wiping cache")
			return
		}

		c.gvksToDeleteFromCache = watch.NewSet()
		c.excluderChanged = false
		c.needToList = true
	}
}

repository: open-policy-agent/gatekeeper

repo_name: open-policy-agent/gatekeeper


text:
// Code generated by go-swagger; DO NOT EDIT.

// Copyright 2017-2020 Authors of Cilium
// SPDX-License-Identifier: Apache-2.0

package core_v1

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"net/http"

	"github.com/go-openapi/runtime"

	"github.com/cilium/kube-apate/api/k8s/v1/models"
)

// ReadCoreV1NamespacedResourceQuotaStatusOKCode is the HTTP code returned for type ReadCoreV1NamespacedResourceQuotaStatusOK
const ReadCoreV1NamespacedResourceQuotaStatusOKCode int = 200

/*ReadCoreV1NamespacedResourceQuotaStatusOK OK

swagger:response readCoreV1NamespacedResourceQuotaStatusOK
*/
type ReadCoreV1NamespacedResourceQuotaStatusOK struct {

	/*
	  In: Body
	*/
	Payload *models.IoK8sAPICoreV1ResourceQuota `json:"body,omitempty"`
}

// NewReadCoreV1NamespacedResourceQuotaStatusOK creates ReadCoreV1NamespacedResourceQuotaStatusOK with default headers values
func NewReadCoreV1NamespacedResourceQuotaStatusOK() *ReadCoreV1NamespacedResourceQuotaStatusOK {

	return &ReadCoreV1NamespacedResourceQuotaStatusOK{}
}

// WithPayload adds the payload to the read core v1 namespaced resource quota status o k response
func (o *ReadCoreV1NamespacedResourceQuotaStatusOK) WithPayload(payload *models.IoK8sAPICoreV1ResourceQuota) *ReadCoreV1NamespacedResourceQuotaStatusOK {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the read core v1 namespaced resource quota status o k response
func (o *ReadCoreV1NamespacedResourceQuotaStatusOK) SetPayload(payload *models.IoK8sAPICoreV1ResourceQuota) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *ReadCoreV1NamespacedResourceQuotaStatusOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(200)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

// ReadCoreV1NamespacedResourceQuotaStatusUnauthorizedCode is the HTTP code returned for type ReadCoreV1NamespacedResourceQuotaStatusUnauthorized
const ReadCoreV1NamespacedResourceQuotaStatusUnauthorizedCode int = 401

/*ReadCoreV1NamespacedResourceQuotaStatusUnauthorized Unauthorized

swagger:response readCoreV1NamespacedResourceQuotaStatusUnauthorized
*/
type ReadCoreV1NamespacedResourceQuotaStatusUnauthorized struct {
}

// NewReadCoreV1NamespacedResourceQuotaStatusUnauthorized creates ReadCoreV1NamespacedResourceQuotaStatusUnauthorized with default headers values
func NewReadCoreV1NamespacedResourceQuotaStatusUnauthorized() *ReadCoreV1NamespacedResourceQuotaStatusUnauthorized {

	return &ReadCoreV1NamespacedResourceQuotaStatusUnauthorized{}
}

// WriteResponse to the client
func (o *ReadCoreV1NamespacedResourceQuotaStatusUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses

	rw.WriteHeader(401)
}

repository: cilium/kube-apate

repo_name: cilium/kube-apate


text:
package config

import (
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"strings"
)

/*
  -h --help                     Show this screen
  -p PORT --port=PORT           Port [default: 8888]
  -s MAX_SIZE --size=MAX_SIZE   Max cache size, bytes [default: 1000000000]
  -a MAX_AGE --age=MAX_AGE      Max age of cached item, seconds. 0 = never expire. [default: 0]
  -b BUFFER_SIZE --statistics-buffer-size=BUFFER_SIZE  Number of entries to store in statistics
                                                       ring buffer. [default: 1000]
  -c PATH_TO_CERT --cert-file=PATH_TO_CERT   Path to PEM file containing private key and certificate for SSL
  -ca PATH_TO_CA --ca-file=PATH_TO_CA   Path to CA file, if provided client certificates will be checked against this ca
  -d --debug   Run in debug mode
  -ba <USER>:<PASSWORD> --basic-auth=<USER>:<PASSWORD>   Enable basic auth, requires that SSL is enabled.
*/

type Config struct {
	Size                 int    `mapstructure:"size"`
	Port                 int    `mapstructure:"port"`
	HTTPStatusPort       int    `mapstructure:"http-status-port"`
	Age                  int    `mapstructure:"age"`
	StatisticsBufferSize int    `mapstructure:"statistics-buffer-size"`
	ReadHeaderTimeout    int    `mapstructure:"read-header-timeout"`
	ReadTimeout          int    `mapstructure:"read-timeout"`
	WriteTimeout         int    `mapstructure:"write-timeout"`
	HttpPprof            bool   `mapstructure:"http-pprof"`
	RequestLog           bool   `mapstructure:"request-log"`
	UseSyslog            bool   `mapstructure:"use-syslog"`
	LogDestination       string `mapstructure:"log-destination"`
	CAFile               string `mapstructure:"ca-file"`
	CertFile             string `mapstructure:"cert-file"`
	KeyFile              string `mapstructure:"key-file"`
	BasicAuth            string `mapstructure:"basic-auth"`
}

func init() {
	viper.SetConfigName("qocache-conf")
	viper.AddConfigPath(".")
	viper.SetEnvPrefix("QOCACHE")
	viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
	viper.AutomaticEnv()
	addIntParameter("port", "p", "Port to bind to", 8888)
	addIntParameter("http-status-port", "t", "If set a non-TLS server will be started in addition to qocache which only serves /status, this can be used for health checks and similar", 0)
	addIntParameter("size", "s", "Max cache size in bytes", 1000000000)
	addIntParameter("age", "a", "Max age of cached item in seconds, 0 = never expire", 0)
	addIntParameter("statistics-buffer-size", "b", "Number of items to store in statistics ring buffer", 1000)
	addIntParameter("read-header-timeout", "h", "Timeout in seconds for reading HTTP request headers", 20)
	addIntParameter("read-timeout", "r", "Timeout in seconds for reading request body", 60)
	addIntParameter("write-timeout", "w", "Timeout in seconds for reading request body and writing response", 120)
	addBoolParameter("http-pprof", "If HTTP pprof endpoint should be enabled or not", false)
	addBoolParameter("request-log", "If HTTP request logging should be enabled or not", false)
	addBoolParameter("use-syslog", "If syslog should be used or not, default false => log to stderr (DEPRECATED, use --log-destination instead)", false)
	addStringParameter("log-destination", "Destination for logs, stderr/stdout/syslog (default stderr)", "stderr")
	addStringParameter("ca-file", "Path to CA certificate authority file, if passed in it will be used to verify client certificates", "")
	addStringParameter("cert-file", "Path to file containing certificate and optionally private key for server side TLS", "")
	addStringParameter("key-file", "Path to file containing private key for server side TLS, if not set the key is assumed to be present in cert-file", "")
}

func bindEnv(name string) {
	err := viper.BindEnv(name)
	if err != nil {
		panic(err)
	}
}

func addStringParameter(longName, usage, value string) {
	bindEnv(longName)
	pflag.String(longName, value, usage)
}

func addBoolParameter(longName, usage string, value bool) {
	bindEnv(longName)
	pflag.Bool(longName, value, usage)
}

func addIntParameter(longName, shortName, usage string, value int) {
	bindEnv(longName)
	pflag.IntP(longName, shortName, value, usage)
}

func GetConfig() (Config, error) {
	if err := viper.ReadInConfig(); err != nil {
		// Don't care if the config file is missing
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			return Config{}, err
		}
	}

	pflag.Parse()
	err := viper.BindPFlags(pflag.CommandLine)
	c := Config{}
	if err != nil {
		return c, err
	}

	err = viper.Unmarshal(&c)
	if c.KeyFile == "" {
		c.KeyFile = c.CertFile
	}

	return c, err
}

repository: thiruselvaa/qocache

repo_name: thiruselvaa/qocache


text:
cmake_minimum_required(VERSION 3.13.0)
# Global Variables
set(SEP "/")
set(PATH_SEP ":")
set(CONDA_PREFIX "")
set(CMAKE_PREFIX_PATH $ENV{CMAKE_PREFIX_PATH})

## Xilinx
set(XILINX_XRT $ENV{XILINX_XRT})
set(XILINX_VITIS $ENV{XILINX_VITIS})
set(XILINX_VIVADO $ENV{XILINX_VIVADO})
set(XCL_KERNEL $ENV{XCL_KERNEL})
set(XCL_EMULATION_MODE $ENV{XCL_EMULATION_MODE})

## CMake
set(CMAKE_SKIP_BUILD_RPATH FALSE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/lib ${XILINX_XRT}/lib)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

## C++
set(CMAKE_CXX_STANDARD 17)


text:
package gounion

import "testing"

func TestOneSet(t *testing.T) {
	uf := UnionFind{}
	for i := 0; i < 10; i++ {
		uf.Add()
	}
	for i := 9; i > 0; i-- {
		uf.Union(Item(i-1), Item(i))
	}
	if len(uf.GetAll()) != 1 {
		t.Error("Bad sets", uf.GetAll())
	}
}

func TestTwoSet(t *testing.T) {
	uf := UnionFind{}
	for i := 0; i < 10; i++ {
		uf.Add()
	}
	for i := 1; i < 5; i++ {
		uf.Union(Item(i-1), Item(i))
	}
	for i := 6; i < 10; i++ {
		uf.Union(Item(i-1), Item(i))
	}
	if len(uf.GetAll()) != 2 {
		t.Error("Bad sets", uf.GetAll())
	}
}

repository: drussel/gounion

repo_name: drussel/gounion


text:
package glib

// #cgo pkg-config: glib-2.0 gobject-2.0
// #include <glib.h>
// #include <glib-object.h>
// #include "glib.go.h"
import "C"
import "unsafe"

// SList is a representation of Glib's GSList.
type SList struct {
	list *C.struct__GSList
}

func WrapSList(obj uintptr) *SList {
	return wrapSList((*C.struct__GSList)(unsafe.Pointer(obj)))
}

func wrapSList(obj *C.struct__GSList) *SList {
	return &SList{obj}
}

func (v *SList) Native() uintptr {
	return uintptr(unsafe.Pointer(v.list))
}

func (v *SList) native() *C.struct__GSList {
	if v == nil || v.list == nil {
		return nil
	}
	return v.list
}

func (v *SList) Append(data uintptr) *SList {
	ret := C.g_slist_append(v.native(), C.gpointer(data))
	if ret == v.native() {
		return v
	} else {
		return wrapSList(ret)
	}
}

// GSList * 	g_slist_alloc ()
// GSList * 	g_slist_prepend ()
// GSList * 	g_slist_insert ()
// GSList * 	g_slist_insert_before ()
// GSList * 	g_slist_insert_sorted ()
// GSList * 	g_slist_remove ()
// GSList * 	g_slist_remove_link ()
// GSList * 	g_slist_delete_link ()
// GSList * 	g_slist_remove_all ()
// void 	g_slist_free ()
// void 	g_slist_free_full ()
// void 	g_slist_free_1 ()
// guint 	g_slist_length ()
// GSList * 	g_slist_copy ()
// GSList * 	g_slist_copy_deep ()
// GSList * 	g_slist_reverse ()
// GSList * 	g_slist_insert_sorted_with_data ()
// GSList * 	g_slist_sort ()
// GSList * 	g_slist_sort_with_data ()
// GSList * 	g_slist_concat ()
// void 	g_slist_foreach ()
// GSList * 	g_slist_last ()
// #define 	g_slist_next()
// GSList * 	g_slist_nth ()
// gpointer 	g_slist_nth_data ()
// GSList * 	g_slist_find ()
// GSList * 	g_slist_find_custom ()
// gint 	g_slist_position ()
// gint 	g_slist_index ()

license: ISC


text:
@article{amland2000risk,
  title={Risk-based testing:: Risk analysis fundamentals and metrics for software testing including a financial application case study},
  author={Amland, St{\aa}le},
  journal={Journal of Systems and Software},
  volume={53},
  number={3},
  pages={287--295},
  year={2000},
  publisher={Elsevier}
}


text:
@InProceedings{rakhlin11a,
  title = {Online Learning: Beyond Regret},
  author = {Alexander Rakhlin and Karthik Sridharan and Ambuj Tewari},
  pages = {559--594},
  abstract = {We study online learnability of a wide class of problems, extending the results of \cite{RakSriTew10} to general notions of performance measure well beyond external regret. Our framework simultaneously captures such well-known notions as internal and general $\Phi$-regret, learning with non-additive global cost functions, Blackwell's approachability, calibration of forecasters, and more. We show that learnability in all these situations is due to control of the same three quantities: a martingale convergence term, a term describing the ability to perform well if future is known, and  a generalization of sequential Rademacher complexity, studied in \cite{RakSriTew10}. Since we directly study complexity of the problem instead of focusing on efficient algorithms, we are able to improve and extend many known results which have been previously derived via an algorithmic construction.},
  pdf = {http://jmlr.org/proceedings/papers/v19/rakhlin11a/rakhlin11a.pdf},
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_language: TeX


text:
inherit deploy

DESCRIPTION = "ARM Trusted Firmware"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://license.rst;md5=1dd070c98a281d18d9eefd938729b031"

FILESEXTRAPATHS_append := "${THISDIR}/${PN}:"

SRC_URI = " \
        git://github.com/ARM-software/arm-trusted-firmware.git;nobranch=1 \
        file://0001-Fix-reset-issue-on-H6-by-using-R_WDOG.patch \
        "
SRCREV_sun50iw2 = "c390ecd6db5fadb054466a8d4168d9bbbff2fa95"
SRCREV_sun50iw6 = "c390ecd6db5fadb054466a8d4168d9bbbff2fa95"

S = "${WORKDIR}/git"
B = "${WORKDIR}/build"

COMPATIBLE_MACHINE = "(sun50iw2|sun50iw6)"

PLATFORM_sun50iw2 = "sun50i_a64"
PLATFORM_sun50iw6 = "sun50i_h6"

LDFLAGS[unexport] = "1"

do_compile() {
    oe_runmake -C ${S} BUILD_BASE=${B} \
      CROSS_COMPILE=${TARGET_PREFIX} \
      PLAT=${PLATFORM} \
      bl31 \
      all
}

do_deploy() {
    install -D -p -m 0644 ${B}/${PLATFORM}/release/bl31.bin ${DEPLOYDIR}/bl31.bin
}

addtask deploy after do_compile

repository: dimtass/meta-allwinner-hx

repo_name: dimtass/meta-allwinner-hx


text:
package main

import api "github.com/skyapps-id/K8s-Style-Configmap-and-Secret/api"

func main() {
	api.Run()
}


text:
// Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.

// Code generated; DO NOT EDIT.

package legalclientmodels

import (
	"github.com/go-openapi/errors"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// RetrievePolicyResponse Retrieve policy response
//
// swagger:model Retrieve policy response.
type RetrievePolicyResponse struct {

	// countrycode
	// Required: true
	CountryCode *string `json:"countryCode"`

	// countrygroupcode
	CountryGroupCode string `json:"countryGroupCode,omitempty"`

	// createdat
	// Format: date-time
	CreatedAt *strfmt.DateTime `json:"createdAt,omitempty"`

	// description
	Description string `json:"description,omitempty"`

	// id
	// Required: true
	ID *string `json:"id"`

	// isdefaultopted
	// Required: true
	IsDefaultOpted *bool `json:"isDefaultOpted"`

	// isdefaultselection
	// Required: true
	IsDefaultSelection *bool `json:"isDefaultSelection"`

	// ismandatory
	// Required: true
	IsMandatory *bool `json:"isMandatory"`

	// policyname
	// Required: true
	PolicyName *string `json:"policyName"`

	// policyversions
	PolicyVersions []*PolicyVersionObject `json:"policyVersions,omitempty"`

	// readableid
	ReadableID string `json:"readableId,omitempty"`

	// shouldnotifyonupdate
	// Required: true
	ShouldNotifyOnUpdate *bool `json:"shouldNotifyOnUpdate"`

	// updatedat
	// Format: date-time
	UpdatedAt *strfmt.DateTime `json:"updatedAt,omitempty"`
}

// Validate validates this Retrieve policy response
func (m *RetrievePolicyResponse) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateCountryCode(formats); err != nil {
		res = append(res, err)
	}
	if err := m.validateID(formats); err != nil {
		res = append(res, err)
	}
	if err := m.validateIsDefaultOpted(formats); err != nil {
		res = append(res, err)
	}
	if err := m.validateIsDefaultSelection(formats); err != nil {
		res = append(res, err)
	}
	if err := m.validateIsMandatory(formats); err != nil {
		res = append(res, err)
	}
	if err := m.validatePolicyName(formats); err != nil {
		res = append(res, err)
	}
	if err := m.validateShouldNotifyOnUpdate(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *RetrievePolicyResponse) validateCountryCode(formats strfmt.Registry) error {

	if err := validate.Required("countryCode", "body", m.CountryCode); err != nil {
		return err
	}

	return nil
}

func (m *RetrievePolicyResponse) validateID(formats strfmt.Registry) error {

	if err := validate.Required("id", "body", m.ID); err != nil {
		return err
	}

	return nil
}

func (m *RetrievePolicyResponse) validateIsDefaultOpted(formats strfmt.Registry) error {

	if err := validate.Required("isDefaultOpted", "body", m.IsDefaultOpted); err != nil {
		return err
	}

	return nil
}

func (m *RetrievePolicyResponse) validateIsDefaultSelection(formats strfmt.Registry) error {

	if err := validate.Required("isDefaultSelection", "body", m.IsDefaultSelection); err != nil {
		return err
	}

	return nil
}

func (m *RetrievePolicyResponse) validateIsMandatory(formats strfmt.Registry) error {

	if err := validate.Required("isMandatory", "body", m.IsMandatory); err != nil {
		return err
	}

	return nil
}

func (m *RetrievePolicyResponse) validatePolicyName(formats strfmt.Registry) error {

	if err := validate.Required("policyName", "body", m.PolicyName); err != nil {
		return err
	}

	return nil
}

func (m *RetrievePolicyResponse) validateShouldNotifyOnUpdate(formats strfmt.Registry) error {

	if err := validate.Required("shouldNotifyOnUpdate", "body", m.ShouldNotifyOnUpdate); err != nil {
		return err
	}

	return nil
}

// MarshalBinary interface implementation
func (m *RetrievePolicyResponse) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *RetrievePolicyResponse) UnmarshalBinary(b []byte) error {
	var res RetrievePolicyResponse
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

repository: AccelByte/accelbyte-go-sdk

repo_name: AccelByte/accelbyte-go-sdk


text:
@inproceedings{GJM22,
author={Golia, Priyanka and  Juba, Brendan and  Meel, Kuldeep S.},
title={A Scalable Shannon Entropy Estimator,
booktitle={Proceedings of International Conference on Computer-Aided Verification (CAV)},
month={8},
year={2022}
}

repository: meelgroup/meelgroup-website

repo_name: meelgroup/meelgroup-website