text:
DESCRIPTION = "Bacula filedaemon is the client to backup your device using Bacula a network based backup program"
SECTION = "console/network"
PRIORITY = "optional"
HOMEPAGE = "http://www.bacula.org"
LICENSE = "GPL"
PR ="r1"
DEPENDS = "gmp openssl zlib readline"

SRC_URI = "http://heanet.dl.sourceforge.net/sourceforge/bacula/bacula-1.38.11.tar.gz \
           file://findlib-attribs.patch \
           file://bacula-fd.init"

S = "${WORKDIR}/bacula-1.38.11"

# Makefile is broken using ccache
# No idea how to fix it so I turned ccache off
CCACHE = ""

inherit autotools update-rc.d

LDFLAGS += "-L${STAGING_LIBDIR}"
CFLAGS += "-L${STAGING_LIBDIR} -I${STAGING_INCDIR}"

INITSCRIPT_NAME = "bacula-fd"

do_configure() {
        oe_runconf --enable-client-only \
                   --prefix=/usr \
                   --with-working-dir=/var/lib/bacula  \
                   --with-fd-user=root \
                   --with-fd-group=bacula
}

do_compile() {
        oe_runmake CFLAGS="${CFLAGS}" LDFLAGS="${LDFLAGS}"
}

do_install() {
         mkdir -p ${D}/${sbindir}
         install -m 0754 ${S}/src/filed/bacula-fd ${D}/${sbindir}/

         mkdir -p ${D}/${sysconfdir}/bacula
         install ${S}/src/filed/bacula-fd.conf ${D}/${sysconfdir}/bacula/
}

# Add group
pkg_postinst() {
        grep -q bacula: /etc/group || addgroup bacula
}

do_install_append() {
         mkdir -p ${D}/${sysconfdir}/init.d
         install ${WORKDIR}/bacula-fd.init ${D}/${sysconfdir}/init.d/bacula-fd
}

SRC_URI[md5sum] = "0d6d6614afdc468d214de4e66f9f5a26"
SRC_URI[sha256sum] = "d095165d256771c918b80f836feaf837aedc1362b2d67171013d3ab7ac5ee47f"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty


text:
@article{ye2021recommending,
 author = {Ye, Xin and Zheng, Yongjie and Aljedaani, Wajdi and Mkaouer, Mohamed Wiem},
 journal = {Soft Computing},
 number = {7},
 pages = {5619--5632},
 publisher = {Springer Berlin Heidelberg},
 title = {Recommending pull request reviewers based on code changes},
 volume = {25},
 year = {2021}
}

license: MIT

license_type: permissive

branch_name: refs/heads/main

gha_license_id: MIT

gha_language: TeX

extension: bib


text:
DESCRIPTION = "LuneOS QML components"
LICENSE = "LGPL-2.1"
LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504"

PV = "0.4.2+git${SRCPV}"
SRCREV = "3978ad06c97377d72363b46e7c49410808e51d8b"

DEPENDS = "qtbase qtdeclarative qtlocation qtquickcontrols qtquickcontrols2 luna-service2 libwebos-application kf5bluezqt-mer qtdeclarative-native qtwebengine"

RRECOMMENDS_${PN} += "qtlocation"

SRC_URI = "${WEBOS_PORTS_GIT_REPO_COMPLETE}"
S = "${WORKDIR}/git"

inherit qmake5
inherit webos_ports_repo
inherit webos_filesystem_paths

PACKAGES += "${PN}-examples"
FILES_${PN} += " \
    ${OE_QMAKE_PATH_QML}/LuneOS/ \
    ${OE_QMAKE_PATH_QML}/QtQuick/Controls.2/LuneOS/ \
    ${OE_QMAKE_PATH_QML}/QtQuick/Controls/Styles/LuneOS/ \
    ${OE_QMAKE_PATH_QML}/LunaWebEngineViewStyle/ \
"
FILES_${PN}-examples += " \
    ${webos_applicationsdir}/org.luneos.components.gallery \
"

do_configure_prepend() {
    # Dynamically set the Qt and Chromium versions based on exported values in below files generated by QtWebEngine's bbappend
    QT_VERSION=`cat ${STAGING_DATADIR}/qtwebengine/qt-version.txt`
    CHROMIUM_VERSION=`cat ${STAGING_DATADIR}/qtwebengine/chromium-version.txt`

    sed -i "s|@QT_VERSION@|${QT_VERSION}|" ${S}/modules/LuneOS/Components/UserAgent.qml
    sed -i "s|@CHROMIUM_VERSION@|${CHROMIUM_VERSION}|" ${S}/modules/LuneOS/Components/UserAgent.qml
}

repository: jackwangdamao/meta-webos-ports

repo_name: jackwangdamao/meta-webos-ports

branch_name: refs/heads/master

extension: bb


text:
DESCRIPTION = "Startup notification support"
LICENSE = "LGPL"
SECTION = "libs"
PRIORITY = "optional"
MAINTAINER = "Phil Blundell <pb@handhelds.org>"
DEPENDS = "x11"

inherit autotools pkgconfig

SRC_URI = "http://www.freedesktop.org/software/startup-notification/releases/startup-notification-0.8.tar.gz"

do_stage () {
	autotools_stage_all
}

repository: BackupTheBerlios/openslug-svn

repo_name: BackupTheBerlios/openslug-svn


text:
package etcd

import (
	"github.com/garfieldlw/crontab-system/app/controller"
	format_api "github.com/garfieldlw/crontab-system/library/format/format-api"
	"github.com/garfieldlw/crontab-system/page/service/common"
	"github.com/garfieldlw/crontab-system/page/service/etcd"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Controller struct {
	*controller.BaseController
}

func (o *Controller) Keys(c *gin.Context) {
	var reqInfo common.ETCDKeysInputModel
	errReq := o.BindRequestJsonBody(c, &reqInfo)
	if errReq != nil {
		res, _ := format_api.ApiJsonWithError(format_api.ParameterError, errReq.Error(), "")
		c.JSON(http.StatusOK, res)
		return
	}

	result, err := etcd.GetKeys(c.Request.Context(), reqInfo.Client, reqInfo.Prefix, reqInfo.Key)
	if err != nil {
		res, _ := format_api.ApiJsonWithError(format_api.ServerError, err.Error(), "")
		c.JSON(http.StatusOK, res)
		return
	}

	res, _ := format_api.ApiJsonWithError(format_api.CodeSuccess, "", result)
	c.JSON(http.StatusOK, res)
	return
}

repository: garfieldlw/crontab-system

repo_name: garfieldlw/crontab-system

extension: go


text:
SUMMARY = "Hierarchical, reference counted memory pool system with destructors"
HOMEPAGE = "https://talloc.samba.org"
SECTION = "libs"
LICENSE = "LGPL-3.0-or-later & GPL-3.0-or-later"
LIC_FILES_CHKSUM = "file://talloc.h;beginline=3;endline=27;md5=a301712782cad6dd6d5228bfa7825249 \
                    file://pytalloc.h;beginline=1;endline=18;md5=21ab13bd853679d7d47a1739cb3b7db6 \
                    "

export PYTHONHASHSEED="1"

SRC_URI = "https://www.samba.org/ftp/talloc/talloc-${PV}.tar.gz \
           file://0001-talloc-Add-configure-options-for-packages.patch \
           file://0002-Fix-pyext_PATTERN-for-cross-compilation.patch \
"
SRC_URI[sha256sum] = "6df36862c42466ef88f360444513870ef46934f9016c84383cc4008a7d0c46ba"

inherit waf-samba

PACKAGECONFIG ??= "\
    ${@bb.utils.filter('DISTRO_FEATURES', 'acl', d)} \
    ${@bb.utils.contains('DISTRO_FEATURES', 'xattr', 'attr', '', d)} \
"
PACKAGECONFIG[acl] = "--with-acl,--without-acl,acl"
PACKAGECONFIG[attr] = "--with-attr,--without-attr,attr"
PACKAGECONFIG[libaio] = "--with-libaio,--without-libaio,libaio"
PACKAGECONFIG[libbsd] = "--with-libbsd,--without-libbsd,libbsd"
PACKAGECONFIG[libcap] = "--with-libcap,--without-libcap,libcap"
PACKAGECONFIG[valgrind] = "--with-valgrind,--without-valgrind,valgrind"

SRC_URI += "${@bb.utils.contains('PACKAGECONFIG', 'attr', '', 'file://avoid-attr-unless-wanted.patch', d)}"

S = "${WORKDIR}/talloc-${PV}"

#cross_compile cannot use preforked process, since fork process earlier than point subproces.popen
#to cross Popen
export WAF_NO_PREFORK="yes"

EXTRA_OECONF += "--disable-rpath \
                 --disable-rpath-install \
                 --bundled-libraries=NONE \
                 --builtin-libraries=replace \
                 --disable-silent-rules \
                 --with-libiconv=${STAGING_DIR_HOST}${prefix}\
                "

PACKAGES += "pytalloc pytalloc-dev"

RPROVIDES:${PN}-dbg += "pytalloc-dbg"

FILES:pytalloc = "${libdir}/python${PYTHON_BASEVERSION}/site-packages/* \
                  ${libdir}/libpytalloc-util.so.2 \
                  ${libdir}/libpytalloc-util.so.2.1.1 \
                 "
FILES:pytalloc-dev = "${libdir}/libpytalloc-util.so"
RDEPENDS:pytalloc = "python3"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_language: BitBake


text:
@Book{xie2015,
  title = {Dynamic Documents with {R} and knitr},
  author = {Yihui Xie},
  publisher = {Chapman and Hall/CRC},
  address = {Boca Raton, Florida},
  year = {2015},
  edition = {2nd},
  note = {ISBN 978-1498716963},
  url = {http://yihui.name/knitr/},
}

@Book{xie2015,
  title = {Research Methods for Everyday Life: Blending Qualitative and Quantitative Approaches},
  author = {Scott W. Vanderstoep, Deidre D. Johnston},
  publisher = {Jossey-Bass},
  address = {San Francisco, California},
  year = {2009},
  edition = {2nd},
}

repository: ap-research/handbook

repo_name: ap-research/handbook


text:
package main

import (
	"github.com/giansalex/pluralsight-transcripter/model"
	"github.com/giansalex/pluralsight-transcripter/repository"
	"github.com/giansalex/pluralsight-transcripter/service"
	"go.uber.org/dig"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

func newUserRepository(db *gorm.DB) repository.UserRepository {
	return repository.NewUserRepository(db)
}

func newCourseRepository(db *gorm.DB) repository.CourseRepository {
	return repository.NewCourseRepository(db)
}

func newTranscriptRepository(db *gorm.DB) repository.TranscriptRepository {
	return repository.NewTranscriptRepository(db)
}

func getCurrentUser(users repository.UserRepository) *model.User {
	return users.GetUser()
}

func newAPI(user *model.User) service.APIService {
	return service.NewAPI(apiURL, user.Jwt.String)
}

func useTranscriptService(transcript *service.DefaultTranscriptService) service.TranscriptService {
	return transcript
}

func buildContainer(dbPath string) *dig.Container {
	container := dig.New()

	container.Provide(func() (*gorm.DB, error) {
		return gorm.Open("sqlite3", dbPath)
	})
	container.Provide(newUserRepository)
	container.Provide(newCourseRepository)
	container.Provide(newTranscriptRepository)
	container.Provide(getCurrentUser)
	container.Provide(newAPI)
	container.Provide(service.NewTranscriptService)
	container.Provide(useTranscriptService)

	return container
}

repository: giansalex/pluralsight-transcripter

repo_name: giansalex/pluralsight-transcripter


text:
LICENSE     = "LiPS"
DESCRIPTION = "Voice call event history"
SECTION = "gpe"
PRIORITY    = "optional"
PR          = "r0"

DEPENDS = "gtk+ dbus-glib libgpewidget libgpephone libiac libchenabler"

inherit gpephone autotools

SRC_URI = "${GPEPHONE_MIRROR}/vochistory-${PV}/callhistory-${PV}.tar.bz2"
S = "${WORKDIR}/callhistory-${PV}"
SRC_URI[md5sum] = "1a3ef24580667be35667b7eefd0f4efe"
SRC_URI[sha256sum] = "1e321eb315eb8c60d5d8ae745d3b48cfe5cb388e73b71760440b590be58c74c7"

branch_name: HEAD


text:
/*
  GoLang code created by Jirawat Harnsiriwatanakit https://github.com/kazekim
*/

package thcerror

type Error interface {
	StatusCodeValue() string
	MessageTHValue() string
	MessageENValue() string
	Error() string
}

repository: kazekim/thaibankclient-go

repo_name: kazekim/thaibankclient-go


text:
if(NOT CMAKE_Go_COMPILER)
  set(Go_BIN_PATH
    $ENV{GOPATH}
    $ENV{GOROOT}
    $ENV{GOROOT}/../bin
    /usr/bin
    /usr/local/bin
    )
    find_program(CMAKE_Go_COMPILER
      NAMES go
      PATHS ${Go_BIN_PATH}
    )
endif()

mark_as_advanced(CMAKE_Go_COMPILER)

configure_file(${CMAKE_CURRENT_LIST_DIR}/CMakeGoCompiler.cmake.in ${CMAKE_PLATFORM_INFO_DIR}/CMakeGoCompiler.cmake @ONLY)

set(CMAKE_Go_COMPILER_ENV_VAR "GOCOMPILER")

repository: cyberroadie/sctp-examples

repo_name: cyberroadie/sctp-examples

extension: cmake


text:
// Copyright 2020 Saferwall. All rights reserved.
// Use of this source code is governed by Apache v2 license
// license that can be found in the LICENSE file.

package pe

import (
	"bytes"
	"encoding/binary"
	"errors"
	"log"
	"fmt"
)

const (
	maxExportedSymbols = 0x2000
)

// ImageExportDirectory represents the IMAGE_EXPORT_DIRECTORY structure.
// The export directory table contains address information that is used
// to resolve imports to the entry points within this image.
type ImageExportDirectory struct {
	Characteristics       uint32 // Reserved, must be 0.
	TimeDateStamp         uint32 // The time and date that the export data was created.
	MajorVersion          uint16 // The major version number. The major and minor version numbers can be set by the user.
	MinorVersion          uint16 // The minor version number.
	Name                  uint32 // The address of the ASCII string that contains the name of the DLL. This address is relative to the image base.
	Base                  uint32 // The starting ordinal number for exports in this image. This field specifies the starting ordinal number for the export address table. It is usually set to 1.
	NumberOfFunctions     uint32 // The number of entries in the export address table.
	NumberOfNames         uint32 // The number of entries in the name pointer table. This is also the number of entries in the ordinal table.
	AddressOfFunctions    uint32 //The address of the export address table, relative to the image base.
	AddressOfNames        uint32 // The address of the export name pointer table, relative to the image base. The table size is given by the Number of Name Pointers field.
	AddressOfNameOrdinals uint32 // The address of the ordinal table, relative to the image base.
}

// ExportFunction represents an imported function in the export table.
type ExportFunction struct {
	Ordinal      uint32
	FunctionRVA  uint32
	NameOrdinal  uint32
	NameRVA      uint32
	Name         string
	Forwarder    string
	ForwarderRVA uint32
}

func (pe *File) parseExportDirectory(rva, size uint32) error {

	// Define some vars.
	exportDir := ImageExportDirectory{}
	errorMsg := fmt.Sprintf("Error parsing export directory at RVA: 0x%x", rva)

	fileOffset := pe.getOffsetFromRva(rva)
	buf := bytes.NewReader(pe.data[fileOffset : fileOffset+size])
	err := binary.Read(buf, binary.LittleEndian, &exportDir)
	if err != nil {
		return errors.New(errorMsg)
	}

	// We keep track of the bytes left in the file and use it to set a upper
	// bound in the number of items that can be read from the different arrays.
	lengthUntilEOF := func(rva uint32) uint32 { return pe.size - pe.getOffsetFromRva(rva) }
	var length uint32
	var addressOfNames []byte

	if exportDir.NumberOfFunctions == 0 {
		log.Println("Export Directory counts zero number of functions")
		return nil
	}

	length = min(lengthUntilEOF(exportDir.AddressOfNames), exportDir.NumberOfNames*4)
	addressOfNames, err = pe.getData(exportDir.AddressOfNames, length)
	if err != nil {
		return errors.New(errorMsg)
	}

	length = min(lengthUntilEOF(exportDir.AddressOfNameOrdinals), exportDir.NumberOfNames*4)
	addressOfNameOrdinals, err := pe.getData(exportDir.AddressOfNameOrdinals, length)

	if err != nil {
		return errors.New(errorMsg)
	}

	length = min(lengthUntilEOF(exportDir.AddressOfFunctions), exportDir.NumberOfFunctions*4)
	addressOfFunctions, err := pe.getData(exportDir.AddressOfFunctions, length)
	if err != nil {
		return errors.New(errorMsg)
	}

	maxFailedEntries := 10
	var forwarderStr string
	var forwarderOffset uint32
	safetyBoundary := pe.size // overly generous upper bound
	symbolCounts := make(map[uint32]int)
	parsingFailed := false

	// read the image export directory
	section := pe.getSectionByRva(exportDir.AddressOfNames)
	if section != nil {
		safetyBoundary = (section.VirtualAddress + uint32(len(section.Data(0, 0, pe)))) - exportDir.AddressOfNames
	}

	numNames := min(exportDir.NumberOfNames, safetyBoundary/4)
	var symbolAddress uint32
	for i := uint32(0); i < numNames; i++ {

		defer func() {
			// recover from panic if one occured. Set err to nil otherwise.
			if recover() != nil {
				err = errors.New("array index out of bounds")
			}
		}()

		symbolOrdinal := binary.LittleEndian.Uint16(addressOfNameOrdinals[i*2:])
		if symbolOrdinal*4 < uint16(len(addressOfFunctions)) {
			symbolAddress = binary.LittleEndian.Uint32(addressOfFunctions[symbolOrdinal*4:])
		} else {
			return errors.New(`Corrupt? a bad pointer... we assume it's
			 all useless, no exports`)
		}

		if symbolAddress == 0 {
			continue
		}

		// If the function's RVA points within the export directory
		// it will point to a string with the forwarded symbol's string
		// instead of pointing the the function start address.
		if symbolAddress >= rva && symbolAddress < rva+size {
			forwarderStr = pe.getStringAtRVA(symbolAddress, 0x100000)
			forwarderOffset = pe.getOffsetFromRva(symbolAddress)
		} else {
			forwarderStr = ""
			fileOffset = 0
		}

		symbolNameAddress := binary.LittleEndian.Uint32(addressOfNames[i*4:])
		if symbolNameAddress == 0 {
			maxFailedEntries--
			if maxFailedEntries <= 0 {
				parsingFailed = true
				break
			}
		}
		symbolName := pe.getStringAtRVA(symbolNameAddress, 0x100000)
		if !IsValidFunctionName(symbolName) {
			parsingFailed = true
			break
		}

		symbolNameOffset := pe.getOffsetFromRva(symbolNameAddress)
		if symbolNameOffset == 0 {
			maxFailedEntries--
			if maxFailedEntries <= 0 {
				parsingFailed = true
				break
			}
		}

		// File 0b1d3d3664915577ab9a32188d29bbf3542b86c7b9ce333e245496c3018819f1
		// was being parsed as potentially containing millions of exports.
		// Checking for duplicates addresses the issue.
		symbolCounts[symbolAddress]++
		if symbolCounts[symbolAddress] > 0x200 {
			log.Printf(`Export directory contains more than 0x200 repeated
			 entries: %d, Name:%s, Address:0x%x`, symbolCounts[symbolAddress],
			 string(symbolName), symbolAddress)
			break
		}
		if len(symbolCounts) > maxExportedSymbols {
			log.Printf(`Export directory contains more than %d symbol entries.
			 Assuming corrupt.`, maxExportedSymbols)
			break
		}
		newExport := ExportFunction{
			Name:         symbolName,
			NameRVA:      symbolNameAddress,
			NameOrdinal:  uint32(symbolOrdinal),
			Ordinal:      exportDir.Base + uint32(symbolOrdinal),
			FunctionRVA:  symbolAddress,
			Forwarder:    forwarderStr,
			ForwarderRVA: forwarderOffset,
		}

		pe.Exports = append(pe.Exports, newExport)
	}

	if parsingFailed {
		log.Printf(`RVA AddressOfNames in the export directory points to an
		 invalid address: 0x%x`, exportDir.AddressOfNames)
	}

	maxFailedEntries = 10
	section = pe.getSectionByRva(exportDir.AddressOfFunctions)

	// Overly generous upper bound
	safetyBoundary = pe.size
	if section != nil {
		safetyBoundary = section.VirtualAddress +
		uint32(len(section.Data(0, 0, pe))) - exportDir.AddressOfNames
	}
	parsingFailed = false
	ordinals := make(map[uint32]bool)
	for _, exp := range pe.Exports {
		ordinals[exp.Ordinal] = true
	}
	numNames = min(exportDir.NumberOfFunctions, safetyBoundary/4)
	for i := uint32(0); i < numNames; i++ {
		value := i + exportDir.Base
		if ordinals[value] {
			continue
		}

		symbolAddress = binary.LittleEndian.Uint32(addressOfFunctions[i*4:])
		if symbolAddress == 0 {
			continue
		}

		// Checking for forwarder again.
		if symbolAddress >= rva && symbolAddress < rva+size {
			forwarderStr = pe.getStringAtRVA(symbolAddress, 0x100000)
			forwarderOffset = pe.getOffsetFromRva(symbolAddress)
		} else {
			forwarderStr = ""
			fileOffset = 0
		}

		// File 0b1d3d3664915577ab9a32188d29bbf3542b86c7b9ce333e245496c3018819f1
		// was being parsed as potentially containing millions of exports.
		// Checking for duplicates addresses the issue.
		symbolCounts[symbolAddress]++
		if symbolCounts[symbolAddress] > 0x200 {
			log.Printf(`Export directory contains more than 0x200 repeated
			 entries: %d, Address:0x%x`, symbolCounts[symbolAddress],
			 symbolAddress)
			break
		}
		if len(symbolCounts) > maxExportedSymbols {
			log.Printf(`Export directory contains more than %d ordinal entries.
			 Assuming corrupt.`, maxExportedSymbols)
			break
		}
		newExport := ExportFunction{
			Ordinal:      exportDir.Base + i,
			FunctionRVA:  symbolAddress,
			Forwarder:    forwarderStr,
			ForwarderRVA: forwarderOffset,
		}

		pe.Exports = append(pe.Exports, newExport)

	}

	return nil
}

repository: actuallyachraf/saferwall

repo_name: actuallyachraf/saferwall


text:
DESCRIPTION = "Minimal console-only initramfs image."

PACKAGE_INSTALL= "\
        base-files \
        base-passwd \
        busybox \
        sysvinit \
        initscripts \
        ${ROOTFS_BOOTSTRAP_INSTALL} \
"

IMAGE_LINGUAS = " "

LICENSE = "MIT"

IMAGE_FEATURES = ""

export IMAGE_BASENAME = "image-small-initramfs"

IMAGE_FSTYPES = "${INITRAMFS_FSTYPES} ${INITRAMFS_FSTYPES}.u-boot"
inherit image

IMAGE_ROOTFS_SIZE = "8192"


text:
package experimental2

import (
	"encoding/binary"
	"sort"

	v12 "go.opentelemetry.io/proto/otlp/trace/v1"

	otlptracecol "go.opentelemetry.io/proto/otlp/collector/trace/v1"

	"github.com/tigrannajaryan/exp-otelproto/core"
	otlptracecolexp "github.com/tigrannajaryan/exp-otelproto/encodings/experimental2/collector/trace/v1"
	otlpcommon "github.com/tigrannajaryan/exp-otelproto/encodings/experimental2/common/v1"
	otlpresource "github.com/tigrannajaryan/exp-otelproto/encodings/experimental2/resource/v1"
	otlptrace "github.com/tigrannajaryan/exp-otelproto/encodings/experimental2/trace/v1"

	v1 "go.opentelemetry.io/proto/otlp/common/v1"
)

type dictElem struct {
	ref   uint32
	count int
}
type dictType map[string]dictElem

type translatorPass int

const countStringsPass translatorPass = 1
const replacePass translatorPass = 2

type spanTranslator struct {
	pass       translatorPass
	stringDict dictType
	bytesDict  dictType
}

func NewSpanTranslator() *spanTranslator {
	return &spanTranslator{}
}

func (st *spanTranslator) FromOTLPSpans(batch *otlptracecol.ExportTraceServiceRequest) core.ExportRequest {

	res := &otlptracecolexp.ExportTraceServiceRequest{}
	st.stringDict = dictType{}
	st.bytesDict = dictType{}

	st.pass = countStringsPass
	for _, rssi := range batch.ResourceSpans {
		rsso := &otlptrace.ResourceSpans{
			Resource: &otlpresource.Resource{
				Attributes:             st.translateAttrs(rssi.Resource.Attributes),
				DroppedAttributesCount: rssi.Resource.DroppedAttributesCount,
			},
			ScopeSpans: st.translateInstrumentationLibrarySpans(rssi.ScopeSpans),
		}
		res.ResourceSpans = append(res.ResourceSpans, rsso)
	}

	res.StringDict = createStringDict(&st.stringDict)
	res.BytesDict = createBytesDict(&st.bytesDict)

	res = &otlptracecolexp.ExportTraceServiceRequest{}
	st.pass = replacePass
	for _, rssi := range batch.ResourceSpans {
		rsso := &otlptrace.ResourceSpans{
			Resource: &otlpresource.Resource{
				Attributes:             st.translateAttrs(rssi.Resource.Attributes),
				DroppedAttributesCount: rssi.Resource.DroppedAttributesCount,
			},
			ScopeSpans: st.translateInstrumentationLibrarySpans(rssi.ScopeSpans),
		}
		res.ResourceSpans = append(res.ResourceSpans, rsso)

	}

	return res
}

const firstDictRef = uint32(1)

func (st *spanTranslator) dictionizeStr(dict dictType, str *string, ref *uint32) bool {
	if len(*str) == 0 {
		return false
	}

	var idx dictElem
	var ok bool

	if st.pass == countStringsPass {
		if idx, ok = dict[*str]; !ok {
			idx.ref = uint32(len(dict) + 1)
			idx.count = 1
			dict[*str] = idx
		} else {
			idx.count++
			dict[*str] = idx
		}
		return false
	} else if st.pass == replacePass {
		if idx, ok = dict[*str]; !ok {
			return false
		}
		*str = ""
		*ref = idx.ref
		return true
	} else {
		return false
	}
}

func (st *spanTranslator) dictionizeBytes(dict dictType, str *[]byte, ref *uint32) bool {
	if len(*str) == 0 {
		return false
	}

	var idx dictElem
	var ok bool

	if st.pass == countStringsPass {
		if idx, ok = dict[string(*str)]; !ok {
			idx.ref = uint32(len(dict) + 1)
			idx.count = 1
			dict[string(*str)] = idx
		} else {
			idx.count++
			dict[string(*str)] = idx
		}
		return false
	} else if st.pass == replacePass {
		if idx, ok = dict[string(*str)]; !ok {
			return false
		}
		*str = nil
		*ref = idx.ref
		return true
	} else {
		return false
	}
}

func createDict(dict *dictType) {

	var freqs []struct {
		str   string
		count int
	}
	for k, v := range *dict {
		freqs = append(
			freqs, struct {
				str   string
				count int
			}{str: k, count: v.count},
		)
	}

	sort.SliceStable(
		freqs, func(i, j int) bool {
			return freqs[i].count > freqs[j].count
		},
	)
	*dict = dictType{}
	ref := firstDictRef
	for _, e := range freqs {

		buf := make([]byte, 10)
		n := binary.PutUvarint(buf, uint64(ref))
		if n > len(e.str) {
			// Not worth using ref since numeric encoding of the ref is larger than the string itself
			continue
		}
		(*dict)[e.str] = dictElem{
			ref:   ref,
			count: e.count,
		}
		ref++
	}
}

func createStringDict(dict *dictType) *otlpcommon.StringDict {
	createDict(dict)

	r := &otlpcommon.StringDict{
		StartIndex: firstDictRef,
		Values:     make([]string, len(*dict)),
	}
	for k, v := range *dict {
		r.Values[v.ref-firstDictRef] = k
	}

	return r
}

func createBytesDict(dict *dictType) *otlpcommon.BytesDict {
	createDict(dict)

	r := &otlpcommon.BytesDict{
		StartIndex: firstDictRef,
		Values:     make([][]byte, len(*dict)),
	}
	for k, v := range *dict {
		r.Values[v.ref-firstDictRef] = []byte(k)
	}

	return r
}

func (st *spanTranslator) translateAttrs(attrs []*v1.KeyValue) (r []*otlpcommon.KeyValue) {
	for _, attr := range attrs {
		var ref uint32
		var kv *otlpcommon.KeyValue
		if st.dictionizeStr(st.stringDict, &attr.Key, &ref) {
			kv = &otlpcommon.KeyValue{KeyRef: ref}
		} else {
			kv = &otlpcommon.KeyValue{Key: attr.Key}
		}

		var v *otlpcommon.AnyValue
		switch iv := attr.Value.Value.(type) {
		case *v1.AnyValue_StringValue:
			var ref uint32
			if st.dictionizeStr(st.stringDict, &iv.StringValue, &ref) {
				v = &otlpcommon.AnyValue{Value: &otlpcommon.AnyValue_StringRefValue{StringRefValue: ref}}
			} else {
				v = &otlpcommon.AnyValue{Value: &otlpcommon.AnyValue_StringValue{StringValue: iv.StringValue}}
			}

		case *v1.AnyValue_BoolValue:
			v = &otlpcommon.AnyValue{Value: &otlpcommon.AnyValue_BoolValue{BoolValue: iv.BoolValue}}
		case *v1.AnyValue_IntValue:
			v = &otlpcommon.AnyValue{Value: &otlpcommon.AnyValue_IntValue{IntValue: iv.IntValue}}
		case *v1.AnyValue_DoubleValue:
			v = &otlpcommon.AnyValue{Value: &otlpcommon.AnyValue_DoubleValue{DoubleValue: iv.DoubleValue}}
		default:
			panic("not implemented")
		}

		kv.Value = v

		r = append(r, kv)
	}
	return r
}

func (st *spanTranslator) translateInstrumentationLibrarySpans(
	in []*v12.ScopeSpans,
) (r []*otlptrace.ScopeSpans) {

	for _, ils := range in {
		out := &otlptrace.ScopeSpans{
			Scope: st.translateInstrumentationLibrary(ils.Scope),
		}

		for _, span := range ils.Spans {
			outSpan := st.translateSpan(span)
			out.Spans = append(out.Spans, outSpan)
		}

		r = append(r, out)
	}

	return r
}

func (st *spanTranslator) translateSpan(span *v12.Span) *otlptrace.Span {
	if span == nil {
		return nil
	}

	if span.Links != nil {
		panic("not implemented")
	}

	s := &otlptrace.Span{
		TraceId:                span.TraceId,
		SpanId:                 span.SpanId,
		TraceState:             span.TraceState,
		ParentSpanId:           span.ParentSpanId,
		Name:                   span.Name,
		Kind:                   otlptrace.Span_SpanKind(span.Kind),
		StartTimeUnixNano:      span.StartTimeUnixNano,
		EndTimeUnixNano:        span.EndTimeUnixNano,
		Attributes:             st.translateAttrs(span.Attributes),
		DroppedAttributesCount: span.DroppedAttributesCount,
		Events:                 st.translateEvents(span.Events),
		DroppedEventsCount:     span.DroppedEventsCount,
		Links:                  nil,
		DroppedLinksCount:      span.DroppedLinksCount,
		Status:                 st.translateStatus(span.Status),
	}
	st.dictionizeStr(st.stringDict, &s.Name, &s.NameRef)
	st.dictionizeBytes(st.bytesDict, &s.TraceId, &s.TraceIdRef)
	st.dictionizeBytes(st.bytesDict, &s.SpanId, &s.SpanIdRef)
	st.dictionizeBytes(st.bytesDict, &s.ParentSpanId, &s.ParentSpanIdRef)
	return s
}

func (st *spanTranslator) translateInstrumentationLibrary(in *v1.InstrumentationScope) *otlpcommon.InstrumentationScope {
	if in == nil {
		return nil
	}
	is := &otlpcommon.InstrumentationScope{
		Name:                   in.Name,
		Version:                in.Version,
		Attributes:             st.translateAttrs(in.Attributes),
		DroppedAttributesCount: in.DroppedAttributesCount,
	}
	st.dictionizeStr(st.stringDict, &is.Name, &is.NameRef)
	st.dictionizeStr(st.stringDict, &is.Version, &is.VersionRef)
	return is
}

func (st *spanTranslator) translateEvents(events []*v12.Span_Event) []*otlptrace.Span_Event {
	out := []*otlptrace.Span_Event{}
	for _, e := range events {
		out = append(out, st.translateEvent(e))
	}
	return out
}

func (st *spanTranslator) translateEvent(e *v12.Span_Event) *otlptrace.Span_Event {
	e1 := &otlptrace.Span_Event{
		TimeUnixNano:           e.TimeUnixNano,
		Name:                   e.Name,
		Attributes:             st.translateAttrs(e.Attributes),
		DroppedAttributesCount: e.DroppedAttributesCount,
	}
	st.dictionizeStr(st.stringDict, &e1.Name, &e1.NameRef)
	return e1
}

func (st *spanTranslator) translateStatus(status *v12.Status) *otlptrace.Status {
	return &otlptrace.Status{
		Message: status.Message,
		Code:    otlptrace.Status_StatusCode(status.Code),
	}
}

repository: tigrannajaryan/exp-otelproto

repo_name: tigrannajaryan/exp-otelproto

gha_language: Go


text:
DESCRIPTION = "Blueman is a GTK+ Bluetooth Manager"
LICENSE = "GPLv3"
LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504"

DEPENDS = "bluez5 python3-pygobject python3-cython-native python3-setuptools-native intltool-native"

inherit autotools systemd gsettings python3native gtk-icon-cache

SRC_URI = " \
    git://github.com/blueman-project/blueman.git \
    file://0001-Search-for-cython3.patch \
"
SRCREV = "c4a03417e81e21543d4568e8e7f7de307582eb50"
PV = "2.0.5+git${SRCPV}"
S = "${WORKDIR}/git"

EXTRA_OECONF = " \
    --disable-runtime-deps-check \
    --disable-schemas-compile \
"

SYSTEMD_SERVICE_${PN} = "${BPN}-mechanism.service"
SYSTEMD_AUTO_ENABLE_${PN} = "disable"

RRECOMENDS_${PN} += "adwaita-icon-theme"
RDEPENDS_${PN} += " \
    python3-dbus \
    packagegroup-tools-bluetooth \
"

PACKAGECONFIG[thunar] = "--enable-thunar-sendto,--disable-thunar-sendto,,thunar"

FILES_${PN} += " \
    ${datadir}/dbus-1 \
    ${datadir}/Thunar \
    ${systemd_user_unitdir} \
    ${exec_prefix}${systemd_system_unitdir} \
    ${PYTHON_SITEPACKAGES_DIR} \
"

FILES_${PN}-staticdev += "${PYTHON_SITEPACKAGES_DIR}/_blueman.a"

repository: eigendude/meta-openembedded

repo_name: eigendude/meta-openembedded

branch_name: refs/heads/warrior


text:
@inproceedings{DBLP:conf/coots/ColbyJJLP98,
 author = {Christopher Colby and
Lalita Jategaonkar Jagadeesan and
Radha Jagadeesan and
Konstantin Läufer and
Carlos Puchol},
 bibsource = {dblp computer science bibliography, https://dblp.org},
 biburl = {https://dblp.org/rec/conf/coots/ColbyJJLP98.bib},
 booktitle = {4th USENIX Conference on Object-Oriented Technologies and Systems
(COOTS), April 27-30, 1998, Eldorado Hotel, Santa Fe, New Mexico,
USA},
 pages = {131--149},
 publisher = {USENIX},
 timestamp = {Tue, 02 Feb 2021 00:00:00 +0100},
 title = {Objects and Concurrency in Triveni: A Telecommunication Case Study
in Java},
 url = {http://www.usenix.org/publications/library/proceedings/coots98/colby.html},
 year = {1998}
}


text:
@article{landau2021omniscape,
  title={Omniscape. jl: Software to compute omnidirectional landscape connectivity},
  author={Landau, Vincent A and Shah, Viral B and Anantharaman, Ranjan and Hall, Kimberly R},
  journal={Journal of Open Source Software},
  volume={6},
  number={57},
  pages={2829},
  year={2021}
}

gha_language: Julia


text:
DESCRIPTION = "Libraries and test programs for decoding mpeg-2 and mpeg-1 video streams"
HOMEPAGE = "http://libmpeg2.sourceforge.net/"
SECTION = "libs"
PRIORITY = "optional"
LICENSE = "GPL"
DEPENDS = "virtual/libsdl"
PR = "r4"

SRC_URI = "http://libmpeg2.sourceforge.net/files/mpeg2dec-${PV}.tar.gz"
S = "${WORKDIR}/mpeg2dec-0.4.0"

inherit autotools pkgconfig

EXTRA_OECONF = "--enable-shared"

mpeg2dec_include = "mpeg2.h mpeg2convert.h"

do_stage () {
	oe_libinstall -so -C libmpeg2/.libs libmpeg2 ${STAGING_LIBDIR}
	oe_libinstall -so -C libmpeg2/convert/.libs libmpeg2convert ${STAGING_LIBDIR}

	mkdir -p ${STAGING_INCDIR}/mpeg2dec/
	for i in ${mpeg2dec_include}; do
		install -m 0644 include/$i ${STAGING_INCDIR}/mpeg2dec/
	done
}

PACKAGES += "libmpeg2 libmpeg2-dev libmpeg2convert libmpeg2convert-dev"

FILES_${PN} = "${bindir}/*"
FILES_libmpeg2 = "${libdir}/libmpeg2.so.*"
FILES_libmpeg2convert = "${libdir}/libmpeg2convert.so.*"


text:
SUMMARY = "A small library to drive an OLED device"
DESCRIPTION = "\
A small library to drive an OLED device with either SSD1306 , SSD1309, SSD1322, \
SSD1325, SSD1327, SSD1331, SSD1351 or SH1106 chipset"
HOMEPAGE = "https://github.com/rm-hull/luma.oled"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENSE.rst;md5=5ec447eb69733e20a55838de7e8cb991"

inherit pypi setuptools3

SRC_URI[sha256sum] = "af97d79fa3481d2c48b7bccfb6de349219f6d814fdc9a3dd075c7b2c71206450"

CLEANBROKEN = "1"

PYPI_PACKAGE = "luma.oled"

RDEPENDS:${PN} += " \
	${PYTHON_PN}-luma-core \
"


text:
@article{CoLTaxonomy,
 author = {Species 2000  Secretariat},
 editor = {Y. Roskov and L. Abucay and T. Orrell and D. Nicolson and N. Bailly and P. M. Kirk and T. Bourgoin and R. E. DeWalt and W. Decock and A. De Wever and E. van Nieukerken and J. Zarucchi and L. Penev},
 issn = {ISSN 2405-8858},
 link = {http://www.catalogueoflife.org/col},
 month = {March},
 organization = {Species 2000 \& ITIS Catalogue of Life},
 publisher = {Species 2000: Naturalis, Leiden, the Netherlands},
 title = {Species 2000 & ITIS Catalogue of Life},
 year = {2017}
}

@article{GBIFTaxonomy,
 author = {GBIF Secretariat},
 doi = {10.15468/39omei},
 link = {http://www.gbif.org/dataset/d7dddbf4-2cf0-4f39-9b2a-bb099caae36c},
 month = {July},
 organization = {GBIF},
 title = {GBIF Backbone Taxonomy},
 year = {2016}
}

@article{HibbettEtAl2007,
 author = {David S. Hibbett and Manfred Binder and Joseph F. Bischoff and Meredith Blackwell and Paul F. Cannon and Ove E. Eriksson and Sabine Huhndorf and Timothy James and Paul M. Kirk and Robert Lücking and H. Thorsten Lumbsch and François Lutzoni and P. Brandon Matheny and David J. McLaughlin and Martha J. Powell and Scott Redhead and Conrad L. Schoch and Joseph W. Spatafora and Joost A. Stalpers and Rytas Vilgalys and M. Catherine Aime and André Aptroot and Robert Bauer and Dominik Begerow and Gerald L. Benny and Lisa A. Castlebury and Pedro W. Crous and Yu-Cheng Dai and Walter Gams and David M. Geiser and Gareth W. Griffith and Cécile Gueidan and David L. Hawksworth and Geir Hestmark and Kentaro Hosaka and Richard A. Humber and Kevin D. Hyde and Joseph E. Ironside and Urmas Kõljalg and Cletus P. Kurtzman and Karl-Henrik Larsson and Robert Lichtwardt and Joyce Longcore and Jolanta Miądlikowska and Andrew Miller and Jean-Marc Moncalvo and Sharon Mozley-Standridge and Franz Oberwinkler and Erast Parmasto and Valérie Reeb and Jack D. Rogers and Claude Roux and Leif Ryvarden and José Paulo Sampaio and Arthur Schüßler and Junta Sugiyama and R. Greg Thorn and Leif Tibell and Wendy A. Untereiner and Christopher Walker and Zheng Wang and Alex Weir and Michael Weiss and Merlin M. White and Katarina Winka and Yi-Jian Yao and Ning Zhang},
 doi = {https://doi.org/10.1016/j.mycres.2007.03.004},
 issn = {0953-7562},
 journal = {Mycological Research},
 link = {http://www.sciencedirect.com/science/article/pii/S0953756207000615},
 note = {http://figshare.com/articles/Fungal_Classification_2015/1465038},
 number = {5},
 pages = {509 - 547},
 title = {A higher-level phylogenetic classification of the Fungi},
 volume = {111},
 year = {2007}
}

@article{HinchliffEtAl2015,
 author = {Hinchliff, Cody E. and Smith, Stephen A. and Allman, James F. and Burleigh, J. Gordon and Chaudhary, Ruchi and Coghill, Lyndon M. and Crandall, Keith A. and Deng, Jiabin and Drew, Bryan T. and Gazis, Romina and Gude, Karl and Hibbett, David S. and Katz, Laura A. and Laughinghouse, H. Dail and McTavish, Emily Jane and Midford, Peter E. and Owen, Christopher L. and Ree, Richard H. and Rees, Jonathan A. and Soltis, Douglas E. and Williams, Tiffani and Cranston, Karen A.},
 doi = {10.1073/pnas.1423041112},
 eprint = {http://www.pnas.org/content/112/41/12764.full.pdf},
 journal = {Proceedings of the National Academy of Sciences},
 link = {http://www.pnas.org/content/112/41/12764.abstract},
 number = {41},
 pages = {12764-12769},
 title = {Synthesis of phylogeny and taxonomy into a comprehensive tree of life},
 volume = {112},
 year = {2015}
}

@article{IRMNGTaxonomy,
 author = {T. Rees (compiler)},
 link = {http://www.obis.org.au/irmng},
 title = {The Interim Register of Marine and Nonmarine Genera (IRMNG)},
 year = {2006}
}

@article{KirkIF,
 author = {Paul Kirk},
 journal = {(personal communication)},
 link = {http://www.indexfungorum.org/},
 month = {April},
 organization = {GBIF},
 title = {Index Fungorum},
 year = {2014}
}

@article{NCBITaxonomy,
 author = {US National Center on Biotechnology Information},
 link = {http://www.ncbi.nlm.nih.gov/Taxonomy/},
 title = {NCBI Taxonomy}
}

@article{QuastEtAl2013,
 author = {Quast, Christian and Pruesse, Elmar and Yilmaz, Pelin and Gerken, Jan and Schweer, Timmy and Yarza, Pablo and Peplies, Jörg and Glöckner, Frank Oliver},
 doi = {10.1093/nar/gks1219},
 eprint = {/oup/backfile/content_public/journal/nar/41/d1/10.1093/nar/gks1219/2/gks1219.pdf},
 journal = {Nucleic Acids Research},
 link = {+ http://dx.doi.org/10.1093/nar/gks1219},
 number = {D1},
 pages = {D590},
 title = {The SILVA ribosomal RNA gene database project: improved data processing and web-based tools},
 volume = {41},
 year = {2013}
}

@article{RedelingsH2017,
 author = {Redelings, Benjamin D. and Holder, Mark T.},
 doi = {10.7717/peerj.3058},
 issn = {2167-8359},
 journal = {PeerJ},
 keyword = {Supertree, Phylogenetics, Taxonomy, Software, Tree of life},
 link = {https://doi.org/10.7717/peerj.3058},
 month = {mar},
 pages = {e3058},
 title = {A supertree pipeline for summarizing phylogenetic and taxonomic information for millions of species},
 volume = {5},
 year = {2017}
}

@article{ReesC2017,
 author = {Jonathan Rees and Karen Cranston},
 doi = {10.3897/BDJ.5.e12581},
 eprint = {https://doi.org/10.3897/BDJ.5.e12581},
 issn = {1314-2836},
 journal = {Biodiversity Data Journal},
 link = {https://doi.org/10.3897/BDJ.5.e12581},
 pages = {e12581},
 publisher = {Pensoft Publishers},
 title = {Automated assembly of a reference taxonomy for phylogenetic data synthesis},
 volume = {5},
 year = {2017}
}

@article{SchaferhoffEtAt2010,
 author = {Sch{\"a}ferhoff, Bastian
and Fleischmann, Andreas
and Fischer, Eberhard
and Albach, Dirk C.
and Borsch, Thomas
and Heubl, G{\"u}nther
and M{\"u}ller, Kai F.},
 doi = {10.1186/1471-2148-10-352},
 issn = {1471-2148},
 journal = {BMC Evolutionary Biology},
 link = {http://dx.doi.org/10.1186/1471-2148-10-352},
 number = {1},
 pages = {352},
 title = {Towards resolving Lamiales relationships: insights from rapidly evolving chloroplast sequences},
 volume = {10},
 year = {2010}
}

@article{ThePlantList,
 author = {Editors of the Plant List, link = {http://www.theplantlist.org/}, title = {The Plant List {(2013).} Version 1.1},
 year = {2013}
}

@article{WoRMSTaxonomy,
 author = {{WoRMS} Editorial Board},
 doi = {10.14284/170},
 link = {http://www.marinespecies.org/aphia.php},
 title = {WoRMS: World Registry of Marine Species}
}

repository: mtholder/OTifacts

repo_name: mtholder/OTifacts


text:
% Encoding: UTF-8

@Misc{sp20-516-252-IBM-cloud,
      author={{Margaret Rouse}},
      title={IBM Cloud},
      url={https://searchcloudcomputing.techtarget.com/definition/IBM-Bluemix/},
      howpublished={Web Page},
      month=May,
      year= {2017}
    }

@Misc{sp20-516-252-Enterprise-ready-AI,
      organization={{IBM}},
      title={Enterprise-ready-{A}{I}},
      url={https://www.ibm.com/watson/about/},
      howpublished={Web Page},
      month=May,
      year= {2017}
    }

@Misc{sp20-516-252-machine-learning,
      organization={{IBM}},
      title={machine-learning},
      url={https://www.ibm.com/cloud/machine-learning/},
      howpublished={Web Page},
      month=May,
      year = {2017}
    }

@Misc{sp20-516-230-kubernetes,
      organization={IBM},
      title={Kubernetes},
      url={https://www.ibm.com/cloud/learn/kubernetes},
      howpublished={Web Page},
      month=mar,
      year = {2020}
    }

@Misc{sp20-516-230-IBM-cloud-products,
      organization={IBM},
      title={IBM Cloud Products},
      url={https://www.ibm.com/cloud/products},
      howpublished={Web Page},
      month=mar,
      year = {2020}
    }


text:
require mingw-runtime.inc

PR = "r1"

SRC_URI = "${SOURCEFORGE_MIRROR}/mingw/mingwrt-${PV}-mingw32-src.tar.gz"

S = "${WORKDIR}/mingwrt-${PV}-mingw32"

SRC_URI[md5sum] = "0411b98fd5eeac0706e2abb7122526bb"
SRC_URI[sha256sum] = "4f4d19f3e15fdf00957932211be609b6bf4e689ad5938ce7bff666a638bde0e7"


text:
Automatically generated by Mendeley Desktop 1.14.1-dev1
Any changes to this file will be lost if it is regenerated by Mendeley.

BibTeX export options can be customized via Preferences -> BibTeX in Mendeley Desktop

@article{Everett1985a,
abstract = {This is the final report on the performance of 8 low-energy, passive solar houses at Great Linford, Milton Keynes, monitored by the Open University Energy Research Group (ERG), for the Milton Keynes Development Corporation (MKDC), under contract to the Energy Technology Support Unit (ETSU) at Harwell.

[The smaller file contains the Executive Summary; the larger file contains the main report, excluding the Executive Summary].},
annote = {Page 163 has wind stuff on it},
author = {Everett, R. and Horton, a. and Doggart, J.},
file = {:Users/jonathanchambers/Documents/Papers/1985/Everett, Horton, Doggart/1985 - Everett, Horton, Doggart - Linford Low Energy Houses.pdf:pdf},
title = {{Linford Low Energy Houses}},
url = {http://oro.open.ac.uk/19861/},
year = {1985}
}

repository: apcshields/autocomplete-bibtex

repo_name: apcshields/autocomplete-bibtex


text:
package main

import (
	"fmt"
	log "github.com/Sirupsen/logrus"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
)

const (
	sysfsFpgaClassPath = "/sys/class/fpga"
	osdevPath          = "/dev"
	portDeviceFmt      = "intel-fpga-port.%d"
)

type pciBdf struct {
	bus      int
	device   int
	function int
}

func (bdf *pciBdf) label() string {
	return fmt.Sprintf("%02d:%02d.%d", bdf.bus, bdf.device, bdf.function)
}

type intelPort struct {
	instanceId int
	name       string
	bdf        pciBdf
}

type intelPorts struct {
	portList []intelPort
}

func busdevfnFromSymlink(linkname string) pciBdf {
	symlink, err := filepath.EvalSymlinks(linkname)
	if err == nil {
		r := regexp.MustCompile("[^/:.]+")
		items := r.FindAllString(symlink, -1)
		bus, _ := strconv.Atoi(items[len(items)-3])
		device, _ := strconv.Atoi(items[len(items)-2])
		function, _ := strconv.Atoi(items[len(items)-1])
		return pciBdf{bus, device, function}
	}

	log.Errorf("Failed to get busdevfn from " + linkname)
	return pciBdf{}
}

func (ires *intelPorts) enumerate() {
	var bdf pciBdf

	ires.portList = []intelPort{}
	entries, err := ioutil.ReadDir(sysfsFpgaClassPath)
	if err != nil {
		log.Errorf("[IntelPorts] Failed to read directory content from " + sysfsFpgaClassPath + ": " + err.Error())
		return
	}

	for _, f := range entries {
		// Get instance ID from entry name "intel-fpga-dev.<instance id>"
		substrs := strings.Split(f.Name(), ".")
		instanceId, _ := strconv.Atoi(substrs[len(substrs)-1])

		syspath := filepath.Join(sysfsFpgaClassPath, f.Name())
		portname := fmt.Sprintf(portDeviceFmt, instanceId)
		if _, err := os.Stat(filepath.Join(syspath, portname)); err == nil {
			// Get bdf (bus, device, function) from symlink "device -> ../../../0000:06:00.0"
			bdf = busdevfnFromSymlink(filepath.Join(syspath, "device"))
			// Add intel port to list
			port := intelPort{name: portname, instanceId: instanceId, bdf: bdf}
			ires.portList = append(ires.portList, port)
			log.Infof("[IntelPorts] new AFU PORT: name %s, instance %d, bdf %s", port.name, port.instanceId, port.bdf.label())
		}
	}

	log.Infof("[IntelPorts] Nb AFU ports %d", len(ires.portList))
	return
}


text:
@inproceedings{DBLP:conf/propor/RealFO20,
  author    = {Livy Real and
               Erick Fonseca and
               Hugo Gon{\c{c}}alo Oliveira},
  editor    = {Paulo Quaresma and
               Renata Vieira and
               Sandra M. Alu{\'{\i}}sio and
               Helena Moniz and
               Fernando Batista and
               Teresa Gon{\c{c}}alves},
  title     = {The {ASSIN} 2 Shared Task: {A} Quick Overview},
  booktitle = {Computational Processing of the Portuguese Language - 14th International
               Conference, {PROPOR} 2020, Evora, Portugal, March 2-4, 2020, Proceedings},
  series    = {Lecture Notes in Computer Science},
  volume    = {12037},
  pages     = {406--412},
  publisher = {Springer},
  year      = {2020},
  url       = {https://doi.org/10.1007/978-3-030-41505-1_39},
  doi       = {10.1007/978-3-030-41505-1_39},
  timestamp = {Tue, 03 Mar 2020 09:40:18 +0100},
  biburl    = {https://dblp.org/rec/conf/propor/RealFO20.bib},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}

repository: tensorflow/datasets

repo_name: tensorflow/datasets

gha_language: Python


text:
//go:build !arm64

package nodeps

// MariaDBDefaultVersion is the default MariaDB version
const MariaDBDefaultVersion = MariaDB103

// ValidMariaDBVersions is the versions of MariaDB that are valid
var ValidMariaDBVersions = map[string]bool{
	MariaDB55:  true,
	MariaDB100: true,
	MariaDB101: true,
	MariaDB102: true,
	MariaDB103: true,
	MariaDB104: true,
	MariaDB105: true,
	MariaDB106: true,
}

// MariaDB Versions
const (
	MariaDB55  = "5.5"
	MariaDB100 = "10.0"
	MariaDB101 = "10.1"
	MariaDB102 = "10.2"
	MariaDB103 = "10.3"
	MariaDB104 = "10.4"
	MariaDB105 = "10.5"
	MariaDB106 = "10.6"
)

repository: mglaman/ddev

repo_name: mglaman/ddev


text:
/*
 * Copyright 2020 Dgraph Labs, Inc. and Contributors
 *
 * 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 z

import (
	"fmt"
	"math/rand"
	"sync"
	"sync/atomic"
	"time"
	"unsafe"

	"github.com/dustin/go-humanize"
)

// Allocator amortizes the cost of small allocations by allocating memory in bigger chunks.
// Internally it uses z.Calloc to allocate memory. Once allocated, the memory is not moved,
// so it is safe to use the allocated bytes to unsafe cast them to Go struct pointers.
type Allocator struct {
	pageSize int
	curBuf   int
	curIdx   int
	buffers  [][]byte
	size     uint64
	Ref      uint64
	Tag      string
}

// allocs keeps references to all Allocators, so we can safely discard them later.
var allocsMu *sync.Mutex
var allocRef uint64
var allocs map[uint64]*Allocator

func init() {
	allocsMu = new(sync.Mutex)
	allocs = make(map[uint64]*Allocator)

	// Set up a unique Ref per process.
	rand.Seed(time.Now().UnixNano())
	allocRef = uint64(rand.Int63n(1<<16)) << 48
	fmt.Printf("Using z.Allocator with starting ref: %x\n", allocRef)
}

// NewAllocator creates an allocator starting with the given size.
func NewAllocator(sz int) *Allocator {
	ref := atomic.AddUint64(&allocRef, 1)
	a := &Allocator{
		pageSize: sz,
		Ref:      ref,
	}

	allocsMu.Lock()
	allocs[ref] = a
	allocsMu.Unlock()
	return a
}

func PrintAllocators() {
	allocsMu.Lock()
	tags := make(map[string]int)
	var total uint64
	for _, ac := range allocs {
		tags[ac.Tag]++
		total += ac.Size()
	}
	for tag, count := range tags {
		fmt.Printf("Allocator Tag: %s Count: %d\n", tag, count)
	}
	fmt.Printf("Total allocators: %d. Total Size: %s\n",
		len(allocs), humanize.IBytes(total))
	allocsMu.Unlock()
}

// AllocatorFrom would return the allocator corresponding to the ref.
func AllocatorFrom(ref uint64) *Allocator {
	allocsMu.Lock()
	a := allocs[ref]
	allocsMu.Unlock()
	return a
}

// Size returns the size of the allocations so far.
func (a *Allocator) Size() uint64 {
	return a.size
}

// Release would release the memory back. Remember to make this call to avoid memory leaks.
func (a *Allocator) Release() {
	if a == nil {
		return
	}
	for _, b := range a.buffers {
		Free(b)
	}

	allocsMu.Lock()
	delete(allocs, a.Ref)
	allocsMu.Unlock()
}

const maxAlloc = 1 << 30

func (a *Allocator) MaxAlloc() int {
	return maxAlloc
}

const nodeAlign = int(unsafe.Sizeof(uint64(0))) - 1

func (a *Allocator) AllocateAligned(sz int) []byte {
	tsz := sz + nodeAlign
	out := a.Allocate(tsz)
	aligned := (a.curIdx - tsz + nodeAlign) & ^nodeAlign

	start := tsz - (a.curIdx - aligned)
	return out[start : start+sz]
}

func (a *Allocator) Copy(buf []byte) []byte {
	out := a.Allocate(len(buf))
	copy(out, buf)
	return out
}

// Allocate would allocate a byte slice of length sz. It is safe to use this memory to unsafe cast
// to Go structs.
func (a *Allocator) Allocate(sz int) []byte {
	if len(a.buffers) == 0 {
		buf := Calloc(a.pageSize)
		a.buffers = append(a.buffers, buf)
	}

	if sz >= maxAlloc {
		panic(fmt.Sprintf("Allocate call exceeds max allocation possible."+
			" Requested: %d. Max Allowed: %d\n", sz, maxAlloc))
	}
	cb := a.buffers[a.curBuf]
	if len(cb) < a.curIdx+sz {
		for {
			a.pageSize *= 2 // Do multiply by 2 here.
			if a.pageSize >= sz {
				break
			}
		}
		if a.pageSize > maxAlloc {
			a.pageSize = maxAlloc
		}

		buf := Calloc(a.pageSize)
		a.buffers = append(a.buffers, buf)
		a.curBuf++
		a.curIdx = 0
		cb = a.buffers[a.curBuf]
	}

	slice := cb[a.curIdx : a.curIdx+sz]
	a.curIdx += sz
	a.size += uint64(sz)
	return slice
}

repository: Shusaku-Sahashi/ristretto

repo_name: Shusaku-Sahashi/ristretto


text:
# Clearsilver
SECTION = "net"
DESCRIPTION = "Clearsilver is a fast, powerful, and language-neutral HTML template system"
LICENSE = "Neotonic ClearSilver License"
DEPENDS = "python"
MAINTAINER = "Cliff Brake <cliff.brake@gmail.com>"
PR = "r0"

SRC_URI = "http://www.clearsilver.net/downloads/${P}.tar.gz \
           file://crosscompile.patch;patch=1"

EXTRA_OECONF = "--disable-apache --disable-perl --disable-ruby --disable-java --disable-csharp --enable-gettext --with-python=${STAGING_BINDIR}/python"

inherit autotools

FILES_${PN} += "/usr/lib/python*"

do_compile() {
	BUILD_SYS=${BUILD_SYS} HOST_SYS=${HOST_SYS} oe_runmake
}

do_configure() {
	gnu-configize
	oe_runconf
}


text:
/*
Copyright 2011 Google Inc.

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

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

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

package main

import (
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"time"

	"camlistore.org/pkg/cmdmain"
)

// env is the environment that a camput test runs within.
type env struct {
	// stdin is the standard input, or /dev/null if nil
	stdin io.Reader

	// Timeout optionally specifies the timeout on the command.
	Timeout time.Duration

	// TODO(bradfitz): vfs files.
}

func (e *env) timeout() time.Duration {
	if e.Timeout != 0 {
		return e.Timeout
	}
	return 15 * time.Second

}
func (e *env) Run(args ...string) (out, err []byte, exitCode int) {
	outbuf := new(bytes.Buffer)
	errbuf := new(bytes.Buffer)
	os.Args = append(os.Args[:1], args...)
	cmdmain.Stdout, cmdmain.Stderr = outbuf, errbuf
	if e.stdin == nil {
		cmdmain.Stdin = strings.NewReader("")
	} else {
		cmdmain.Stdin = e.stdin
	}
	exitc := make(chan int, 1)
	cmdmain.Exit = func(code int) {
		exitc <- code
		runtime.Goexit()
	}
	go func() {
		cmdmain.Main()
		cmdmain.Exit(0)
	}()
	select {
	case exitCode = <-exitc:
	case <-time.After(e.timeout()):
		panic("timeout running command")
	}
	out = outbuf.Bytes()
	err = errbuf.Bytes()
	return
}

// TestUsageOnNoargs tests that we output a usage message when given no args, and return
// with a non-zero exit status.
func TestUsageOnNoargs(t *testing.T) {
	var e env
	out, err, code := e.Run()
	if code != 1 {
		t.Errorf("exit code = %d; want 1", code)
	}
	if len(out) != 0 {
		t.Errorf("wanted nothing on stdout; got:\n%s", out)
	}
	if !bytes.Contains(err, []byte("Usage: camput")) {
		t.Errorf("stderr doesn't contain usage. Got:\n%s", err)
	}
}

// TestCommandUsage tests that we output a command-specific usage message and return
// with a non-zero exit status.
func TestCommandUsage(t *testing.T) {
	var e env
	out, err, code := e.Run("attr")
	if code != 1 {
		t.Errorf("exit code = %d; want 1", code)
	}
	if len(out) != 0 {
		t.Errorf("wanted nothing on stdout; got:\n%s", out)
	}
	sub := "Attr takes 3 args: <permanode> <attr> <value>"
	if !bytes.Contains(err, []byte(sub)) {
		t.Errorf("stderr doesn't contain substring %q. Got:\n%s", sub, err)
	}
}

func TestUploadingChangingDirectory(t *testing.T) {
	// TODO(bradfitz):
	//    $ mkdir /tmp/somedir
	//    $ cp dev-camput /tmp/somedir
	//    $ ./dev-camput  -file /tmp/somedir/ 2>&1 | tee /tmp/somedir/log
	// ... verify it doesn't hang.
	t.Logf("TODO")
}

func testWithTempDir(t *testing.T, fn func(tempDir string)) {
	tempDir, err := ioutil.TempDir("", "")
	if err != nil {
		t.Errorf("error creating temp dir: %v", err)
		return
	}
	defer os.RemoveAll(tempDir)

	confDir := filepath.Join(tempDir, "conf")
	mustMkdir(t, confDir, 0700)
	defer os.Setenv("CAMLI_CONFIG_DIR", os.Getenv("CAMLI_CONFIG_DIR"))
	os.Setenv("CAMLI_CONFIG_DIR", confDir)
	if err := ioutil.WriteFile(filepath.Join(confDir, "client-config.json"), []byte("{}"), 0644); err != nil {
		t.Fatal(err)
	}

	debugFlagOnce.Do(registerDebugFlags)

	fn(tempDir)
}

// Tests that uploads of deep directory trees don't deadlock.
// See commit ee4550bff453526ebae460da1ad59f6e7f3efe77 for backstory
func TestUploadDirectories(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping test in short mode.")
	}

	testWithTempDir(t, func(tempDir string) {
		uploadRoot := filepath.Join(tempDir, "to_upload") // read from here
		mustMkdir(t, uploadRoot, 0700)

		blobDestDir := filepath.Join(tempDir, "blob_dest") // write to here
		mustMkdir(t, blobDestDir, 0700)

		// There are 10 stat cache workers. Simulate a slow lookup in
		// the file-based ones (similar to reality), so the
		// directory-based nodes make it to the upload worker first
		// (where it would currently/previously deadlock waiting on
		// children that are starved out) See
		// ee4550bff453526ebae460da1ad59f6e7f3efe77.
		testHookStatCache = func(el interface{}, ok bool) {
			if !ok {
				return
			}
			if ok && strings.HasSuffix(el.(*node).fullPath, ".txt") {
				time.Sleep(50 * time.Millisecond)
			}
		}
		defer func() { testHookStatCache = nil }()

		dirIter := uploadRoot
		for i := 0; i < 2; i++ {
			dirPath := filepath.Join(dirIter, "dir")
			mustMkdir(t, dirPath, 0700)
			for _, baseFile := range []string{"file.txt", "FILE.txt"} {
				filePath := filepath.Join(dirPath, baseFile)
				if err := ioutil.WriteFile(filePath, []byte("some file contents "+filePath), 0600); err != nil {
					t.Fatalf("error writing to %s: %v", filePath, err)
				}
				t.Logf("Wrote file %s", filePath)
			}
			dirIter = dirPath
		}

		// Now set statCacheWorkers greater than uploadWorkers, so the
		// sleep above can re-arrange the order that files get
		// uploaded in, so the directory comes before the file. This
		// was the old deadlock.
		defer setAndRestore(&uploadWorkers, 1)()
		defer setAndRestore(&statCacheWorkers, 5)()

		e := &env{
			Timeout: 5 * time.Second,
		}
		stdout, stderr, exit := e.Run(
			"--blobdir="+blobDestDir,
			"--havecache=false",
			"--verbose=false", // useful to set true for debugging
			"file",
			uploadRoot)
		if exit != 0 {
			t.Fatalf("Exit status %d: stdout=[%s], stderr=[%s]", exit, stdout, stderr)
		}
	})
}

func TestCamputBlob(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping test in short mode.")
	}

	testWithTempDir(t, func(tempDir string) {
		blobDestDir := filepath.Join(tempDir, "blob_dest") // write to here
		mustMkdir(t, blobDestDir, 0700)

		e := &env{
			Timeout: 5 * time.Second,
			stdin:   strings.NewReader("foo"),
		}
		stdout, stderr, exit := e.Run(
			"--blobdir="+blobDestDir,
			"--havecache=false",
			"--verbose=false", // useful to set true for debugging
			"blob", "-")
		if exit != 0 {
			t.Fatalf("Exit status %d: stdout=[%s], stderr=[%s]", exit, stdout, stderr)
		}
		if got, want := string(stdout), "sha1-0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33\n"; got != want {
			t.Errorf("Stdout = %q; want %q", got, want)
		}
	})
}

func mustMkdir(t *testing.T, fn string, mode int) {
	if err := os.Mkdir(fn, 0700); err != nil {
		t.Errorf("error creating dir %s: %v", fn, err)
	}
}

func setAndRestore(dst *int, v int) func() {
	old := *dst
	*dst = v
	return func() { *dst = old }
}

repository: DavidBenko/gateway

repo_name: DavidBenko/gateway

branch_name: refs/heads/develop


text:
package deployment

import (
	hydrav1alpha1 "github.com/ory/hydra-maester/api/v1alpha1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

const BEBSecretNameSuffix = "-beb-oauth2"

// NewOAuth2Client creates a Hydra OAuth2Client CR object
func NewOAuth2Client() *hydrav1alpha1.OAuth2Client {
	labels := map[string]string{
		AppLabelKey:       PublisherName,
		instanceLabelKey:  instanceLabelValue,
		dashboardLabelKey: dashboardLabelValue,
	}
	oa2CR := &hydrav1alpha1.OAuth2Client{
		ObjectMeta: metav1.ObjectMeta{
			Name:      ControllerName,
			Namespace: ControllerNamespace,
			Labels:    labels,
		},
		Spec: hydrav1alpha1.OAuth2ClientSpec{
			GrantTypes: []hydrav1alpha1.GrantType{"client_credentials"},
			Scope:      "read write beb uaa.resource",
			SecretName: OAuth2ClientSecretName(),
		},
	}
	return oa2CR
}

func OAuth2ClientSecretName() string {
	return ControllerName + BEBSecretNameSuffix
}

repository: Rider-io/kyma

repo_name: Rider-io/kyma


text:
package framing

import (
	"fmt"

	"github.com/rsocket/rsocket-go/internal/common"
)

// FramePayload is payload frame.
type FramePayload struct {
	*BaseFrame
}

// Validate returns error if frame is invalid.
func (p *FramePayload) Validate() (err error) {
	return
}

func (p *FramePayload) String() string {
	m, _ := p.MetadataUTF8()
	return fmt.Sprintf("FramePayload{%s,data=%s,metadata=%s}", p.header, p.DataUTF8(), m)
}

// Metadata returns metadata bytes.
func (p *FramePayload) Metadata() ([]byte, bool) {
	return p.trySliceMetadata(0)
}

// Data returns data bytes.
func (p *FramePayload) Data() []byte {
	return p.trySliceData(0)
}

// MetadataUTF8 returns metadata as UTF8 string.
func (p *FramePayload) MetadataUTF8() (metadata string, ok bool) {
	raw, ok := p.Metadata()
	if ok {
		metadata = string(raw)
	}
	return
}

// DataUTF8 returns data as UTF8 string.
func (p *FramePayload) DataUTF8() string {
	return string(p.Data())
}

// NewFramePayload returns a new payload frame.
func NewFramePayload(id uint32, data, metadata []byte, flags ...FrameFlag) *FramePayload {
	fg := newFlags(flags...)
	bf := common.NewByteBuff()
	if len(metadata) > 0 {
		fg |= FlagMetadata
		if err := bf.WriteUint24(len(metadata)); err != nil {
			panic(err)
		}
		if _, err := bf.Write(metadata); err != nil {
			panic(err)
		}
	}
	if len(data) > 0 {
		if _, err := bf.Write(data); err != nil {
			panic(err)
		}
	}
	return &FramePayload{
		NewBaseFrame(NewFrameHeader(id, FrameTypePayload, fg), bf),
	}
}

repository: allanche/rsocket-go

repo_name: allanche/rsocket-go


text:
package models

import (
	"goblog/pkg/types"
	"time"
)

// BaseModel 模型基类
type BaseModel struct {
	ID       uint64    `gorm:"column:id;primaryKey;autoIncrement;not null"`
	CreateAt time.Time `gorm:"column:created_at;autoCreateTime"`
	UpdateAt time.Time `gorm:"column:updated_at;autoUpdateTime"`
}

// GetStringID 获取 ID 的字符串格式
func (a BaseModel) GetStringID() string {
	return types.Uint64ToString(a.ID)
}


text:
/*
Copyright 2019 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 adapter

import (
	"strings"
	"time"

	"github.com/sirupsen/logrus"

	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/test-infra/prow/apis/prowjobs/v1"
	"k8s.io/test-infra/prow/config"
	"k8s.io/test-infra/prow/gerrit/client"
	"k8s.io/test-infra/prow/gerrit/reporter"
	"k8s.io/test-infra/prow/pjutil"
)

// messageFilter builds a filter for jobs based on the messageBody matching the trigger regex of the jobs.
func messageFilter(lastUpdate time.Time, change client.ChangeInfo, presubmits []config.Presubmit, latestReport *reporter.JobReport, logger *logrus.Entry) (pjutil.Filter, error) {
	var filters []pjutil.Filter
	currentRevision := change.Revisions[change.CurrentRevision].Number

	contextGetter := func() (sets.String, sets.String, error) {
		allContexts := sets.String{}
		failedContexts := sets.String{}
		for _, presubmit := range presubmits {
			allContexts.Insert(presubmit.Name)
		}
		if latestReport != nil {
			jobs := map[string]*reporter.Job{}
			for _, job := range latestReport.Jobs {
				jobs[job.Name] = job
			}
			for _, presubmit := range presubmits {
				j, ok := jobs[presubmit.Name]
				if ok && (strings.ToLower(j.State) == string(v1.FailureState) || strings.ToLower(j.State) == string(v1.ErrorState)) {
					failedContexts.Insert(presubmit.Name)
				}
			}
		}
		return failedContexts, allContexts, nil
	}
	for _, message := range change.Messages {
		messageTime := message.Date.Time
		if message.RevisionNumber != currentRevision || !messageTime.After(lastUpdate) {
			continue
		}
		filter, err := pjutil.PresubmitFilter(false, contextGetter, message.Message, logger)
		if err != nil || filter == nil {
			logger.Warnf("failed to create filter for %s", message.Message)
			continue
		}
		filters = append(filters, filter)
	}
	return pjutil.AggregateFilter(filters), nil
}

repository: TAIPANBOX/test-infra

repo_name: TAIPANBOX/test-infra


text:
version https://git-lfs.github.com/spec/v1
oid sha256:6149b01d673d4f093bcf5fff7c4fc2b10644244a1f8d92044d6d0e603b2603b0
size 1370

repository: initialz/tensorflow-yolo-face-ios

repo_name: initialz/tensorflow-yolo-face-ios


text:
package cache

import (
	"sync"
)

type bucket struct {
	sync.RWMutex
	lookup map[string]map[string]*Entry
}

func (b *bucket) get(primary string, secondary string) *Entry {
	defer b.RUnlock()
	b.RLock()
	group, ok := b.lookup[primary]
	if ok == false {
		return nil
	}
	return group[secondary]
}

func (b *bucket) set(primary string, secondary string, entry *Entry) *Entry {
	defer b.Unlock()
	b.Lock()

	if group, ok := b.lookup[primary]; ok {
		existing := group[secondary]
		group[secondary] = entry
		return existing
	}

	b.lookup[primary] = map[string]*Entry{secondary: entry}
	return nil
}

func (b *bucket) delete(primary string, secondary string, deletables chan *Entry) bool {
	defer b.Unlock()
	b.Lock()
	if group, ok := b.lookup[primary]; ok {
		if entity, ok := group[secondary]; ok {
			delete(group, secondary)
			if deletables != nil {
				deletables <- entity
			}
			return true
		}
	}
	return false
}

func (b *bucket) deleteAll(primary string, deletables chan *Entry) bool {
	defer b.Unlock()
	b.Lock()
	if group, ok := b.lookup[primary]; ok {
		for _, entity := range group {
			deletables <- entity
		}
		delete(b.lookup, primary)
		return true
	}
	return false
}

repository: karlseguin/garnish

repo_name: karlseguin/garnish


text: @inbook{Cardoso05SWSWPC,	address = {Heidelberg, Germany},	author = {Cardoso, Jorge and Sheth, Amit},	booktitle = {Semantic Web Service and Web Processes Conference},	date-added = {2018-04-25 20:02:07 +0000},	date-modified = {2018-04-25 20:02:07 +0000},	isbn = {3-540-24328-3},	owner = {Jorge Cardoso},	pages = {1-13},	publisher = {Springer-Verlag},	refid = {39},	timestamp = {2010.08.26},	title = {Introduction to Semantic Web Services and Web Process Composition},	webpdf = {/Papers/BC-2004-002-Springer-SWSWPC-Introduction-to-semantic-web-services-and-web-process.pdf},	year = {2005}}


text:
DESCRIPTION = "Fribidi library for bidirectional text"
SECTION = "libs"
PRIORITY = "optional"
PR = "r1"

PROVIDES = "libfribidi"

# Slightly incompatible with 0.10.x, so:
DEFAULT_PREFERENCE = "-1"
DEFAULT_PREFERENCE_angstrom = "1"

inherit autotools lib_package pkgconfig

CFLAGS_append = "  -DPAGE_SIZE=4096 "

SRC_URI = "http://fribidi.org/download/fribidi-${PV}.tar.gz"

SRC_URI[md5sum] = "626db17d2d99b43615ad9d12500f568a"
SRC_URI[sha256sum] = "49cf91586e48b52fe25872ff66c1da0dff0daac2593f9f300e2af12f44f64177"
BBCLASSEXTEND = "native"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty


text:
package rds

import (
	"fmt"

	"code.cloudfoundry.org/lager"
	"github.com/huaweicloud/huaweicloud-service-broker/pkg/models"
	"github.com/jinzhu/gorm"

	// import mysql driver
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

// BuildBindingCredential from different rds instance
func BuildBindingCredential(
	host string,
	port int,
	name string,
	username string,
	password string,
	servicetype string,
	logger lager.Logger) (BindingCredential, error) {

	var uri string
	var jdbcuri string

	if servicetype == models.RDSPostgresqlServiceName {
		// Postgresql
		uri = fmt.Sprintf("%s:%s@%s:%d", username, password, host, port)
	} else if servicetype == models.RDSMysqlServiceName {
		// Mysql
		name = "broker"
		err := CreateDatabase(username, password, host, port, "mysql", name)
		if err != nil {
			logger.Debug(fmt.Sprintf("create database failed: %v", err))
		}
		uri = fmt.Sprintf("mysql://%s:%s@%s:%d/%s?reconnect=true", username, password, host, port, name)
		jdbcuri = fmt.Sprintf("jdbc:mysql://%s:%d/%s?user=%s&password=%s", host, port, name, username, password)
	} else if servicetype == models.RDSSqlserverServiceName {
		// Sqlserver
		uri = fmt.Sprintf("%s:%s@%s:%d", username, password, host, port)
	} else if servicetype == models.RDSHwsqlServiceName {
		// Hwsql
		uri = fmt.Sprintf("%s:%s@%s:%d", username, password, host, port)
	} else {
		return BindingCredential{}, fmt.Errorf("unknown service type: %s", servicetype)
	}

	// Init BindingCredential
	bc := BindingCredential{
		Host:     host,
		Port:     port,
		Name:     name,
		UserName: username,
		Password: password,
		URI:      uri,
		JDBCURL:  jdbcuri,
		Type:     servicetype,
	}
	return bc, nil
}

// CreateDatabase create database by name
func CreateDatabase(DatabaseUsername string,
	DatabasePassword string,
	DatabaseHost string,
	DatabasePort int,
	DatabaseType string,
	DatabaseName string) error {
	// connect to back database
	connStr := fmt.Sprintf(
		"%v:%v@tcp(%v:%v)/mysql?charset=utf8&parseTime=True&loc=Local",
		DatabaseUsername,
		DatabasePassword,
		DatabaseHost,
		DatabasePort)

	dbConn, err := gorm.Open(DatabaseType, connStr)
	if err != nil {
		return err
	}

	CreateDataBaseSQL := fmt.Sprintf(`create database %s;`, DatabaseName)
	if err := dbConn.Exec(CreateDataBaseSQL).Error; err != nil {
		return err
	}

	return nil
}

repository: edisonxiang/huaweicloud-service-broker

repo_name: edisonxiang/huaweicloud-service-broker


text:
DESCRIPTION = "Interface definitions for Zope products"
SECTION = "console/network"

LICENSE = "ZPL-2.1"
LIC_FILES_CHKSUM = "file://PKG-INFO;beginline=8;endline=8;md5=e54fd776274c1b7423ec128974bd9d46"
PR = "r1"

SRC_URI = "http://pypi.python.org/packages/source/z/zope.interface/zope.interface-${PV}.tar.gz"
SRC_URI[md5sum] = "685fc532550abb07cca6190c9cd2b901"
SRC_URI[sha256sum] = "b81d898532c47f73475c2d0c23580e289eed25923d007eca8e62750c0998bba0"

S = "${WORKDIR}/zope.interface-${PV}"

inherit setuptools

RPROVIDES_${PN} += "zope-interfaces"
FILES_${PN}-dbg += "${PYTHON_SITEPACKAGES_DIR}/*.egg/*/*/.debug"
FILES_${PN}-dev += "${PYTHON_SITEPACKAGES_DIR}/zope/interface/*.c"
FILES_${PN}-doc += "${PYTHON_SITEPACKAGES_DIR}/zope/interface/*.txt"
FILES_${PN}-tests = " \
        ${PYTHON_SITEPACKAGES_DIR}/zope/interface/tests \
        ${PYTHON_SITEPACKAGES_DIR}/zope/interface/common/tests \
"

repository: ExorEmbedded/exor-workspace

repo_name: ExorEmbedded/exor-workspace


text:
package catalogsourceconfig

import (
	"context"
	"fmt"
	"strings"

	"github.com/operator-framework/operator-marketplace/pkg/datastore"

	olm "github.com/operator-framework/operator-lifecycle-manager/pkg/api/apis/operators/v1alpha1"
	"github.com/operator-framework/operator-marketplace/pkg/apis/marketplace/v1alpha1"
	"github.com/operator-framework/operator-sdk/pkg/sdk"
	"github.com/sirupsen/logrus"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// Copied from https://github.com/operator-framework/operator-lifecycle-manager/blob/master/pkg/controller/registry/configmap_loader.go#L18
// TBD: Vendor in the folder once we require more than just these constants from the OLM registry code
const (
	ConfigMapCRDName     = "customResourceDefinitions"
	ConfigMapCSVName     = "clusterServiceVersions"
	ConfigMapPackageName = "packages"
)

// Handler is the interface that wraps the Handle method
type Handler interface {
	Handle(ctx context.Context, event sdk.Event) error
}

type handler struct {
	reader datastore.Reader
}

var log *logrus.Entry

// Handle handles a new event associated with CatalogSourceConfig type
func (h *handler) Handle(ctx context.Context, event sdk.Event) error {
	csc := event.Object.(*v1alpha1.CatalogSourceConfig)
	log = getLoggerWithCatalogSourceConfigTypeFields(csc)
	// Ignore the delete event as the garbage collector will clean up the created resources as per the OwnerReference
	if event.Deleted {
		log.Infof("Deleted")
		return nil
	}
	data, err := h.createCatalogData(csc)
	if err != nil {
		return err
	}
	return createCatalogSource(csc, data)
}

// createCatalogData constructs the ConfigMap data by reading the manifest information of all packages
// from the datasource
func (h *handler) createCatalogData(csc *v1alpha1.CatalogSourceConfig) (map[string]string, error) {
	packageIDs := getPackageIDs(csc.Spec.Packages)
	data := make(map[string]string)
	if len(packageIDs) < 1 {
		return data, fmt.Errorf("No packages specified in CatalogSourceConfig %s/%s", csc.Namespace, csc.Name)
	}

	// TBD: Do we create a CatalogSource per package?
	for id := range packageIDs {
		manifest, err := h.reader.Read(packageIDs[id])
		if err != nil {
			log.Errorf("Error \"%v\" getting manifest for package ID %s", err, packageIDs[id])
			continue
		}
		// TODO: Add more error checking
		data[ConfigMapCRDName] += manifest.Manifest.Data.CRDs
		data[ConfigMapCSVName] += manifest.Manifest.Data.CSVs
		data[ConfigMapPackageName] += manifest.Manifest.Data.Packages
	}
	return data, nil
}

// createCatalogSource creates a new CatalogSource CR and all the resources it requires
func createCatalogSource(cr *v1alpha1.CatalogSourceConfig, data map[string]string) error {
	// Create the ConfigMap that will be used by the CatalogSource
	catalogConfigMap := newConfigMap(cr, data)
	log.Infof("Creating %s ConfigMap", catalogConfigMap.Name)
	err := sdk.Create(catalogConfigMap)
	if err != nil && !errors.IsAlreadyExists(err) {
		log.Errorf("Failed to create ConfigMap : %v", err)
		return err
	}

	catalogSource := newCatalogSource(cr, catalogConfigMap.Name)
	err = sdk.Create(catalogSource)
	if err != nil && !errors.IsAlreadyExists(err) {
		log.Errorf("Failed to create CatalogSource : %v", err)
		return err
	}
	log.Infof("Created")
	return nil
}

// getLoggerWithCatalogSourceConfigTypeFields returns a logger entry that can be used for consistent logging
func getLoggerWithCatalogSourceConfigTypeFields(csc *v1alpha1.CatalogSourceConfig) *logrus.Entry {
	return logrus.WithFields(logrus.Fields{
		"type":            csc.TypeMeta.Kind,
		"targetNamespace": csc.Spec.TargetNamespace,
		"name":            csc.GetName(),
	})
}

// getPackageIDs returns a list of IDs from a comma separated string of IDs
func getPackageIDs(csIDs string) []string {
	return strings.Split(csIDs, ",")
}

// newCatalogSource returns a CatalogSource object
func newCatalogSource(cr *v1alpha1.CatalogSourceConfig, configMapName string) *olm.CatalogSource {
	name := v1alpha1.CatalogSourcePrefix + cr.Name
	return &olm.CatalogSource{
		TypeMeta: metav1.TypeMeta{
			Kind:       olm.CatalogSourceKind,
			APIVersion: olm.CatalogSourceCRDAPIVersion,
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: cr.Spec.TargetNamespace,
			OwnerReferences: []metav1.OwnerReference{
				*metav1.NewControllerRef(cr, cr.GroupVersionKind()),
			},
		},
		Spec: olm.CatalogSourceSpec{
			SourceType:  "internal",
			ConfigMap:   configMapName,
			DisplayName: cr.Name,
			// TBD: Where do we get this information from?
			Publisher: cr.Name,
		},
	}
}

// newConfigMap returns a new ConfigMap object
func newConfigMap(cr *v1alpha1.CatalogSourceConfig, data map[string]string) *corev1.ConfigMap {
	name := v1alpha1.ConfigMapPrefix + cr.Name
	return &corev1.ConfigMap{
		TypeMeta: metav1.TypeMeta{
			Kind:       "ConfigMap",
			APIVersion: "v1",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: cr.Spec.TargetNamespace,
			OwnerReferences: []metav1.OwnerReference{
				*metav1.NewControllerRef(cr, cr.GroupVersionKind()),
			},
		},
		Data: data,
	}
}

repository: SamiSousa/operator-marketplace

repo_name: SamiSousa/operator-marketplace


text:
DESCRIPTION = "MPEG Video Decoder Library"
SECTION = "libs"
PRIORITY = "optional"
MAINTAINER = "Tim Ansell <ipks@mithis.net>"
DEPENDS = "virtual/libsdl"
LICENSE = "GPL"

SRC_URI = "http://libmpeg2.sourceforge.net/files/mpeg2dec-${PV}.tar.gz \
			file://Makefile.patch;patch=1 "
S = "${WORKDIR}/mpeg2dec-0.4.0"

inherit autotools

EXTRA_OECONF="--enable-shared"

do_stage() {
	oe_libinstall -a -so -C libmpeg2 libmpeg2 ${STAGING_LIBDIR}
	oe_libinstall -a -so -C libmpeg2/convert libmpeg2convert ${STAGING_LIBDIR}

	install -d ${STAGING_INCDIR}/mpeg2dec/
	install -m 0644 include/mpeg2.h ${STAGING_INCDIR}/mpeg2dec/
	install -m 0644 include/mpeg2convert.h ${STAGING_INCDIR}/mpeg2dec/
}


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

package main

import (
	"bytes"
	"flag"
	"log"
	"strings"
	"testing"

	"github.com/codegangsta/cli"
	"github.com/mssola/capture"
)

func testPatchContext(source, destination string) *cli.Context {
	set := flag.NewFlagSet("test", 0)
	c := cli.NewContext(nil, set, nil)
	args := []string{}

	if source != "" {
		args = append(args, source)
	}
	if destination != "" {
		args = append(args, destination)
	}

	if err := set.Parse(args); err != nil {
		log.Fatalf("Cannot parse args: %s", err)
	}
	return c
}

func testCommand() string {
	cmd := dockerClient.(*mockClient).lastCmd
	if len(cmd) != 1 {
		return ""
	}

	// The command is basically: "zypper ref && actual command".
	return strings.TrimSpace(strings.Split(cmd[0], "&&")[1])
}

func TestListPatchesNoImageSpecified(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { listPatchesCmd(testContext([]string{}, false)) })

	if testCommand() != "" {
		t.Fatalf("The command should not have been executed")
	}
	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
	if !strings.Contains(buffer.String(), "Error: no image name specified") {
		t.Fatal("It should've logged something\n")
	}
}

func TestListPatchesCommandFailure(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{commandFail: true}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	capture.All(func() {
		listPatchesCmd(testContext([]string{"opensuse:13.2"}, false))
	})

	if testCommand() != "zypper lp" {
		t.Fatalf("Wrong command!")
	}
	if !strings.Contains(buffer.String(), "Error: Command exited with status 1") {
		t.Fatal("It should've logged something\n")
	}
	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}

func TestPatchCommandWrongInvocation(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { patchCmd(testPatchContext("", "")) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
	if !strings.Contains(buffer.String(), "Wrong invocation") {
		t.Fatal("It should've logged something\n")
	}
}

func TestPatchCommandImageOverwriteDetected(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{listFail: true}

	capture.All(func() { patchCmd(testPatchContext("ori", "new:1.0.0")) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}

func TestPatchCommandRunAndCommitFailure(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{startFail: true}

	capture.All(func() { patchCmd(testPatchContext("ori", "new:1.0.0")) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}

func TestPatchCommandInvalidTargetName(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	capture.All(func() { patchCmd(testPatchContext("ori", "WRONG")) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}

func TestPatchCommandCommitSuccess(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{listReturnOneImage: true}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { patchCmd(testPatchContext("opensuse:13.2", "new:1.0.0")) })

	if exitInvocations != 0 {
		t.Fatal(buffer.String())
	}
	if !strings.Contains(buffer.String(), "new:1.0.0 successfully created") {
		t.Fatal("It should've logged something\n")
	}
}

func TestPatchCommandCannotUpdateCache(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)
	capture.All(func() { patchCmd(testPatchContext("ori", "new:1.0.0")) })

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
	if !strings.Contains(buffer.String(), "new:1.0.0 successfully created") {
		t.Fatal("The new image should have been successfully created\n")
	}
	if !strings.Contains(buffer.String(), "This will break the") {
		t.Fatal("We should warn users zypper-docker ps is not going to work\n")
	}
}

func TestListPatchesContainerCheckContainerFailure(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{listFail: true}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	capture.All(func() {
		listPatchesContainerCmd(testContext([]string{"opensuse:13.2"}, false))
	})

	if exitInvocations != 1 {
		t.Fatalf("Expected to have exited with error")
	}
}

func TestListPatchesContainerCheckContainerSuccess(t *testing.T) {
	setupTestExitStatus()
	dockerClient = &mockClient{}

	buffer := bytes.NewBuffer([]byte{})
	log.SetOutput(buffer)

	capture.All(func() {
		listPatchesContainerCmd(testContext([]string{"suse"}, false))
	})

	if exitInvocations != 0 {
		t.Fatalf("Should not have exited with error")
	}
}

repository: jloehel/zypper-docker

repo_name: jloehel/zypper-docker


text:
@article{WatsonCrick1953,
  title={Molecular structure of nucleic acids},
  author={Watson, James D and Crick, Francis HC and others},
  journal={Nature},
  volume={171},
  number={4356},
  pages={737--738},
  year={1953}
}

repository: stencila/encoda

repo_name: stencila/encoda

gha_language: Jupyter Notebook


text:
@InProceedings{azizyan15,
  supplementary = {Supplementary:azizyan15-supp.zip},
  title = {{Efficient Sparse Clustering of High-Dimensional Non-spherical Gaussian Mixtures}},
  author = {Azizyan, Martin and Singh, Aarti and Wasserman, Larry},
  pages = {37-45},
  abstract = {We consider the problem of clustering data points in high dimensions, i.e., when the number of data points may be much smaller than the number of dimensions. Specifically, we consider a Gaussian mixture model (GMM) with two non-spherical Gaussian components, where the clusters are distinguished by only a few relevant dimensions. The method we propose is a combination of a recent approach for learning parameters of a Gaussian mixture model and sparse linear discriminant analysis (LDA). In addition to cluster assignments, the method returns an estimate of the set of features relevant for clustering. Our results indicate that the sample complexity of clustering depends on the sparsity of the relevant feature set, while only scaling logarithmically with the ambient dimension. Further, we require much milder assumptions than existing work on clustering in high dimensions. In particular, we do not require spherical clusters nor necessitate mean separation along relevant dimensions.},
}

repository: mreid/papersite

repo_name: mreid/papersite


text:
DESCRIPTION = "A system for controlling process state under UNIX"
HOMEPAGE = "http://supervisord.org"
SECTION = "admin"
PRIORITY = "optional"
LICENSE = "BSD"
PR = "ml1"

SRC_URI = "https://pypi.python.org/packages/source/s/supervisor/supervisor-${PV}.tar.gz \
           file://supervisord.conf \
           file://supervisord.sh"

S = "${WORKDIR}/supervisor-${PV}"

inherit setuptools

# Removed python-meld3 from RDEPENDS. Will probably need to post-install it with pip.

RDEPENDS_${PN} = "\
	python-setuptools \
	python-misc \
	python-html \
	python-unixadmin \
	python-xmlrpc \
	python-shell \
	python-resource"

PACKAGES = "${PN}"

site_packages="${libdir}/python2.*/site-packages"

FILES_${PN} = "\
	${sysconfdir}/* \
	${bindir}/* \
	${site_packages}/*.egg-info \
	${site_packages}/*.pth \
	${site_packages}/supervisor/*.pyo \
	${site_packages}/supervisor/*.txt \
	${site_packages}/supervisor/ui \
	${site_packages}/supervisor/medusa/*.pyo \
	${site_packages}/supervisor/medusa/*.txt \
	${site_packages}/supervisor/medusa/thread/*.pyo"

do_install_prepend() {
	install -d ${D}${sysconfdir}/init.d
	install -d ${D}${sysconfdir}/supervisor/conf.d

	install -m 0644 ${WORKDIR}/supervisord.conf ${D}${sysconfdir}/supervisord.conf
	install -m 0755 ${WORKDIR}/supervisord.sh ${D}${sysconfdir}/init.d/supervisord.sh
}

pkg_postinst() {
    update-rc.d supervisord defaults 90
}

pkg_postrm() {
    update-rc.d supervisord remove
}

SRC_URI[md5sum] = "94ff3cf09618c36889425a8e002cd51a"
SRC_URI[sha256sum] = "82aac54c5760b6a4f4c28dda203714e362a68b4a9ba8549fa65955998e3a2212"


text:
DESCRIPTION = "libssh is a mulitplatform C library \
implementing the SSHv2 and SSHv1 protocol for client \
and server implementations."

LICENSE = "LGPLv2.1"
LIC_FILES_CHKSUM = "file://COPYING;md5=388a4fb1dea8ceae0be78ba9b01fc139"

PR = "r0"

SRC_URI = "\
  http://www.libssh.org/files/0.5/libssh-${PV}.tar.gz \
"
inherit cmake

# Add build directory.
OECMAKE_BUILDPATH = "${WORKDIR}/build"
EXTRA_OEMAKE = "-C ${OECMAKE_BUILDPATH}"
OECMAKE_SOURCEPATH = "${WORKDIR}/libssh-${PV}"

SRC_URI[md5sum] = "9ad01838d3b89d98e900e0f6260a88cc"
SRC_URI[sha256sum] = "ed42a6c94c74bafed580caeaf40af83ec409aaa1b83010cb1e1c60b94f10daf0"

repository: wolfgar/meta-stef

repo_name: wolfgar/meta-stef

gha_language: BlitzBasic


text:
// Package storage is responsible for the persistent storage of state.
//
// Sous state is stored in a file hierarchy like this:
//
//     /
//         defs.yaml
//         manifests/
//             github.com/
//                 username/
//                     reponame/
//                         dirname/
//                             subdirname.yaml
package storage

import (
	"fmt"
	"io"
	"sort"

	"github.com/opentable/hy"
	"github.com/opentable/sous/lib"
	"github.com/opentable/sous/util/logging"
	"github.com/opentable/sous/util/yaml"
	"github.com/pkg/errors"
)

type (
	// DiskStateManager implements StateReader and StateWriter using disk
	// storage as its back-end.
	DiskStateManager struct {
		BaseDir string
		Codec   *hy.Codec
	}
)

// NewDiskStateManager returns a new DiskStateManager configured to read and
// write from a filesystem tree containing YAML files.
func NewDiskStateManager(baseDir string) *DiskStateManager {
	c := hy.NewCodec(func(c *hy.Codec) {
		c.FileExtension = "yaml"
		c.MarshalFunc = yaml.Marshal
		c.UnmarshalFunc = yaml.Unmarshal
	})
	return &DiskStateManager{Codec: c, BaseDir: baseDir}
}

func repairState(s *sous.State) error {

	for _, m := range s.Manifests.Snapshot() {
		sort.Strings(m.Owners)
	}
	reportDebugDiskStateManagerMessage("Validating State", nil, nil, logging.Log)

	flaws := s.Validate()
	reportDebugDiskStateManagerMessage("Repairng State flaws", flaws, nil, logging.Log)

	_, es := sous.RepairAll(flaws)

	if len(es) > 0 {
		strs := []string{}
		for _, e := range es {
			strs = append(strs, e.Error())
		}
		return errors.Errorf("Couldn't repair state: %v", strs)
	}
	return nil
}

// ReadState loads the entire intended state of the world from a dir.
func (dsm *DiskStateManager) ReadState() (*sous.State, error) {
	// TODO: Allow state dir to be passed as flag in sous/cli.
	// TODO: Consider returning a error to indicate if the state dir exists at all.
	reportDebugDiskStateManagerMessage("Reading state from disk", nil, nil, logging.Log)
	s := sous.NewState()
	err := dsm.Codec.Read(dsm.BaseDir, s)
	if err != nil {
		return s, err
	}

	// XXX Move to validation
	if s.Defs.Clusters == nil {
		return s, nil // errors.Errorf("no clusters defined in %s", dsm.baseDir)
	}
	// XXX Move to validation
	for _, k := range s.Manifests.Keys() {
		m, _ := s.Manifests.Get(k)
		if m == nil {
			return nil, fmt.Errorf("manifest %q is nil", k)
		}
		for clusterName := range m.Deployments {
			if _, ok := s.Defs.Clusters[clusterName]; !ok {
				return s, errors.Errorf("cluster %q not defined (from manifest %q)",
					clusterName, k)
			}
		}
	}
	if e := repairState(s); e != nil {
		return nil, e
	}
	return s, nil
}

// WriteState records the entire intended state of the world to a dir.
func (dsm *DiskStateManager) WriteState(s *sous.State, u sous.User) error {
	if e := repairState(s); e != nil {
		return e
	}
	reportDebugDiskStateManagerMessage("Writing state to disk", nil, nil, logging.Log)
	return dsm.Codec.Write(dsm.BaseDir, s)
}

type diskStateManagerMessage struct {
	logging.CallerInfo
	msg          string
	flawsMessage sous.FlawMessage
	err          error
	debug        bool
}

func reportDebugDiskStateManagerMessage(msg string, flaws []sous.Flaw, err error, log logging.LogSink) {
	reportDiskStateManagerMessage(msg, flaws, err, log, true)
}

func reportDiskStateManagerMessage(msg string, f []sous.Flaw, err error, log logging.LogSink, debug ...bool) {

	isDebug := false
	if len(debug) > 0 {
		isDebug = debug[0]
	}

	msgLog := diskStateManagerMessage{
		msg:          msg,
		CallerInfo:   logging.GetCallerInfo(logging.NotHere()),
		err:          err,
		flawsMessage: sous.FlawMessage{f},
		debug:        isDebug,
	}
	logging.Deliver(msgLog, log)
}

func (msg diskStateManagerMessage) WriteToConsole(console io.Writer) {
	if !msg.debug {
		fmt.Fprintf(console, "%s\n", msg.composeMsg())
	}
}

func (msg diskStateManagerMessage) DefaultLevel() logging.Level {
	level := logging.WarningLevel

	if msg.debug == true {
		level = logging.DebugLevel
	}

	return level
}

func (msg diskStateManagerMessage) Message() string {
	return msg.composeMsg()
}

func (msg diskStateManagerMessage) composeMsg() string {
	errMsg := "nil"
	if msg.err != nil {
		errMsg = msg.err.Error()
	}
	flaws := msg.flawsMessage.ReturnFlawMsg()
	if flaws == "" {
		flaws = "nil"
	}
	return fmt.Sprintf("Disk State Manager Message %s: flaws {%s}, error {%s}", msg.msg, flaws, errMsg)
}

func (msg diskStateManagerMessage) EachField(f logging.FieldReportFn) {
	f("@loglov3-otl", "sous-generic-v1")

	flaws := msg.flawsMessage.ReturnFlawMsg()

	if flaws != "" {
		f("sous-flaws", flaws)
	}

	if msg.err != nil {
		f("error", msg.err.Error())
	}
	msg.CallerInfo.EachField(f)
}