text:
//
//   Copyright © 2021 Uncharted Software 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 routes

import (
	"fmt"
	"net/http"

	"github.com/golang/protobuf/ptypes/empty"
	"github.com/pkg/errors"
	"goji.io/v3/pat"

	"github.com/uncharted-distil/distil-compute/model"
	"github.com/uncharted-distil/distil/api/env"
	api "github.com/uncharted-distil/distil/api/model"
	"github.com/uncharted-distil/distil/api/task"
	log "github.com/unchartedsoftware/plog"
)

// ClusteringResult represents a clustering response for a variable.
type ClusteringResult struct {
	ClusterField string `json:"cluster"`
}

// ClusteringHandler generates a route handler that enables clustering
// of a variable and the creation of the new column to hold the cluster label.
func ClusteringHandler(metaCtor api.MetadataStorageCtor, dataCtor api.DataStorageCtor, config env.Config) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		// check if route is enabled
		if !config.ClusteringEnabled {
			// return empty result
			err := handleJSON(w, empty.Empty{})
			if err != nil {
				handleError(w, errors.Wrap(err, "unable marshal clustering result into JSON"))
				return
			}
			return
		}
		// get dataset name
		dataset := pat.Param(r, "dataset")
		// get variable name
		variable := pat.Param(r, "variable")
		// get cluster count
		params, err := getPostParameters(r)
		if err != nil {
			handleError(w, errors.Wrap(err, "Unable to parse post parameters"))
			return
		}
		clusterCount := config.ClusteringKMeansDefaultCount
		if params["clusterCount"] != nil {
			clusterCount = int(params["clusterCount"].(float64))
		}

		// arbitrary limit to protect against errant input
		if clusterCount < 3 || clusterCount > 10 {
			handleError(w, errors.Errorf("cluster count must be between 3 and 10"))
			return
		}

		// get storage clients
		metaStorage, err := metaCtor()
		if err != nil {
			handleError(w, err)
			return
		}
		dataStorage, err := dataCtor()
		if err != nil {
			handleError(w, err)
			return
		}

		ds, err := metaStorage.FetchDataset(dataset, false, false, false)
		if err != nil {
			handleError(w, err)
			return
		}
		storageName := ds.StorageName

		clusterVarName := fmt.Sprintf("%s%s_%d", model.ClusterVarPrefix, variable, clusterCount)

		// check if the cluster variables exist
		clusterVarExist, err := metaStorage.DoesVariableExist(dataset, clusterVarName)
		if err != nil {
			handleError(w, err)
			return
		}

		// get the source dataset folder
		datasetMeta, err := metaStorage.FetchDataset(dataset, false, false, false)
		if err != nil {
			handleError(w, err)
			return
		}

		// create the new metadata and database variables
		if !clusterVarExist {
			// add data variable if needed
			clusterVarInStorage, err := dataStorage.DoesVariableExist(dataset, storageName, clusterVarName)
			if err != nil {
				log.Warnf("unable to check if cluster variable already exists: %v", err)
			}
			if !clusterVarInStorage {
				err = dataStorage.AddVariable(dataset, storageName, clusterVarName, model.CategoricalType, "")
				if err != nil {
					handleError(w, err)
					return
				}
			}

			// cluster data
			addMeta, clustered, err := task.Cluster(datasetMeta, variable, config.ClusteringKMeans, clusterCount)
			if err != nil {
				handleError(w, err)
				return
			}

			if addMeta {
				err = metaStorage.AddVariable(dataset, clusterVarName, "Pattern", model.CategoricalType, []string{model.VarDistilRoleMetadata})
				if err != nil {
					handleError(w, err)
					return
				}
			}

			// build the data for batching
			clusteredData := make(map[string]string)
			// get all the unique pattern values
			uniquePatterns := map[string]bool{}
			for _, cluster := range clustered {
				clusteredData[cluster.D3MIndex] = cluster.Label
				uniquePatterns[cluster.Label] = true
			}
			// convert map keys to array
			keys := make([]string, len(uniquePatterns))
			idx := 0
			for key := range uniquePatterns {
				keys[idx] = key
				idx++
			}
			// fetch the new cluster var
			clusterVar, err := metaStorage.FetchVariable(dataset, clusterVarName)
			if err != nil {
				handleError(w, err)
				return
			}
			// set values
			clusterVar.Values = keys
			// update cluster variable
			err = metaStorage.UpdateVariable(dataset, clusterVarName, clusterVar)
			if err != nil {
				handleError(w, err)
				return
			}
			clusteredVariable := &model.Variable{}
			// update the variable grouping
			for _, v := range ds.Variables {
				if v.Grouping != nil && v.Grouping.GetIDCol() == variable {
					clusteredVariable = v
				}
			}
			if clusteredVariable.Grouping != nil {
				if model.IsTimeSeries(clusteredVariable.Grouping.GetType()) {
					clusteredVariable.Grouping.(*model.TimeseriesGrouping).ClusterCol = clusterVarName
				} else if model.IsMultiBandImage(clusteredVariable.Grouping.GetType()) {
					clusteredVariable.Grouping.(*model.MultiBandImageGrouping).ClusterCol = clusterVarName
				}
				err = metaStorage.UpdateVariable(dataset, clusteredVariable.Key, clusteredVariable)
				if err != nil {
					handleError(w, err)
					return
				}
			}
			// update the batches
			err = dataStorage.UpdateVariableBatch(storageName, clusterVarName, clusteredData)
			if err != nil {
				handleError(w, err)
				return
			}
		}

		// marshal output into JSON
		err = handleJSON(w, ClusteringResult{
			ClusterField: clusterVarName,
		})
		if err != nil {
			handleError(w, errors.Wrap(err, "unable marshal clustering result into JSON"))
			return
		}
	}
}

// ClusteringExplainHandler creates a route handler that will cluster an explained
// result output, treating it as a tabular dataset.
func ClusteringExplainHandler(solutionCtor api.SolutionStorageCtor, metaCtor api.MetadataStorageCtor,
	dataCtor api.DataStorageCtor, config env.Config) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		// get dataset name
		resultID := pat.Param(r, "result-id")

		// get storage clients
		solutionStorage, err := solutionCtor()
		if err != nil {
			handleError(w, err)
			return
		}
		dataStorage, err := dataCtor()
		if err != nil {
			handleError(w, err)
			return
		}
		metaStorage, err := metaCtor()
		if err != nil {
			handleError(w, err)
			return
		}

		// get target from solution data
		result, err := solutionStorage.FetchSolutionResultByUUID(resultID)
		if err != nil {
			handleError(w, err)
			return
		}
		request, err := solutionStorage.FetchRequestBySolutionID(result.SolutionID)
		if err != nil {
			handleError(w, err)
			return
		}
		target := ""
		for _, f := range request.Features {
			if f.FeatureType == model.FeatureTypeTarget {
				target = f.FeatureName
				break
			}
		}

		explainURI := ""
		for _, e := range result.ExplainOutput {
			if e.Type == "step" {
				explainURI = e.URI
			}
		}

		clusterVarName := fmt.Sprintf("%s%s_shap", model.ClusterVarPrefix, target)
		datasetMeta, err := metaStorage.FetchDataset(result.Dataset, false, false, false)
		if err != nil {
			handleError(w, err)
			return
		}
		err = dataStorage.AddField(result.Dataset, fmt.Sprintf("%s_explain", datasetMeta.StorageName), clusterVarName, model.StringType, "")
		if err != nil {
			handleError(w, err)
			return
		}

		// cluster data
		_, clustered, err := task.ClusterExplainOutput(target, result.ResultURI, explainURI, &config)
		if err != nil {
			handleError(w, err)
			return
		}

		// build the data for batching
		clusteredData := make(map[string]string)
		for _, cluster := range clustered {
			clusteredData[cluster.D3MIndex] = cluster.Label
		}

		// update the batches
		// TODO: THIS HAS WAY TOO MUCH KNOWLEDGE OF THE DATABASE BAKED INTO IT
		filters := api.NewFilterParamsFromFilters([]*model.Filter{
			{Key: "result_id",
				Type:       model.CategoricalFilter,
				Categories: []string{result.ResultURI},
				Mode:       model.IncludeFilter,
			},
		})
		err = dataStorage.UpdateData(result.Dataset, fmt.Sprintf("%s_explain", datasetMeta.StorageName), clusterVarName, clusteredData, filters)
		if err != nil {
			handleError(w, err)
			return
		}

		// marshal output into JSON
		err = handleJSON(w, ClusteringResult{
			ClusterField: clusterVarName,
		})
		if err != nil {
			handleError(w, errors.Wrap(err, "unable marshal clustering result into JSON"))
			return
		}
	}
}

repository: uncharted-distil/distil

repo_name: uncharted-distil/distil

gha_language: Go


text:
SUMMARY = "Labrador first stage bootloader"

LICENSE = "CLOSED"

SRC_URI = " file://bootloader.bin"

inherit allarch deploy

ALLOW_EMPT_${PN} = "1"
do_compile[noexec] = "1"

do_deploy () {
	install -m 0755 ${WORKDIR}/bootloader.bin ${DEPLOYDIR}/
}

addtask deploy after do_compile

license: MIT

repository: bernardocrodrigues/meta-labrador

license_type: permissive

repo_name: bernardocrodrigues/meta-labrador

branch_name: refs/heads/main

extension: bb


text:
HOMEPAGE = "http://www.packagekit.org/"
DEPENDS = "libpam expat dbus-glib intltool-native"
LICENSE = "LGPLv2+"

PR = "r9"

SRC_URI = "http://hal.freedesktop.org/releases/PolicyKit-${PV}.tar.gz \
           file://PolicyKit.conf \
          "

EXTRA_OECONF = "--with-authfw=pam --with-os-type=moblin --disable-man-pages --disable-gtk-doc"

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

inherit autotools pkgconfig

do_install_append () {
	install -m 0644 ${WORKDIR}/PolicyKit.conf ${D}${sysconfdir}/PolicyKit/PolicyKit.conf
	install -d ${D}${localstatedir}/run/PolicyKit
}

FILES_${PN} += " ${datadir}/dbus-1 \
                 ${datadir}/PolicyKit \
                 ${localstatedir}/run/PolicyKit \
"

pkg_postinst_${PN} () {
    # can't do this offline
    if [ "x$D" != "x" ]; then
        exit 1
    fi
    grep "^polkituser:" /etc/group > /dev/null || addgroup polkituser
    grep "^polkituser:" /etc/passwd > /dev/null || adduser --disabled-password --system --home /var/run/polkit polkituser --ingroup polkituser -g polkituser

	echo "d root polkituser 0770 /var/run/PolicyKit none" > /etc/default/volatiles/98_policykit
	rm -f /etc/volatile.cache

	# Fix owners
	for i in /var/lib/PolicyKit /usr/libexec/polkit-read-auth-helper /usr/libexec/polkit-revoke-helper /usr/libexec/polkit-grant-helper /usr/libexec/polkit-explicit-grant-helper /usr/libexec/polkit-grant-helper-pam ; do
		chown root:polkituser $i
	done

	for i in /var/lib/PolicyKit-public /usr/libexec/polkit-set-default-helper ; do
		chown polkituser:root $i
	done

	chown polkituser:polkituser /var/lib/misc/PolicyKit.reload
	chown root:root /usr/libexec/polkit-resolve-exe-helper

	# Fix permissions
	for i in /var/run/PolicyKit /var/lib/PolicyKit ; do
		chmod 770 $i
	done

	chmod 755 /var/lib/PolicyKit-public
	chmod 775 /var/lib/misc/PolicyKit.reload

	for i in /usr/libexec/polkit-read-auth-helper /usr/libexec/polkit-revoke-helper /usr/libexec/polkit-grant-helper /usr/libexec/polkit-explicit-grant-helper ; do
		chmod 2755 $i
	done

	for i in /usr/libexec/polkit-set-default-helper /usr/libexec/polkit-resolve-exe-helper ; do
		chmod 4755 $i
	done

	chmod 4754 /usr/libexec/polkit-grant-helper-pam

	DBUSPID=`pidof dbus-daemon`
    if [ "x$DBUSPID" != "x" ]; then
        /etc/init.d/dbus-1 force-reload
    fi
}

pkg_postrm_${PN} () {
    deluser polkituser || true
    delgroup polkituser || true
	rm -f /etc/default/volatiles/98_policykit
    rm -f /etc/volatile.cache
}

SRC_URI[md5sum] = "802fd13ae41f73d79359e5ecb0a98716"
SRC_URI[sha256sum] = "f40c7c6bec19d7dba2335bddcffd0457494409a0dfce11d888c748dc892e80b7"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package inmemory

import (
	"context"
	"reflect"
	"testing"

	"github.com/dejaq/prototype/common/timeline"

	"github.com/dejaq/prototype/broker/pkg/overseer"
	"github.com/dejaq/prototype/broker/pkg/synchronization"
)

func createTopic(buckets uint16) (*Memory, error) {
	c := overseer.NewCatalog()
	ctx := context.Background()
	err := c.AddTopic(ctx, synchronization.Topic{Topic: timeline.Topic{
		ID: "id",
		Settings: timeline.TopicSettings{
			BucketCount: buckets,
		},
	}})

	if err != nil {
		return nil, err
	}
	return New(c), nil
}

func Test_TopicNames(t *testing.T) {
	m, err := createTopic(1)
	ctx := context.Background()
	if err != nil {
		t.Error(err)
	}
	err = m.CreateTopic(ctx, "id")
	if err != nil {
		t.Error(reflect.TypeOf(m), err)
	}
	// create same topic should fail
	err = m.CreateTopic(ctx, "id")
	if err == nil {
		t.Error(reflect.TypeOf(m), "expect error, got nil")
	}
	// empty topic ID should rise an error
	err = m.CreateTopic(ctx, "")
	if err == nil {
		t.Error(reflect.TypeOf(m), "expect error, got nil")
	}
}

func Test_TopicBuckets(t *testing.T) {
	m, err := createTopic(0)
	ctx := context.Background()
	if err != nil {
		t.Error(err)
	}
	// bucket count less than 1 should rise an error
	err = m.CreateTopic(ctx, "id")
	if err == nil {
		t.Error(reflect.TypeOf(m), "expect error, got nil")
	}
}

repository: dejaq/prototype

repo_name: dejaq/prototype

branch_name: refs/heads/master

extension: go


text:
SUMMARY = "Versatile Commodore Emulator"
HOMEPAGE = "http://vice-emu.sourceforge.net"
LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=c93c0550bd3173f4504b2cbd8991e50b"

# Sources for c64 software:
# [1] ftp://arnold.c64.org/pub/games/

SRC_URI = " \
    ${SOURCEFORGE_MIRROR}/vice-emu/${BPN}-${PV}.tar.gz \
    file://0001-Adjust-to-ffmpeg4.patch \
    file://c64_16.png \
    file://c64_32.png \
    file://c64_48.png \
    file://vice_64.desktop \
    file://vice_64dtv.desktop \
    file://vice_64sc.desktop \
"
SRC_URI[sha256sum] = "20df84c851aaf2f5000510927f6d31b32f269916d351465c366dc0afc9dc150c"

inherit autotools-brokensep pkgconfig gtk-icon-cache features_check

REQUIRED_DISTRO_FEATURES = "opengl x11"

DEPENDS = " \
    glib-2.0-native \
    bdftopcf-native \
    mkfontdir-native \
    mkfontscale-native \
    dos2unix-native \
    xa-native \
    bison-native \
    glew \
    gtk+3 \
    libsdl \
    libpng \
    jpeg \
    giflib \
    libxxf86vm \
    portaudio-v19 \
    mpg123 \
    virtual/libgl \
    vte9 \
    ffmpeg4 \
"

PACKAGECONFIG ??= "${@bb.utils.filter('DISTRO_FEATURES', 'pulseaudio', d)}"
PACKAGECONFIG[pulseaudio] = "--with-pulse,--without-pulse,pulseaudio,pulseaudio-server"

EXTRA_OECONF = " \
    --enable-external-ffmpeg \
    --enable-native-gtk3ui \
    --without-oss \
    --disable-pdf-docs \
    --libdir=${libdir} \
    --enable-x64 \
"

EXTRA_OECONF:remove = " \
    --disable-static \
"

CONFIGUREOPTS:remove = " \
    --disable-silent-rules \
    ${@append_libtool_sysroot(d)} \
"

export ar_check="no"

do_configure() {
    cd ${S}/src/resid
    echo "Configuring resid..."
    ACLOCAL="$ACLOCAL" autoreconf -Wcross -Wno-obsolete --verbose --install --force ${EXTRA_AUTORECONF} $acpaths || die "autoreconf execution failed."
    echo "Configuring resid done"
    cd ${S}
    rm -f ./configure
    ACLOCAL="$ACLOCAL" autoreconf -Wcross -Wno-obsolete --verbose --install --force ${EXTRA_AUTORECONF} $acpaths || die "autoreconf execution failed."
    oe_runconf
}

do_install:append() {
    install -d ${D}/${datadir}/applications
    install -m 0644 ${WORKDIR}/vice_64*.desktop ${D}/${datadir}/applications

    for size in 16 32 48; do
        install -d ${D}/${datadir}/icons/hicolor/${size}x${size}/apps
        install -m 0644 ${WORKDIR}/c64_${size}.png ${D}/${datadir}/icons/hicolor/${size}x${size}/apps/c64.png
    done
}

RDEPENDS:${PN} += "hicolor-icon-theme"

RREPLACES:${PN} += "vice-3.2"
RCONFLICTS:${PN} += "vice-3.2"

repository: schnitzeltony/meta-retro

repo_name: schnitzeltony/meta-retro


text:
//go:build kube
// +build kube

/*
   Copyright 2020 Docker Compose CLI 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 kube

import (
	"context"
	"fmt"
	"strings"

	"github.com/compose-spec/compose-go/types"
	"github.com/docker/compose/v2/pkg/api"
	"github.com/docker/compose/v2/pkg/progress"
	utils2 "github.com/docker/compose/v2/pkg/utils"

	apicontext "github.com/docker/compose-cli/api/context"
	"github.com/docker/compose-cli/api/context/store"
	"github.com/docker/compose-cli/kube/client"
	"github.com/docker/compose-cli/kube/helm"
	"github.com/docker/compose-cli/kube/resources"
	"github.com/docker/compose-cli/utils"
)

type composeService struct {
	sdk    *helm.Actions
	client *client.KubeClient
}

// NewComposeService create a kubernetes implementation of the api.Service API
func NewComposeService() (api.Service, error) {
	contextStore := store.Instance()
	currentContext := apicontext.Current()
	var kubeContext store.KubeContext

	if err := contextStore.GetEndpoint(currentContext, &kubeContext); err != nil {
		return nil, err
	}
	config, err := resources.LoadConfig(kubeContext)
	if err != nil {
		return nil, err
	}
	actions, err := helm.NewActions(config)
	if err != nil {
		return nil, err
	}
	apiClient, err := client.NewKubeClient(config)
	if err != nil {
		return nil, err
	}

	return &composeService{
		sdk:    actions,
		client: apiClient,
	}, nil
}

// Up executes the equivalent to a `compose up`
func (s *composeService) Up(ctx context.Context, project *types.Project, options api.UpOptions) error {
	if err := checkUnsupportedUpOptions(ctx, options); err != nil {
		return err
	}
	return progress.Run(ctx, func(ctx context.Context) error {
		return s.up(ctx, project)
	})
}

func checkUnsupportedUpOptions(ctx context.Context, o api.UpOptions) error {
	var errs error
	checks := []struct {
		toCheck, expected interface{}
		option            string
	}{
		{o.Create.Inherit, true, "renew-anon-volumes"},
		{o.Create.RemoveOrphans, false, "remove-orphans"},
		{o.Create.QuietPull, false, "quiet-pull"},
		{o.Create.Recreate, api.RecreateDiverged, "force-recreate"},
		{o.Create.RecreateDependencies, api.RecreateDiverged, "always-recreate-deps"},
		{len(o.Start.AttachTo), 0, "attach-dependencies"},
		{len(o.Start.ExitCodeFrom), 0, "exit-code-from"},
		{o.Create.Timeout, nil, "timeout"},
	}
	for _, c := range checks {
		errs = utils.CheckUnsupported(ctx, errs, c.toCheck, c.expected, "up", c.option)
	}
	return errs
}

func (s *composeService) up(ctx context.Context, project *types.Project) error {
	w := progress.ContextWriter(ctx)

	eventName := "Convert Compose file to Helm charts"
	w.Event(progress.CreatingEvent(eventName))

	chart, err := helm.GetChartInMemory(project)
	if err != nil {
		return err
	}
	w.Event(progress.NewEvent(eventName, progress.Done, ""))

	stack, err := s.sdk.Get(project.Name)
	if err != nil || stack == nil {
		// install stack
		eventName = "Install Compose stack"
		w.Event(progress.CreatingEvent(eventName))

		err = s.sdk.InstallChart(project.Name, chart, func(format string, v ...interface{}) {
			message := fmt.Sprintf(format, v...)
			w.Event(progress.NewEvent(eventName, progress.Done, message))
		})

	} else {
		// update stack
		eventName = "Updating Compose stack"
		w.Event(progress.CreatingEvent(eventName))

		err = s.sdk.UpdateChart(project.Name, chart, func(format string, v ...interface{}) {
			message := fmt.Sprintf(format, v...)
			w.Event(progress.NewEvent(eventName, progress.Done, message))
		})
	}
	if err != nil {
		return err
	}

	w.Event(progress.NewEvent(eventName, progress.Done, ""))

	return s.client.WaitForPodState(ctx, client.WaitForStatusOptions{
		ProjectName: project.Name,
		Services:    project.ServiceNames(),
		Status:      api.RUNNING,
		Log: func(pod string, stateReached bool, message string) {
			state := progress.Done
			if !stateReached {
				state = progress.Working
			}
			w.Event(progress.NewEvent(pod, state, message))
		},
	})
}

// Down executes the equivalent to a `compose down`
func (s *composeService) Down(ctx context.Context, projectName string, options api.DownOptions) error {
	if err := checkUnsupportedDownOptions(ctx, options); err != nil {
		return err
	}
	return progress.Run(ctx, func(ctx context.Context) error {
		return s.down(ctx, projectName, options)
	})
}

func checkUnsupportedDownOptions(ctx context.Context, o api.DownOptions) error {
	var errs error
	checks := []struct {
		toCheck, expected interface{}
		option            string
	}{
		{o.Volumes, false, "volumes"},
		{o.Images, "", "images"},
		{o.RemoveOrphans, false, "remove-orphans"},
	}
	for _, c := range checks {
		errs = utils.CheckUnsupported(ctx, errs, c.toCheck, c.expected, "down", c.option)
	}
	return errs
}

func (s *composeService) down(ctx context.Context, projectName string, options api.DownOptions) error {
	w := progress.ContextWriter(ctx)
	eventName := fmt.Sprintf("Remove %s", projectName)
	w.Event(progress.CreatingEvent(eventName))

	logger := func(format string, v ...interface{}) {
		message := fmt.Sprintf(format, v...)
		if strings.Contains(message, "Starting delete") {
			action := strings.Replace(message, "Starting delete for", "Delete", 1)

			w.Event(progress.CreatingEvent(action))
			w.Event(progress.NewEvent(action, progress.Done, ""))
			return
		}
		w.Event(progress.NewEvent(eventName, progress.Working, message))
	}
	err := s.sdk.Uninstall(projectName, logger)
	if err != nil {
		return err
	}

	events := []string{}
	err = s.client.WaitForPodState(ctx, client.WaitForStatusOptions{
		ProjectName: projectName,
		Services:    nil,
		Status:      api.REMOVING,
		Timeout:     options.Timeout,
		Log: func(pod string, stateReached bool, message string) {
			state := progress.Done
			if !stateReached {
				state = progress.Working
			}
			w.Event(progress.NewEvent(pod, state, message))
			if !utils2.StringContains(events, pod) {
				events = append(events, pod)
			}
		},
	})
	if err != nil {
		return err
	}
	for _, e := range events {
		w.Event(progress.NewEvent(e, progress.Done, ""))
	}
	w.Event(progress.NewEvent(eventName, progress.Done, ""))
	return nil
}

// List executes the equivalent to a `docker stack ls`
func (s *composeService) List(ctx context.Context, opts api.ListOptions) ([]api.Stack, error) {
	if err := checkUnsupportedListOptions(ctx, opts); err != nil {
		return nil, err
	}
	return s.sdk.ListReleases()
}

func checkUnsupportedListOptions(ctx context.Context, o api.ListOptions) error {
	return utils.CheckUnsupported(ctx, nil, o.All, false, "ls", "all")
}

// Build executes the equivalent to a `compose build`
func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
	return api.ErrNotImplemented
}

// Push executes the equivalent ot a `compose push`
func (s *composeService) Push(ctx context.Context, project *types.Project, options api.PushOptions) error {
	return api.ErrNotImplemented
}

// Pull executes the equivalent of a `compose pull`
func (s *composeService) Pull(ctx context.Context, project *types.Project, options api.PullOptions) error {
	return api.ErrNotImplemented
}

// Create executes the equivalent to a `compose create`
func (s *composeService) Create(ctx context.Context, project *types.Project, opts api.CreateOptions) error {
	return api.ErrNotImplemented
}

// Start executes the equivalent to a `compose start`
func (s *composeService) Start(ctx context.Context, project *types.Project, options api.StartOptions) error {
	return api.ErrNotImplemented
}

// Restart executes the equivalent to a `compose restart`
func (s *composeService) Restart(ctx context.Context, project *types.Project, options api.RestartOptions) error {
	return api.ErrNotImplemented
}

// Stop executes the equivalent to a `compose stop`
func (s *composeService) Stop(ctx context.Context, project *types.Project, options api.StopOptions) error {
	return api.ErrNotImplemented
}

// Copy copies a file/folder between a service container and the local filesystem
func (s *composeService) Copy(ctx context.Context, project *types.Project, options api.CopyOptions) error {
	return api.ErrNotImplemented
}

// Logs executes the equivalent to a `compose logs`
func (s *composeService) Logs(ctx context.Context, projectName string, consumer api.LogConsumer, options api.LogOptions) error {
	if err := checkUnsupportedLogOptions(ctx, options); err != nil {
		return err
	}
	if len(options.Services) > 0 {
		consumer = utils.FilteredLogConsumer(consumer, options.Services)
	}
	return s.client.GetLogs(ctx, projectName, consumer, options.Follow)
}

func checkUnsupportedLogOptions(ctx context.Context, o api.LogOptions) error {
	var errs error
	checks := []struct {
		toCheck, expected interface{}
		option            string
	}{
		{o.Since, "", "since"},
		{o.Timestamps, false, "timestamps"},
		{o.Until, "", "until"},
	}
	for _, c := range checks {
		errs = utils.CheckUnsupported(ctx, errs, c.toCheck, c.expected, "logs", c.option)
	}
	return errs
}

// Ps executes the equivalent to a `compose ps`
func (s *composeService) Ps(ctx context.Context, projectName string, options api.PsOptions) ([]api.ContainerSummary, error) {
	return s.client.GetContainers(ctx, projectName, options.All)
}

// Convert translate compose model into backend's native format
func (s *composeService) Convert(ctx context.Context, project *types.Project, options api.ConvertOptions) ([]byte, error) {
	chart, err := helm.GetChartInMemory(project)
	if err != nil {
		return nil, err
	}

	if options.Output != "" {
		_, err := helm.SaveChart(chart, options.Output)
		return nil, err
	}

	buff := []byte{}
	for _, f := range chart.Raw {
		header := "\n" + f.Name + "\n" + strings.Repeat("-", len(f.Name)) + "\n"
		buff = append(buff, []byte(header)...)
		buff = append(buff, f.Data...)
		buff = append(buff, []byte("\n")...)
	}
	return buff, nil
}

func (s *composeService) Kill(ctx context.Context, project *types.Project, options api.KillOptions) error {
	return api.ErrNotImplemented
}

// RunOneOffContainer creates a service oneoff container and starts its dependencies
func (s *composeService) RunOneOffContainer(ctx context.Context, project *types.Project, opts api.RunOptions) (int, error) {
	return 0, api.ErrNotImplemented
}

func (s *composeService) Remove(ctx context.Context, project *types.Project, options api.RemoveOptions) error {
	return api.ErrNotImplemented
}

// Exec executes a command in a running service container
func (s *composeService) Exec(ctx context.Context, project string, opts api.RunOptions) (int, error) {
	if err := checkUnsupportedExecOptions(ctx, opts); err != nil {
		return 0, err
	}
	return 0, s.client.Exec(ctx, project, opts)
}

func checkUnsupportedExecOptions(ctx context.Context, o api.RunOptions) error {
	var errs error
	errs = utils.CheckUnsupported(ctx, errs, o.Index, 0, "exec", "index")
	errs = utils.CheckUnsupported(ctx, errs, o.Privileged, false, "exec", "privileged")
	errs = utils.CheckUnsupported(ctx, errs, o.WorkingDir, "", "exec", "workdir")
	return errs
}

func (s *composeService) Pause(ctx context.Context, project string, options api.PauseOptions) error {
	return api.ErrNotImplemented
}

func (s *composeService) UnPause(ctx context.Context, project string, options api.PauseOptions) error {
	return api.ErrNotImplemented
}

func (s *composeService) Top(ctx context.Context, projectName string, services []string) ([]api.ContainerProcSummary, error) {
	return nil, api.ErrNotImplemented
}

func (s *composeService) Events(ctx context.Context, project string, options api.EventsOptions) error {
	return api.ErrNotImplemented
}

func (s *composeService) Port(ctx context.Context, project string, service string, port int, options api.PortOptions) (string, int, error) {
	return "", 0, api.ErrNotImplemented
}

func (s *composeService) Images(ctx context.Context, projectName string, options api.ImagesOptions) ([]api.ImageSummary, error) {
	return nil, api.ErrNotImplemented
}

repository: docker/compose-cli

repo_name: docker/compose-cli


text:
package service

import (
	"github.com/WeBankPartners/open-monitor/monitor-server/middleware"
	"github.com/WeBankPartners/open-monitor/monitor-server/services/db"
	"github.com/gin-gonic/gin"
)

func GetServiceGroupEndpointList(c *gin.Context)  {
	searchType := c.Param("searchType")
	result,err := db.GetServiceGroupEndpointList(searchType)
	if err != nil {
		middleware.ReturnHandleError(c, err.Error(), err)
	}else{
		middleware.ReturnSuccessData(c, result)
	}
}

func ListServiceGroupEndpoint(c *gin.Context)  {
	serviceGroup := c.Param("serviceGroup")
	monitorType := c.Param("monitorType")
	result,err := db.ListServiceGroupEndpoint(serviceGroup,monitorType)
	if err != nil {
		middleware.ReturnHandleError(c, err.Error(), err)
	}else{
		middleware.ReturnSuccessData(c, result)
	}
}

repository: WeBankPartners/open-monitor

repo_name: WeBankPartners/open-monitor


text:
# ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.
# ******************************************************************************

unset(SPHINX_EXECUTABLE)
unset(SPHINX_VERSION)

find_program(SPHINX_EXECUTABLE NAMES sphinx-build sphinx-build2 DOC "Path to sphinx-build executable")

if (SPHINX_EXECUTABLE)
    execute_process(COMMAND ${SPHINX_EXECUTABLE} --version
                    RESULT_VARIABLE __sphinx_result OUTPUT_VARIABLE __sphinx_output ERROR_VARIABLE __sphinx_error
                    OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_STRIP_TRAILING_WHITESPACE)
    if (__sphinx_result MATCHES 0)
        string(REGEX MATCH ".* ([0-9]+)\\.([0-9]+)\\.([0-9]+)" __sphinx_version_check "${__sphinx_error}")
        set(SPHINX_VERSION ${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3})
    else()
        set(__sphinx_output "${__sphinx_error}")
        message(WARNING "Sphinx: problem extracting version!")
    endif()
endif()

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Sphinx REQUIRED_VARS SPHINX_EXECUTABLE SPHINX_VERSION
                                  VERSION_VAR SPHINX_VERSION)

option(SPHINX_OUTPUT_HTML "Output standalone HTML files" ON)
option(SPHINX_OUTPUT_MAN "Output man pages" ON)
option(SPHINX_WARNINGS_AS_ERRORS "When building documentation treat warnings as errors" ON)

repository: NervanaSystems/aeon

repo_name: NervanaSystems/aeon

extension: cmake


text:
package telemetry

import (
	"errors"
	"regexp"
	"sync"

	logging "github.com/sirupsen/logrus"
)

// counters ...
// Holds the reference to the registered counters
var counters sync.Map

// CounterMetadata ...
// Holds the metadata of the counters
// Used during registration as middleware between the services and the prometheus
type CounterMetadata struct {
	Prefix string `mapstructure:"prefix"`
	Name   string `mapstructure:"name"`
	Help   string `mapstructure:"help"`
}

// Configuration ...
// A structure to read the config into
type Configuration struct {
	Metrics map[string]CounterMetadata `mapstructure:"metrics"`
}

// CreateAndRegister Creates a metric and registers it
func CreateAndRegister(countersMetadata []CounterMetadata) error {

	var (
		helpText   string
		errWrapper error // Wrap the errors occurred during the process
	)

	for i := range countersMetadata {

		// Validate the name before creating
		reg := regexp.MustCompile(`^[a-zA-Z0-9_]`)

		if !reg.MatchString(countersMetadata[i].Name) {
			if errWrapper == nil {
				errWrapper = errors.New("failed to create metric for " + countersMetadata[i].Name + " reason: invalid name... ")
			} else {
				errWrapper = errors.New(errWrapper.Error() + "failed to create metric for " + countersMetadata[i].Name + " reason: invalid name.... ")
			}

			continue
		}

		// Check if the counter is already registered
		_, ok := counters.Load(countersMetadata[i].Prefix + countersMetadata[i].Name)

		if ok {
			logging.WithField("telemetry: CreateAndRegister", countersMetadata[i].Name).WithError(errors.New("counter already exists")).Error("could not register")

			if errWrapper == nil {

				errWrapper = errors.New("failed to create metric for " + countersMetadata[i].Name + " reason: it already exists... ")
			} else {

				errWrapper = errors.New(errWrapper.Error() + "failed to create metric for " + countersMetadata[i].Name + " reason: it already exists.... ")
			}

			continue
		}

		// Check if the help text is provided
		// If not, add a default one
		if countersMetadata[i].Help == "" {
			helpText = "number of " + countersMetadata[i].Name
		} else {
			helpText = countersMetadata[i].Help
		}

		// Create a counter using the specified metadata
		counter := NewCounter(countersMetadata[i].Prefix+countersMetadata[i].Name, helpText)

		// Register the counter with prometheus
		err := Register(counter)
		if err != nil {
			logging.WithField("telemetry: CreateAndRegister", countersMetadata[i].Name).WithError(err).Error("could not register")

			if errWrapper == nil {
				errWrapper = errors.New("failed to create metric for " + countersMetadata[i].Name + " reason: " + err.Error() + "... ")
			} else {
				errWrapper = errors.New(errWrapper.Error() + "failed to create metric for " + countersMetadata[i].Name + " reason: " + err.Error() + ".... ")
			}

			continue
		}

		// Store the reference to the counter in the in-memory store
		counters.Store(countersMetadata[i].Prefix+countersMetadata[i].Name, counter)
	}

	return errWrapper
}

// IncrementCounter ...
// A public method which increments the counter for the specified counter name
func IncrementCounter(metricName, prefix string) {

	go incrementCounter(metricName, prefix)
}

func incrementCounter(metricName, prefix string) {

	name := prefix + metricName

	// Get the reference to the counter
	_, ok := counters.Load(name)

	if !ok {
		// Counter doesn't exist. Create and then increment
		logging.WithField("telemetry: IncrementCounter", name).Debug("could not find the counter. Creating ... ")

		counterMetadata := CounterMetadata{
			Prefix: prefix,
			Name:   metricName,
			Help:   "",
		}

		err := CreateAndRegister([]CounterMetadata{counterMetadata})

		if err != nil {
			logging.WithField("telemetry: IncrementCounter", name).WithError(err).Errorln("could not create the metric")
		}
	}

	value, _ := counters.Load(name)
	// Increment the counter
	counter, ok := value.(*Counter)

	if !ok {
		logging.WithField("telemetry: IncrementCounter", name).Errorln("error while casting interface{} to counter")
	} else {
		counter.Inc()
	}
}

repository: defiAnalysis/Solidity-Go

repo_name: defiAnalysis/Solidity-Go


text:
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.

package tracer

import (
	"strconv"
	"strings"

	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
	"gopkg.in/DataDog/dd-trace-go.v1/internal/globalconfig"
	"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
	"gopkg.in/DataDog/dd-trace-go.v1/internal/samplernames"
)

// SQLCommentInjectionMode represents the mode of SQL comment injection.
//
// Deprecated: Use DBMPropagationMode instead.
type SQLCommentInjectionMode DBMPropagationMode

const (
	// SQLInjectionUndefined represents the comment injection mode is not set. This is the same as SQLInjectionDisabled.
	SQLInjectionUndefined SQLCommentInjectionMode = SQLCommentInjectionMode(DBMPropagationModeUndefined)
	// SQLInjectionDisabled represents the comment injection mode where all injection is disabled.
	SQLInjectionDisabled SQLCommentInjectionMode = SQLCommentInjectionMode(DBMPropagationModeDisabled)
	// SQLInjectionModeService represents the comment injection mode where only service tags (name, env, version) are injected.
	SQLInjectionModeService SQLCommentInjectionMode = SQLCommentInjectionMode(DBMPropagationModeService)
	// SQLInjectionModeFull represents the comment injection mode where both service tags and tracing tags. Tracing tags include span id, trace id and sampling priority.
	SQLInjectionModeFull SQLCommentInjectionMode = SQLCommentInjectionMode(DBMPropagationModeFull)
)

// DBMPropagationMode represents the mode of dbm propagation.
//
// Note that enabling sql comment propagation results in potentially confidential data (service names)
// being stored in the databases which can then be accessed by other 3rd parties that have been granted
// access to the database.
type DBMPropagationMode string

const (
	// DBMPropagationModeUndefined represents the dbm propagation mode not being set. This is the same as DBMPropagationModeDisabled.
	DBMPropagationModeUndefined DBMPropagationMode = ""
	// DBMPropagationModeDisabled represents the dbm propagation mode where all propagation is disabled.
	DBMPropagationModeDisabled DBMPropagationMode = "disabled"
	// DBMPropagationModeService represents the dbm propagation mode where only service tags (name, env, version) are propagated to dbm.
	DBMPropagationModeService DBMPropagationMode = "service"
	// DBMPropagationModeFull represents the dbm propagation mode where both service tags and tracing tags are propagated. Tracing tags include span id, trace id and the sampled flag.
	DBMPropagationModeFull DBMPropagationMode = "full"
)

// Key names for SQL comment tags.
const (
	sqlCommentTraceParent   = "traceparent"
	sqlCommentParentService = "ddps"
	sqlCommentDBService     = "dddbs"
	sqlCommentParentVersion = "ddpv"
	sqlCommentEnv           = "dde"
)

// Current trace context version (see https://www.w3.org/TR/trace-context/#version)
const w3cContextVersion = "00"

// SQLCommentCarrier is a carrier implementation that injects a span context in a SQL query in the form
// of a sqlcommenter formatted comment prepended to the original query text.
// See https://google.github.io/sqlcommenter/spec/ for more details.
type SQLCommentCarrier struct {
	Query         string
	Mode          DBMPropagationMode
	DBServiceName string
	SpanID        uint64
}

// Inject injects a span context in the carrier's Query field as a comment.
func (c *SQLCommentCarrier) Inject(spanCtx ddtrace.SpanContext) error {
	c.SpanID = generateSpanID(now())
	tags := make(map[string]string)
	switch c.Mode {
	case DBMPropagationModeUndefined:
		fallthrough
	case DBMPropagationModeDisabled:
		return nil
	case DBMPropagationModeFull:
		var (
			sampled int64
			traceID uint64
		)
		if ctx, ok := spanCtx.(*spanContext); ok {
			if sp, ok := ctx.samplingPriority(); ok && sp > 0 {
				sampled = 1
			}
			traceID = ctx.TraceID()
		}
		if traceID == 0 { // check if this is a root span
			traceID = c.SpanID
		}
		tags[sqlCommentTraceParent] = encodeTraceParent(traceID, c.SpanID, sampled)
		fallthrough
	case DBMPropagationModeService:
		if ctx, ok := spanCtx.(*spanContext); ok {
			if e, ok := ctx.meta(ext.Environment); ok && e != "" {
				tags[sqlCommentEnv] = e
			}
			if v, ok := ctx.meta(ext.Version); ok && v != "" {
				tags[sqlCommentParentVersion] = v
			}
		}
		if globalconfig.ServiceName() != "" {
			tags[sqlCommentParentService] = globalconfig.ServiceName()
		}
		tags[sqlCommentDBService] = c.DBServiceName
	}
	c.Query = commentQuery(c.Query, tags)
	return nil
}

// encodeTraceParent encodes trace parent as per the w3c trace context spec (https://www.w3.org/TR/trace-context/#version).
func encodeTraceParent(traceID uint64, spanID uint64, sampled int64) string {
	var b strings.Builder
	// traceparent has a fixed length of 55:
	// 2 bytes for the version, 32 for the trace id, 16 for the span id, 2 for the sampled flag and 3 for separators
	b.Grow(55)
	b.WriteString(w3cContextVersion)
	b.WriteRune('-')
	tid := strconv.FormatUint(traceID, 16)
	for i := 0; i < 32-len(tid); i++ {
		b.WriteRune('0')
	}
	b.WriteString(tid)
	b.WriteRune('-')
	sid := strconv.FormatUint(spanID, 16)
	for i := 0; i < 16-len(sid); i++ {
		b.WriteRune('0')
	}
	b.WriteString(sid)
	b.WriteRune('-')
	b.WriteRune('0')
	b.WriteString(strconv.FormatInt(sampled, 16))
	return b.String()
}

var (
	keyReplacer   = strings.NewReplacer(" ", "%20", "!", "%21", "#", "%23", "$", "%24", "%", "%25", "&", "%26", "'", "%27", "(", "%28", ")", "%29", "*", "%2A", "+", "%2B", ",", "%2C", "/", "%2F", ":", "%3A", ";", "%3B", "=", "%3D", "?", "%3F", "@", "%40", "[", "%5B", "]", "%5D")
	valueReplacer = strings.NewReplacer(" ", "%20", "!", "%21", "#", "%23", "$", "%24", "%", "%25", "&", "%26", "'", "%27", "(", "%28", ")", "%29", "*", "%2A", "+", "%2B", ",", "%2C", "/", "%2F", ":", "%3A", ";", "%3B", "=", "%3D", "?", "%3F", "@", "%40", "[", "%5B", "]", "%5D", "'", "\\'")
)

// commentQuery returns the given query with the tags from the SQLCommentCarrier applied to it as a
// prepended SQL comment. The format of the comment follows the sqlcommenter spec.
// See https://google.github.io/sqlcommenter/spec/ for more details.
func commentQuery(query string, tags map[string]string) string {
	if len(tags) == 0 {
		return ""
	}
	var b strings.Builder
	// the sqlcommenter specification dictates that tags should be sorted. Since we know all injected keys,
	// we skip a sorting operation by specifying the order of keys statically
	orderedKeys := []string{sqlCommentDBService, sqlCommentEnv, sqlCommentParentService, sqlCommentParentVersion, sqlCommentTraceParent}
	first := true
	for _, k := range orderedKeys {
		if v, ok := tags[k]; ok {
			// we need to URL-encode both keys and values and escape single quotes in values
			// https://google.github.io/sqlcommenter/spec/
			key := keyReplacer.Replace(k)
			val := valueReplacer.Replace(v)
			if first {
				b.WriteString("/*")
			} else {
				b.WriteRune(',')
			}
			b.WriteString(key)
			b.WriteRune('=')
			b.WriteRune('\'')
			b.WriteString(val)
			b.WriteRune('\'')
			first = false
		}
	}
	if b.Len() == 0 {
		return query
	}
	b.WriteString("*/")
	if query == "" {
		return b.String()
	}
	log.Debug("Injected sql comment: %s", b.String())
	b.WriteRune(' ')
	b.WriteString(query)
	return b.String()
}

// Extract parses for key value attributes in a sql query injected with trace information in order to build a span context
func (c *SQLCommentCarrier) Extract() (ddtrace.SpanContext, error) {
	var ctx *spanContext
	// There may be multiple comments within the sql query, so we must identify which one contains trace information.
	// We look at each comment until we find one that contains a traceparent
	if traceComment, found := findTraceComment(c.Query); found {
		var err error
		if ctx, err = spanContextFromTraceComment(traceComment); err != nil {
			return nil, err
		}
	} else {
		return nil, ErrSpanContextNotFound
	}
	if ctx.traceID.Empty() || ctx.spanID == 0 {
		return nil, ErrSpanContextNotFound
	}
	return ctx, nil
}

// spanContextFromTraceComment looks for specific kv pairs in a comment containing trace information.
// It returns a span context with the appropriate attributes
func spanContextFromTraceComment(c string) (*spanContext, error) {
	var ctx spanContext
	kvs := strings.Split(c, ",")
	for _, unparsedKV := range kvs {
		splitKV := strings.Split(unparsedKV, "=")
		if len(splitKV) != 2 {
			return nil, ErrSpanContextCorrupted
		}
		key := splitKV[0]
		value := strings.Trim(splitKV[1], "'")
		switch key {
		case sqlCommentTraceParent:
			traceIDLower, traceIDUpper, spanID, sampled, err := decodeTraceParent(value)
			if err != nil {
				return nil, err
			}
			ctx.traceID.SetLower(traceIDLower)
			ctx.traceID.SetUpper(traceIDUpper)
			ctx.spanID = spanID
			ctx.setSamplingPriority(sampled, samplernames.Unknown)
		default:
		}
	}
	return &ctx, nil
}

// decodeTraceParent decodes trace parent as per the w3c trace context spec (https://www.w3.org/TR/trace-context/#version).
// this also supports decoding traceparents from open telemetry sql comments which are 128 bit
func decodeTraceParent(traceParent string) (traceIDLower uint64, traceIDUpper uint64, spanID uint64, sampled int, err error) {
	if len(traceParent) < 55 {
		return 0, 0, 0, 0, ErrSpanContextCorrupted
	}
	version := traceParent[0:2]
	switch version {
	case w3cContextVersion:
		if traceIDUpper, err = strconv.ParseUint(traceParent[3:19], 16, 64); err != nil {
			return 0, 0, 0, 0, ErrSpanContextCorrupted
		}
		if traceIDLower, err = strconv.ParseUint(traceParent[19:35], 16, 64); err != nil {
			return 0, 0, 0, 0, ErrSpanContextCorrupted
		}
		if spanID, err = strconv.ParseUint(traceParent[36:52], 16, 64); err != nil {
			return 0, 0, 0, 0, ErrSpanContextCorrupted
		}
		if sampled, err = strconv.Atoi(traceParent[53:55]); err != nil {
			return 0, 0, 0, 0, ErrSpanContextCorrupted
		}
	default:
	}
	return traceIDLower, traceIDUpper, spanID, sampled, err
}

// findTraceComment looks for a sql comment that contains trace information by looking for the keyword traceparent
func findTraceComment(query string) (traceComment string, found bool) {
	startIndex := -1
	containsTrace := false
	keyLength := len(sqlCommentTraceParent)
	qLength := len(query)
	for i := 0; i < qLength-1; {
		if query[i] == '/' && query[i+1] == '*' {
			// look for leading /*
			startIndex = i
			i += 2
			containsTrace = false
		} else if query[i] == '*' && query[i+1] == '/' {
			// look for closing */
			if startIndex == -1 {
				// malformed comment, it did not have a leading /*
				return "", false
			}
			if !containsTrace {
				// ignore this comment, it was not a trace comment
				startIndex = -1
				i += 2
			} else {
				// do not return the query with the leading /* or trailing */
				return query[startIndex+2 : i], true
			}
		} else if !containsTrace && i+keyLength < qLength && query[i:i+keyLength] == sqlCommentTraceParent {
			// look for occurrence of keyword in the query if not yet found and make sure we don't go out of range
			containsTrace = true
			i += keyLength
		} else {
			i++
		}
	}
	return "", false
}

repository: DataDog/dd-trace-go

repo_name: DataDog/dd-trace-go

gha_license_id: NOASSERTION


text:
SUMMARY = "NVMe management command line interface"
AUTHOR = "Stefan Wiehler <stefan.wiehler@missinglinkelectronics.com>"
HOMEPAGE = "https://github.com/linux-nvme/nvme-cli"
SECTION = "console/utils"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://LICENSE;md5=8264535c0c4e9c6c335635c4026a8022"
DEPENDS = "util-linux"
PV .= "+git${SRCPV}"

SRC_URI = "git://github.com/linux-nvme/nvme-cli.git;branch=master;protocol=https"
SRCREV = "f0e9569df9289d6ee55ba2c23615cc7c73a9b088"

S = "${WORKDIR}/git"

inherit bash-completion systemd

do_install() {
    oe_runmake install-spec DESTDIR=${D} PREFIX=${prefix} \
        UDEVDIR=${nonarch_base_libdir}/udev SYSTEMDDIR=${systemd_unitdir}
}

pkg_postinst_ontarget_${PN}() {
    ${sbindir}/nvme gen-hostnqn > ${sysconfdir}/nvme/hostnqn
    ${bindir}/uuidgen > ${sysconfdir}/nvme/hostid
}

PACKAGES =+ "${PN}-dracut ${PN}-zsh-completion"

FILES_${PN} += "${systemd_system_unitdir}"
FILES_${PN}-dracut = "${nonarch_libdir}/dracut/dracut.conf.d"
FILES_${PN}-zsh-completion = "${datadir}/zsh/site-functions"

RDEPENDS_${PN} = "util-linux-uuidgen"

repository: ni/meta-openembedded

repo_name: ni/meta-openembedded

branch_name: refs/heads/nilrt/master/hardknott

gha_license_id: MIT

gha_language: BitBake


text:
# Copyright (c) 2019 Christophe Chapuis <chris.chapuis@gmail.com>

DESCRIPTION = "Library of glib utilities."
LICENSE = "BSD-3-Clause"
SECTION = "webos/support"
LIC_FILES_CHKSUM = "file://src/gutil_log.c;beginline=1;endline=31;md5=c476c5938ec00208b29c1c1743b4a006"

DEPENDS = "glib-2.0"

inherit pkgconfig

SRC_URI = "git://git.merproject.org/mer-core/libglibutil.git"
S = "${WORKDIR}/git"

PV = "1.0.39-1+git${SRCPV}"
SRCREV = "3a2b50ed08addd0eb75fa1f8534c9ba208f34ace"

EXTRA_OEMAKE = "KEEP_SYMBOLS=1"
PARALLEL_MAKE = ""

do_install() {
    make install DESTDIR=${D}
    make install-dev DESTDIR=${D}
}

branch_name: refs/heads/zeus


text:
package main

import (
	"context"
	"time"

	"github.com/Akagi201/cryptotrader/allcoin"
	"github.com/Akagi201/cryptotrader/bigone"
	"github.com/Akagi201/cryptotrader/binance"
	"github.com/Akagi201/cryptotrader/bitfinex"
	"github.com/Akagi201/cryptotrader/bitflyer"
	"github.com/Akagi201/cryptotrader/bittrex"
	"github.com/Akagi201/cryptotrader/cex"
	"github.com/Akagi201/cryptotrader/coincheck"
	"github.com/Akagi201/cryptotrader/coinegg"
	"github.com/Akagi201/cryptotrader/eosforce"
	"github.com/Akagi201/cryptotrader/etherscan"
	"github.com/Akagi201/cryptotrader/fixer"
	"github.com/Akagi201/cryptotrader/gateio"
	"github.com/Akagi201/cryptotrader/huobi"
	"github.com/Akagi201/cryptotrader/lbank"
	"github.com/Akagi201/cryptotrader/liqui"
	"github.com/Akagi201/cryptotrader/okcoin"
	"github.com/Akagi201/cryptotrader/okex"
	"github.com/Akagi201/cryptotrader/poloniex"
	"github.com/Akagi201/cryptotrader/util"
	"github.com/Akagi201/cryptotrader/zb"
	"github.com/davecgh/go-spew/spew"
	log "github.com/sirupsen/logrus"
)

func main() {
	if false {
		// zb
		api := zb.New("", "")

		ticker, err := api.GetTicker("btc", "eth")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)

		orderBook, err := api.GetOrderBook("btc", "eth", 3, 0.1)
		if err != nil {
			log.Errorf("Get orderbook failed, err: %v", err)
		}

		orderBookStr := spew.Sdump(orderBook)
		log.Infof("Get orderbook: %+v", orderBookStr)

		trades, err := api.GetTrades("btc", "eth", 0)
		if err != nil {
			log.Errorf("Get trades failed, err: %v", err)
		}

		tradesStr := spew.Sdump(trades)
		log.Infof("Get trades: %v", tradesStr)

		kline, err := api.GetRecords("btc", "eth", "1min", 0, 0)
		if err != nil {
			log.Errorf("Get kline failed, err: %v", err)
		}

		klineStr := spew.Sdump(kline)
		log.Infof("Get kline: %v", klineStr)

		ethAddr, err := api.GetUserAddress("eth")
		if err != nil {
			log.Errorf("Get UserAddress failed, err: %v", err)
		}

		log.Infof("Get eth addr: %v", ethAddr)
	}

	if false {
		// huobi
		api := huobi.New("", "")
		ticker, err := api.GetTicker("btc", "eth")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// cex
		api := cex.New("", "")
		omgTicker, err := api.GetTicker("btc", "omg")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get OMG ticker: %+v", omgTicker)

		payTicker, err := api.GetTicker("btc", "pay")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get PAY ticker: %+v", payTicker)
	}

	if false {
		// okcoin
		api := okcoin.New("", "")

		ticker, err := api.GetTicker("btc", "eth")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)

	}

	if false {
		// bittrex
		api := bittrex.New("", "")

		ticker, err := api.GetTicker("eth", "storj")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// liqui
		api := liqui.New("", "")

		ticker, err := api.GetTicker("eth", "zrx")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// etherscan
		api := etherscan.New("")

		balance, err := api.GetBalance("0x258ce53268BEaA9BA97fA6b7790d7555ae4044fc")
		if err != nil {
			log.Errorf("Get balance failed, err: %v", err)
		}

		log.Infof("Get balance: %v", balance)

		block, err := api.GetBlockNumber()

		if err != nil {
			log.Errorf("Get block number failed, err: %v", err)
		}

		log.Infof("Get block number: %v", block)
	}

	if false {
		// fixer
		api := fixer.New()

		rate, err := api.GetRate("USD", "btc")
		if err != nil {
			log.Errorf("Get rate failed, err: %v", err)
		}

		log.Infof("Get rate: %v", rate)
	}

	if false {
		// poloniex
		api := poloniex.New("", "")

		ticker, err := api.GetTicker("btc", "eth")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// lbank
		api := lbank.New("", "")

		ticker, err := api.GetTicker("btc", "btc")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// coinegg
		api := coinegg.New("", "")

		ticker, err := api.GetTicker("btc", "btc")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// allcoin
		api := allcoin.New("", "")

		ticker, err := api.GetTicker("usd", "btc")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// bitfinex
		api := bitfinex.New("", "")

		ticker, err := api.GetTicker("usd", "btc")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// coincheck
		api := coincheck.New("", "")

		ticker, err := api.GetTicker("jpy", "btc")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// bitflyer
		api := bitflyer.New("", "")

		ticker, err := api.GetTicker("jpy", "btc")
		if err != nil {
			log.Errorf("Get ticker failed, err: %v", err)
		}

		log.Infof("Get ticker: %+v", ticker)
	}

	if false {
		// binance
		rc := binance.New("xBhrsdymp92w3yTIf20x2TOs39fyyCM4TgeJCtbKuWQe1Rx2nCh2y6rDl1G5u5Th", "bC08CbIl5wBfVYJgrGkYgSl8dJ6JXVoqT57uLTstYyOj9ZUwo8r3dejHdonToiVw")

		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()

		if false {
			ethTicker, err := rc.GetTicker(ctx, "eth", "btc")
			if err != nil {
				log.Fatalf("Binance get ETH-BTC ticker failed, err: %v", err)
			}

			log.Infof("ETH-BTC Ticker: %+v", ethTicker)
		}

		if false {
			tickers, err := rc.GetTickers(ctx)
			if err != nil {
				log.Fatalf("Get tickers failed, err: %v", err)
			}

			log.Infof("Get tickers: %+v", tickers)
		}

		if false {
			err := rc.Ping(ctx)
			if err != nil {
				log.Fatalf("Binance ping failed, err: %v", err)
			}

			log.Infoln("Binance Ping success")
		}

		if false {
			serverTime, err := rc.GetTime(ctx)
			if err != nil {
				log.Fatalf("Binance get time failed, err: %v", err)
			}

			log.Infof("Binance Server time: %v", serverTime)
		}

		if false {
			nulsDepth, err := rc.GetDepth(ctx, "nuls", "btc", 0)
			if err != nil {
				log.Fatalf("Get NULS depth failed, err: %v", err)
			}

			log.Infof("Get NULS Depth: %+v", nulsDepth)
			for i, v := range nulsDepth.Asks[:5] {
				log.Infof("ask orderbook, %v: %v: %v", i, v.Price, v.Amount)
			}
			for i, v := range nulsDepth.Bids[:5] {
				log.Infof("bids orderbook, %v: %v: %v", i, v.Price, v.Amount)
			}
		}

		if false {
			nulsTrades, err := rc.GetTrades(ctx, "nuls", "btc", 0, 0, 0, 0)
			if err != nil {
				log.Fatalf("Get NULS trades failed, err: %v", err)
			}

			log.Infof("Get NULS trades: %+v, len: %v", nulsTrades[:5], len(nulsTrades))
			for i, v := range nulsTrades[len(nulsTrades)-5:] {
				log.Infof("index: %v, price: %v, amount: %v", i, v.Price, v.Amount)
			}
		}

		if false {
			zrxRecords, err := rc.GetRecords(ctx, "zrx", "btc", "1m", 0, 0, 0)
			if err != nil {
				log.Fatalf("Get ZRX records failed, err: %v", err)
			}

			log.Infof("Get ZRX records: %+v", zrxRecords)
		}

		if false {
			bookTickers, err := rc.GetBookTickers(ctx)
			if err != nil {
				log.Fatalf("Get book tickers failed, err: %v", err)
			}

			log.Infof("Get book tickers: %+v", bookTickers)
		}

		{
			account, err := rc.GetAccount(ctx, 0)
			if err != nil {
				log.Fatalf("Get account failed, err: %v", err)
			}
			account = util.GetNonZeroBalance(account)

			log.Infof("Get account: %+v", account)
		}

		if false {
			tradeID, err := rc.Trade(ctx, "zrx", "btc", "BUY", "LIMIT", "GTC", 1, 0.02, 0, 0, 0)
			if err != nil {
				log.Fatalf("Trade ZRX_BTC failed, err: %v", err)
			}

			log.Infof("Trade ZRX_BTC ID: %v", tradeID)
		}

		if false {
			order, err := rc.GetOrder(ctx, "zrx", "btc", 0, 0)
			if err != nil {
				log.Fatalf("Get ZRX_BTC order failed, err: %v", err)
			}

			log.Infof("Get ZRX_BTC order: %+v", order)
		}

		if false {
			err := rc.CancelOrder(ctx, "zrx", "btc", 0, 0)
			if err != nil {
				log.Fatalf("Cancel ZRX_BTC order failed, err: %v", err)
			}

			log.Infof("Cancel ZRX_BTC order success")
		}

		if false {
			orders, err := rc.GetOrders(ctx, "zrx", "btc", 0)
			if err != nil {
				log.Fatalf("Get ZRX_BTC orders failed, err: %v", err)
			}

			log.Infof("Get ZRX_BTC orders: %+v", orders)
		}

		if false {
			orders, err := rc.GetAllOrders(ctx, "zrx", "btc", 0, 0, 0)
			if err != nil {
				log.Fatalf("Get all ZRX_BTC orders failed, err: %v", err)
			}

			log.Infof("Get all ZRX_BTC orders: %+v", orders)
		}

		if false {
			zrxTrades, err := rc.GetMyTrades(ctx, "dnt", "btc", 0, 0, 0)
			if err != nil {
				log.Fatalf("Get my ZRX trades failed, err: %v", err)
			}

			log.Infof("Get my ZRX trades: %+v", zrxTrades)
		}
	}

	if false {
		// OKEX
		c := okex.New("", "")

		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()

		if false {
			ethTicker, err := c.GetTicker(ctx, "eth", "btc")
			if err != nil {
				log.Fatalf("OKEX get eth-btc ticker failed, err: %v", err)
			}

			log.Infof("OKEX ETH-BTC Ticker: %+v", ethTicker)
		}

		if false {
			ethDepth, err := c.GetDepth(ctx, "eth", "btc")
			if err != nil {
				log.Fatalf("OKEX get eth-btc depth failed, err: %v", err)
			}

			log.Infof("OKEX ETH-BTC depth: %+v", ethDepth)
		}

		if false {
			ethTrades, err := c.GetTrades(ctx, "eth", "btc")
			if err != nil {
				log.Fatalf("OKEX get eth-btc trades failed, err: %v", err)
			}

			log.Infof("OKEX ETH-BTC trades: %+v", ethTrades)
		}

		if false {
			ethKline, err := c.GetRecords(ctx, "eth", "btc", "1min", 0, 0)
			if err != nil {
				log.Fatalf("OKEX get eth-btc kline failed, err: %v", err)
			}

			log.Infof("OKEX ETH-BTC kline: %+v", ethKline)
		}

		{
			balance, err := c.GetAccount(ctx)
			if err != nil {
				log.Fatalf("OKEX get balance failed, err: %v", err)
			}
			log.Infof("OKEX balance: %+v", balance)
		}
	}

	if false {
		// gate.io
		c := gateio.New("", "")
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()

		if false {
			pairs, err := c.GetPairs(ctx)
			if err != nil {
				log.Fatalf("gate.io get pairs failed, err: %v", err)
			}

			log.Infof("gate.io pairs: %+v", pairs)
		}

		if false {
			marketInfo, err := c.GetMarketInfo(ctx)
			if err != nil {
				log.Fatalf("gate.io get market_info failed, err: %v", err)
			}

			log.Infof("gate.io market_info: %+v", marketInfo)
		}

		{
			ethTicker, err := c.GetTicker(ctx, "eth", "btc")
			if err != nil {
				log.Fatalf("gate.io get ticker failed, err: %v", err)
			}

			log.Infof("gate.io get ticker eth-btc: %+v", ethTicker)
		}
	}

	if false {
		// big.one
		c := bigone.New("")
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()

		if false {
			ethTicker, err := c.GetTicker(ctx, "eth", "btc")
			if err != nil {
				log.Fatalf("big.one get ticker failed, err: %v", err)
			}

			log.Infof("big.one get ticker eth-btc: %+v", ethTicker)
		}

		if false {
			ethBook, err := c.GetDepth(ctx, "eth", "btc")
			if err != nil {
				log.Fatalf("big.one get eth-btc depth failed, err: %v", err)
			}

			log.Infof("big.one get depth eth-btc: %+v", ethBook)
		}

		if false {
			ethTrade, err := c.GetTrades(ctx, "eth", "btc")
			if err != nil {
				log.Fatalf("big.one get eth-btc trade failed, err: %v", err)
			}

			log.Infof("big.one get trade eth-btc: %+v", ethTrade)
		}

		if false {
			id, err := c.Trade(ctx, "eth", "btc", "BID", 0.1, 0.04)
			if err != nil {
				log.Fatalf("big.one trade eth-btc failed, err: %v", err)
			}
			log.Infof("big.one trade eth-btc success, order id: %v", id)

			order, err := c.GetOrder(ctx, "eth", "btc", id)
			if err != nil {
				log.Fatalf("big.one get order eth-btc failed, err: %v", err)
			}
			log.Infof("big.one get order eth-btc success, order id: %v", order)

			orders, err := c.GetOrders(ctx, "eth", "btc", 10)
			if err != nil {
				log.Fatalf("big.one get orders eth-btc failed, err: %v", err)
			}
			log.Infof("big.one get orders eth-btc success, orders: %+v", orders)

			err = c.CancelOrder(ctx, "eth", "btc", id)
			if err != nil {
				log.Fatalf("big.one cancel order eth-btc failed, err: %v", err)
			}
			log.Info("big.one cancel order eth-btc success")
		}

		if false {
			balance, err := c.GetAccount(ctx)
			if err != nil {
				log.Fatalf("big.one get balance failed, err: %v", err)
			}
			log.Infof("big.one get balance: %+v", balance)
		}
	}

	{
		c := eosforce.New([]string{"docker", "exec", "eosforce", "cleos"}, "https", "w2.eosforce.cn")
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()

		{
			available, err := c.GetAvailable(ctx, "blockgw")
			if err != nil {
				log.Fatalf("eosforce get available balance failed, err: %v", err)
			}

			log.Infof("eosforce available balance: %+v", available)
		}

		{
			staked, err := c.GetStaked(ctx, "kuso", "blockgw")
			if err != nil {
				log.Fatalf("eosforce get staked balance failed, err: %v", err)
			}

			log.Infof("eosforce staked balance: %+v", staked)
		}

		{
			staked, err := c.GetUnstaking(ctx, "kuso", "blockgw")
			if err != nil {
				log.Fatalf("eosforce get unstaking balance failed, err: %v", err)
			}

			log.Infof("eosforce unstaking balance: %+v", staked)
		}

		{
			reward, err := c.GetRewards(ctx, "kuso", "blockgw")
			if err != nil {
				log.Fatalf("eosforce get reward balance failed, err: %v", err)
			}

			log.Infof("eosforce reward balance: %+v", reward)
		}
	}
}

repository: beaquant/cryptotrader

repo_name: beaquant/cryptotrader


text:
SUMMARY = "Remote delta-compression library."
AUTHOR = "Martin Pool, Andrew Tridgell, Donovan Baarda, Adam Schubert"

LICENSE = "LGPL-2.1-or-later"
LIC_FILES_CHKSUM = "file://COPYING;md5=d8045f3b8f929c1cb29a1e3fd737b499"

SRC_URI = "git://github.com/librsync/librsync.git;branch=master;protocol=https"
SRCREV = "e364852674780e43d578e4239128ff7014190ed3"
S = "${WORKDIR}/git"

DEPENDS = "popt"

inherit cmake

PACKAGES =+ "rdiff"
FILES:rdiff = "${bindir}/rdiff"

BBCLASSEXTEND = "native nativesdk"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded


text:
// The main package for the svc-profile executable.
package main

import (
	log "github.com/sirupsen/logrus"

	"github.com/gomeet-examples/svc-profile/cmd"
)

// Main manages command execution
func main() {
	err := cmd.RootCmd.Execute()
	if err != nil {
		log.Fatal(err)
	}
}

repository: gomeet-examples/svc-profile

repo_name: gomeet-examples/svc-profile


text:
cmake_minimum_required(VERSION 3.15)
include(FetchContent)
FetchContent_Declare(fetch-eigen3
        URL      https://gitlab.com/libeigen/eigen/-/archive/3.4-rc1/eigen-3.4-rc1.tar.gz
        URL_MD5  0839b9721e65d2328fb96eb4290d74cc
        QUIET
        CMAKE_ARGS
        -DEIGEN_TEST_CXX11:BOOL=ON
        -DBUILD_TESTING:BOOL=OFF
        -DEIGEN_BUILD_DOC:BOOL=OFF
        -DEIGEN_BUILD_PKGCONFIG:BOOL=OFF
        )
if(NOT TARGET Eigen3::Eigen)
    FetchContent_MakeAvailable(fetch-eigen3) # Avoid needless configure on header only library
    if(NOT TARGET Eigen3::Eigen AND TARGET eigen)
        add_library(Eigen3::Eigen ALIAS eigen)
    endif()
endif()


text:
package oauth

import (
	"time"

	"github.com/authgear/authgear-server/pkg/api/model"
	"github.com/authgear/authgear-server/pkg/lib/session"
	"github.com/authgear/authgear-server/pkg/lib/session/access"
)

type OfflineGrant struct {
	AppID           string                 `json:"app_id"`
	ID              string                 `json:"id"`
	Labels          map[string]interface{} `json:"labels"`
	ClientID        string                 `json:"client_id"`
	AuthorizationID string                 `json:"authz_id"`

	CreatedAt time.Time `json:"created_at"`
	ExpireAt  time.Time `json:"expire_at"`
	Scopes    []string  `json:"scopes"`
	TokenHash string    `json:"token_hash"`

	Attrs      session.Attrs `json:"attrs"`
	AccessInfo access.Info   `json:"access_info"`
}

var _ Grant = &OfflineGrant{}

func (g *OfflineGrant) Session() (kind GrantSessionKind, id string) {
	return GrantSessionKindOffline, g.ID
}

func (g *OfflineGrant) SessionID() string            { return g.ID }
func (g *OfflineGrant) SessionType() session.Type    { return session.TypeOfflineGrant }
func (g *OfflineGrant) SessionAttrs() *session.Attrs { return &g.Attrs }

func (g *OfflineGrant) GetCreatedAt() time.Time     { return g.CreatedAt }
func (g *OfflineGrant) GetClientID() string         { return g.ClientID }
func (g *OfflineGrant) GetAccessInfo() *access.Info { return &g.AccessInfo }

func (g *OfflineGrant) ToAPIModel() *model.Session {
	ua := model.ParseUserAgent(g.AccessInfo.LastAccess.UserAgent)
	amr, _ := g.Attrs.GetAMR()
	acr, _ := g.Attrs.GetACR()
	return &model.Session{
		Meta: model.Meta{
			ID:        g.ID,
			CreatedAt: g.CreatedAt,
			// TODO(session): Session Updated At should be the time user actively updates it.
			UpdatedAt: g.AccessInfo.LastAccess.Timestamp,
		},
		Type: model.SessionTypeOfflineGrant,

		AMR: amr,
		ACR: acr,

		LastAccessedAt:   g.AccessInfo.LastAccess.Timestamp,
		CreatedByIP:      g.AccessInfo.InitialAccess.RemoteIP,
		LastAccessedByIP: g.AccessInfo.LastAccess.RemoteIP,
		UserAgent:        ua,
	}
}

repository: cychiuae/authgear-server

repo_name: cychiuae/authgear-server


text:
package main

import (
	"fmt"
	"github.com/L11R/go-chatwars-api"
	"github.com/arangodb/go-driver"
	"github.com/labstack/echo"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/gommon/log"
	"net/http"
	"sort"
	"time"
)

func Index(c echo.Context) error {
	sess, _ := session.Get("user", c)

	var user user
	if id, found := sess.Values["id"]; found {
		_, err := usersCol.ReadDocument(nil, fmt.Sprint(id), &user)
		if err != nil {
			return echo.ErrNotFound
		}
	}

	type extendedItem struct {
		equipmentItem
		Recipe        []basic
		Basics        []basic
		Purchases     []basic
		Commands      []command
		TotalManaCost int
		ShowUserData  bool
	}

	var extItems []extendedItem

	for _, e := range equipment {
		basics := RecurBasics(e.Recipe)
		basics = FoldBasics(basics)

		commands := RecurCommands(e.Recipe)
		commands = FoldCommands(commands)

		// make recipe to add user amount field
		var recipe []basic
		for name, amount := range e.Recipe {
			if userAmount, found := user.Stock[name]; found {
				recipe = append(recipe, basic{
					Name:       name,
					Amount:     amount,
					UserAmount: userAmount,
				})
			} else {
				recipe = append(recipe, basic{
					Name:   name,
					Amount: amount,
				})
			}
		}

		var purchases []basic

		showUserData := false
		if user.ID != "" {
			showUserData = true

			// add user amount to basics
			for name, amount := range user.Stock {
				for i := range basics {
					if basics[i].Name == name {
						basics[i].UserAmount = amount
					}
				}
			}

			purchases = RecurPurchases(e.Recipe, user.Stock)
			purchases = FoldPurchases(purchases)

			commands = RecurUserCommands(e.Recipe, user.Stock)
			commands = FoldCommands(commands)
		}

		// add craft itself
		commands = append(commands, command{
			e.ID,
			e.Name,
			1,
			e.ManaCost,
		})

		extItem := extendedItem{
			e,
			recipe,
			basics,
			purchases,
			commands,
			0,
			showUserData,
		}

		// count total mana cost
		for _, c := range commands {
			extItem.TotalManaCost += c.CommandManaCost
		}

		// Sort recipe and basics to fix it
		sort.Slice(extItem.Recipe, func(i, j int) bool { return extItem.Recipe[i].Name < extItem.Recipe[j].Name })
		sort.Slice(extItem.Basics, func(i, j int) bool { return extItem.Basics[i].Name < extItem.Basics[j].Name })
		sort.Slice(extItem.Purchases, func(i, j int) bool { return extItem.Purchases[i].Name < extItem.Purchases[j].Name })

		extItems = append(extItems, extItem)
	}

	return c.Render(http.StatusOK, "index", extItems)
}

func Resources(c echo.Context) error {
	sess, _ := session.Get("user", c)

	var user user
	if id, found := sess.Values["id"]; found {
		_, err := usersCol.ReadDocument(nil, fmt.Sprint(id), &user)
		if err != nil {
			return echo.ErrNotFound
		}
	}

	type extendedItem struct {
		resource
		Recipe        []basic
		Basics        []basic
		Purchases     []basic
		Commands      []command
		TotalManaCost int
		ShowUserData  bool
	}

	var extItems []extendedItem

	for _, r := range resources {
		// skip basic
		if r.Composite == false {
			continue
		}

		basics := RecurBasics(r.Recipe)
		basics = FoldBasics(basics)

		commands := RecurCommands(r.Recipe)
		commands = FoldCommands(commands)

		// make recipe to add user amount field
		var recipe []basic
		for name, amount := range r.Recipe {
			if userAmount, found := user.Stock[name]; found {
				recipe = append(recipe, basic{
					Name:       name,
					Amount:     amount,
					UserAmount: userAmount,
				})
			} else {
				recipe = append(recipe, basic{
					Name:   name,
					Amount: amount,
				})
			}
		}

		var purchases []basic

		showUserData := false
		if user.ID != "" {
			showUserData = true

			// add user amount to basics
			for name, amount := range user.Stock {
				for i := range basics {
					if basics[i].Name == name {
						basics[i].UserAmount = amount
					}
				}
			}

			purchases = RecurPurchases(r.Recipe, user.Stock)
			purchases = FoldPurchases(purchases)

			commands = RecurUserCommands(r.Recipe, user.Stock)
			commands = FoldCommands(commands)
		}

		// add craft itself
		commands = append(commands, command{
			r.ID,
			r.Name,
			1,
			r.ManaCost,
		})

		extItem := extendedItem{
			r,
			recipe,
			basics,
			purchases,
			commands,
			0,
			showUserData,
		}

		// count total mana cost
		for _, c := range commands {
			extItem.TotalManaCost += c.CommandManaCost
		}

		// Sort recipe and basics to fix it
		sort.Slice(extItem.Recipe, func(i, j int) bool { return extItem.Recipe[i].Name < extItem.Recipe[j].Name })
		sort.Slice(extItem.Basics, func(i, j int) bool { return extItem.Basics[i].Name < extItem.Basics[j].Name })
		sort.Slice(extItem.Purchases, func(i, j int) bool { return extItem.Purchases[i].Name < extItem.Purchases[j].Name })

		extItems = append(extItems, extItem)
	}

	return c.Render(http.StatusOK, "resources", extItems)
}

func Alchemist(c echo.Context) error {
	sess, _ := session.Get("user", c)

	var user user
	if id, found := sess.Values["id"]; found {
		_, err := usersCol.ReadDocument(nil, fmt.Sprint(id), &user)
		if err != nil {
			return echo.ErrNotFound
		}
	}

	type extendedItem struct {
		alchemyItem
		Recipe        []basic
		Basics        []basic
		Purchases     []basic
		Commands      []command
		TotalManaCost int
		ShowUserData  bool
	}

	var extItems []extendedItem

	for _, a := range alchemy {
		basics := RecurBasics(a.Recipe)
		basics = FoldBasics(basics)

		commands := RecurCommands(a.Recipe)
		commands = FoldCommands(commands)

		// make recipe to add user amount field
		var recipe []basic
		for name, amount := range a.Recipe {
			if userAmount, found := user.Stock[name]; found {
				recipe = append(recipe, basic{
					Name:       name,
					Amount:     amount,
					UserAmount: userAmount,
				})
			} else {
				recipe = append(recipe, basic{
					Name:   name,
					Amount: amount,
				})
			}
		}

		var purchases []basic

		showUserData := false
		if user.ID != "" {
			showUserData = true

			// add user amount to basics
			for name, amount := range user.Stock {
				for i := range basics {
					if basics[i].Name == name {
						basics[i].UserAmount = amount
					}
				}
			}

			purchases = RecurPurchases(a.Recipe, user.Stock)
			purchases = FoldPurchases(purchases)

			commands = RecurUserCommands(a.Recipe, user.Stock)
			commands = FoldCommands(commands)
		}

		// add craft itself
		commands = append(commands, command{
			a.ID,
			a.Name,
			1,
			a.ManaCost,
		})

		extItem := extendedItem{
			a,
			recipe,
			basics,
			purchases,
			commands,
			0,
			showUserData,
		}

		// count total mana cost
		for _, c := range commands {
			extItem.TotalManaCost += c.CommandManaCost
		}

		// Sort recipe and basics to fix it
		sort.Slice(extItem.Recipe, func(i, j int) bool { return extItem.Recipe[i].Name < extItem.Recipe[j].Name })
		sort.Slice(extItem.Basics, func(i, j int) bool { return extItem.Basics[i].Name < extItem.Basics[j].Name })
		sort.Slice(extItem.Purchases, func(i, j int) bool { return extItem.Purchases[i].Name < extItem.Purchases[j].Name })

		extItems = append(extItems, extItem)
	}

	return c.Render(http.StatusOK, "alchemist", extItems)
}

func Shops(c echo.Context) error {
	// Get tokens cursor
	cursor, err := db.Query(
		nil,
		`FOR s IN shops
			RETURN s`,
		nil,
	)
	if err != nil {
		return err
	}

	// Don't forget to close
	defer cursor.Close()

	var shops []cwapi.YellowPage

	// Get all tokens
	for {
		var shop cwapi.YellowPage
		_, err := cursor.ReadDocument(nil, &shop)
		if driver.IsNoMoreDocuments(err) {
			break
		} else if err != nil {
			return err
		}

		shops = append(shops, shop)
	}

	return c.Render(http.StatusOK, "shops", shops)
}

func LoginGet(c echo.Context) error {
	l := login{
		Status: "unknown",
	}

	sess, _ := session.Get("user", c)
	if _, found := sess.Values["id"]; found {
		l.Status = "alreadyLogged"
	}

	return c.Render(http.StatusOK, "login", l)
}

func LoginPost(c echo.Context) error {
	l := new(login)
	if err := c.Bind(l); err != nil {
		log.Error(err)
		l.Status = "internalError"
	}

	if l.ID == 0 {
		l.Status = "idNotSpecified"
	} else if l.Code == "" {
		if err := client.CreateAuthCode(l.ID); err != nil {
			log.Error(err)
			l.Status = "internalError"
		} else {
			// create waiter chan and save it in waiters
			waiter := make(chan map[string]string, 1)
			waiters.Store(l.ID, waiter)

			select {
			// wait auth from updates handler
			case status := <-waiter:
				if s, found := status["createAuthCode"]; found {
					l.Status = s
				}

				waiters.Delete(l.ID)
				// or timeout
			case <-time.After(5 * time.Second):
				l.Status = "timeout"
				waiters.Delete(l.ID)
			}
		}
	} else {
		if err := client.GrantToken(l.ID, l.Code); err != nil {
			log.Error(err)
			l.Status = "internalError"
		} else {
			waiter := make(chan map[string]string, 1)
			waiters.Store(l.ID, waiter)

			select {
			// wait auth from updates handler
			case status := <-waiter:
				if s, found := status["grantToken"]; found {
					if s == "success" {
						// save cookie with ID
						sess, _ := session.Get("user", c)
						sess.Values["id"] = fmt.Sprint(l.ID)
						if err := sess.Save(c.Request(), c.Response()); err != nil {
							log.Error(err)
							l.Status = "internalError"
						}

						// request stock after login
						// Request new stock
						if err := client.RequestStock(fmt.Sprint(l.ID)); err != nil {
							log.Error(err)
							l.Status = "internalError"
						}

						l.Status = s
					} else {
						l.Status = "internalError"
					}
				}

				waiters.Delete(l.ID)
				// or timeout
			case <-time.After(5 * time.Second):
				l.Status = "timeout"
				waiters.Delete(l.ID)
			}
		}
	}

	if l.Status != "success" {
		sess, _ := session.Get("user", c)
		if _, found := sess.Values["id"]; found {
			l.Status = "alreadyLogged"
		}
	}

	return c.Render(http.StatusOK, "login", l)
}

func Stock(c echo.Context) error {
	sess, _ := session.Get("user", c)

	var user user
	_, err := usersCol.ReadDocument(nil, fmt.Sprint(sess.Values["id"]), &user)
	if err != nil {
		return echo.ErrNotFound
	}

	return c.Render(http.StatusOK, "stock", user)
}

func getEquipment(c echo.Context) error {
	v, err := c.FormParams()
	if err != nil {
		return echo.ErrMethodNotAllowed
	}

	name := v.Get("name")
	itemType := v.Get("type")

	if name != "" || itemType != "" {
		for _, e := range equipment {
			if e.Name == name {
				return c.JSON(http.StatusOK, e)
			}

			if e.Type == itemType {
				return c.JSON(http.StatusOK, e)
			}
		}
	}

	return c.JSON(http.StatusOK, equipment)
}

func getEquipmentItem(c echo.Context) error {
	id := c.Param("id")

	for _, e := range equipment {
		if e.ID == id {
			return c.JSON(http.StatusOK, e)
		}
	}

	return echo.ErrNotFound
}

func getAlchemy(c echo.Context) error {
	v, err := c.FormParams()
	if err != nil {
		return echo.ErrMethodNotAllowed
	}

	name := v.Get("name")
	itemType := v.Get("type")

	if name != "" || itemType != "" {
		for _, a := range alchemy {
			if a.Name == name {
				return c.JSON(http.StatusOK, a)
			}

			if a.Type == itemType {
				return c.JSON(http.StatusOK, a)
			}
		}
	}

	return c.JSON(http.StatusOK, equipment)
}

func getAlchemyItem(c echo.Context) error {
	id := c.Param("id")

	for _, a := range alchemy {
		if a.ID == id {
			return c.JSON(http.StatusOK, a)
		}
	}

	return echo.ErrNotFound
}

func getResources(c echo.Context) error {
	v, err := c.FormParams()
	if err != nil {
		return echo.ErrMethodNotAllowed
	}

	name := v.Get("name")

	if name != "" {
		for _, r := range resources {
			if r.Name == name {
				return c.JSON(http.StatusOK, r)
			}
		}
	}

	return c.JSON(http.StatusOK, resources)
}

func getResource(c echo.Context) error {
	id := c.Param("id")

	for _, r := range resources {
		if r.ID == id {
			return c.JSON(http.StatusOK, r)
		}
	}

	return echo.ErrNotFound
}

func getBasics(c echo.Context) error {
	type response struct {
		Item   interface{} `json:"item"`
		Basics []basic     `json:"basics"`
	}

	id := c.Param("id")
	itemType := c.Param("type")

	switch itemType {
	case "equipment":
		for _, e := range equipment {
			if e.ID == id {
				basics := RecurBasics(e.Recipe)
				basics = FoldBasics(basics)

				return c.JSON(http.StatusOK, response{
					e,
					basics,
				})
			}
		}
	case "alchemy":
		for _, a := range alchemy {
			if a.ID == id {
				basics := RecurBasics(a.Recipe)
				basics = FoldBasics(basics)

				return c.JSON(http.StatusOK, response{
					a,
					basics,
				})
			}
		}
	}

	return echo.ErrNotFound
}

func getCommands(c echo.Context) error {
	type response struct {
		Item          interface{} `json:"item"`
		Commands      []command   `json:"commands"`
		TotalManaCost int         `json:"total_mana_cost"`
	}

	id := c.Param("id")
	itemType := c.Param("type")

	switch itemType {
	case "equipment":
		for _, e := range equipment {
			if e.ID == id {
				commands := RecurCommands(e.Recipe)
				commands = FoldCommands(commands)

				// add craft itself
				commands = append(commands, command{
					e.ID,
					e.Name,
					1,
					e.ManaCost,
				})

				res := response{
					e,
					commands,
					0,
				}

				// count total mana cost
				for _, c := range commands {
					res.TotalManaCost += c.CommandManaCost
				}

				return c.JSON(http.StatusOK, res)
			}
		}
	case "alchemy":
		for _, a := range alchemy {
			if a.ID == id {
				commands := RecurCommands(a.Recipe)
				commands = FoldCommands(commands)

				// add craft itself
				commands = append(commands, command{
					a.ID,
					a.Name,
					1,
					a.ManaCost,
				})

				res := response{
					a,
					commands,
					0,
				}

				// count total mana cost
				for _, c := range commands {
					res.TotalManaCost += c.CommandManaCost
				}

				return c.JSON(http.StatusOK, res)
			}
		}
	}

	return echo.ErrNotFound
}

func getShops(c echo.Context) error {
	// Get tokens cursor
	cursor, err := db.Query(
		nil,
		`FOR s IN shops
			RETURN s`,
		nil,
	)
	if err != nil {
		return err
	}

	// Don't forget to close
	defer cursor.Close()

	var shops []cwapi.YellowPage

	// Get all tokens
	for {
		var shop cwapi.YellowPage
		_, err := cursor.ReadDocument(nil, &shop)
		if driver.IsNoMoreDocuments(err) {
			break
		} else if err != nil {
			return err
		}

		shops = append(shops, shop)
	}

	return c.JSON(http.StatusOK, shops)
}

repository: crubalcaba/go-cwcraft

repo_name: crubalcaba/go-cwcraft


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/services/storage/indexed_db/transactional_leveldb/transactional_leveldb_factory.h"

#include "base/memory/ptr_util.h"
#include "base/task/sequenced_task_runner.h"
#include "components/services/storage/indexed_db/scopes/leveldb_scope.h"
#include "components/services/storage/indexed_db/scopes/leveldb_scopes.h"
#include "components/services/storage/indexed_db/transactional_leveldb/transactional_leveldb_database.h"
#include "components/services/storage/indexed_db/transactional_leveldb/transactional_leveldb_iterator.h"
#include "components/services/storage/indexed_db/transactional_leveldb/transactional_leveldb_transaction.h"

namespace content {

std::unique_ptr<TransactionalLevelDBDatabase>
DefaultTransactionalLevelDBFactory::CreateLevelDBDatabase(
    scoped_refptr<LevelDBState> state,
    std::unique_ptr<LevelDBScopes> scopes,
    scoped_refptr<base::SequencedTaskRunner> task_runner,
    size_t max_open_iterators) {
  return base::WrapUnique(new TransactionalLevelDBDatabase(
      std::move(state), std::move(scopes), this, std::move(task_runner),
      max_open_iterators));
}
std::unique_ptr<LevelDBDirectTransaction>
DefaultTransactionalLevelDBFactory::CreateLevelDBDirectTransaction(
    TransactionalLevelDBDatabase* db) {
  return base::WrapUnique(new LevelDBDirectTransaction(db));
}

scoped_refptr<TransactionalLevelDBTransaction>
DefaultTransactionalLevelDBFactory::CreateLevelDBTransaction(
    TransactionalLevelDBDatabase* db,
    std::unique_ptr<LevelDBScope> scope) {
  return base::WrapRefCounted(
      new TransactionalLevelDBTransaction(db, std::move(scope)));
}

std::unique_ptr<TransactionalLevelDBIterator>
DefaultTransactionalLevelDBFactory::CreateIterator(
    std::unique_ptr<leveldb::Iterator> it,
    base::WeakPtr<TransactionalLevelDBDatabase> db,
    base::WeakPtr<TransactionalLevelDBTransaction> txn,
    std::unique_ptr<LevelDBSnapshot> snapshot) {
  return base::WrapUnique(new TransactionalLevelDBIterator(
      std::move(it), std::move(db), std::move(txn), std::move(snapshot)));
}

}  // namespace content

repository: chromium/chromium

repo_name: chromium/chromium

extension: cc


text:
@article{pmid25764049,
 author = {Porthan, K.  and Niiranen, T. J.  and Varis, J.  and Kantola, I.  and Karanko, H.  and Kahonen, M.  and Nieminen, M. S.  and Salomaa, V.  and Huikuri, H. V.  and Jula, A. M. },
 journal = {J. Hypertens.},
 keywords = {intarticle},
 month = {Jun},
 number = {6},
 pages = {1284--1290},
 title = {ECG left ventricular hypertrophy is a stronger risk factor for incident cardiovascular events in women than in men in the general population},
 volume = {33},
 year = {2015}
}

repository: hypertensioncenter/academic-kickstart

repo_name: hypertensioncenter/academic-kickstart

gha_language: TeX

extension: bib


text:
// Copyright (c) 2016 Pedro Martelletto. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
//
// The pss module implements the generation and verification
// of probabilistic RSA signatures as specified in PKCS#1v2.2.
// The mask generator function used is the one defined in
// section B.2.1 of the same document. SHA-256 is used as the
// digest mechanism, and the salt length is assumed to be the
// same size as a SHA-256 digest.

package pss

import (
	"bytes"
	"encoding/binary"
	"errors"
	"godot/rand"
	"godot/sha256"
	"io"
	"math"
	"math/big"
)

const (
	saltLen = sha256.Len
)

// byte2big() transforms a []byte into a *big.Int.
func byte2big(p []byte) *big.Int {
	return new(big.Int).SetBytes(p)
}

// intCeil() rounds the division of two integers up to the nearest
// integer.
func intCeil(a, b uint32) uint32 {
	return uint32(math.Ceil(float64(a)/float64(b)))
}

// mgf1() implements the mask generator function defined in B.2.1.
func mgf1(mSeed []byte, mLen uint32) ([]byte, error) {
	n := intCeil(mLen, sha256.Len)
	t := bytes.NewBuffer(make([]byte, 0, int(n * sha256.Len)))

	for i := uint32(0); i < n; i++ {
		seed := bytes.NewBuffer(mSeed)
		err := binary.Write(seed, binary.BigEndian, i)
		if err != nil {
			return nil, err
		}
		h, err := sha256.DigestBytes(seed.Bytes())
		if err != nil {
			return nil, err
		}
		t.Write(h)
	}

	return t.Bytes()[:mLen], nil
}

// Encode() implements the PSS encoding operation (section 9.1.1).
func Encode(in io.Reader, emBits uint32) (*big.Int, error) {
	// check the length of the desired encoded blob and acquire
	// a random salt of appropriate length.
	emLen := intCeil(emBits, 8)
	if emLen < sha256.Len + saltLen + 2 {
		return nil, errors.New("invalid msg len")
	}
	salt, err := rand.Bytes(saltLen)
	if err != nil {
		return nil, err
	}

	// hash the contents being signed, append the salt, and rehash.
	mHash, err := sha256.DigestAll(in)
	if err != nil {
		return nil, err
	}
	m := append(append(make([]byte, 8), mHash...), salt...)
	h, err := sha256.DigestBytes(m)
	if err != nil {
		return nil, err
	}

	// generate a mask and xor it with the salt to obtain a masked
	// data block.
	mLen := emLen - sha256.Len - 1
	mask, err := mgf1(h, mLen)
	if err != nil {
		return nil, err
	}
	db := byte2big(append(append(make([]byte, 0), 0x01), salt...))
	masked := new(big.Int).Xor(db, byte2big(mask)).Bytes()
	masked[0] &= byte(0xff >> (8 * emLen - emBits))

	return byte2big(append(append(masked, h...), 0xbc)), nil
}

// splitEncoded() splits an encoded blob into a masked data block and
// hash components.
func splitEncoded(em []byte, i int) ([]byte, []byte, error) {
	if em[len(em) - 1] != 0xbc {
		return nil, nil, errors.New("invalid signature")
	}
	// skip 0xbc
	return em[:i - sha256.Len], em[i - sha256.Len:i], nil
}

// Verify() implements the PSS verification operation (section 9.1.2).
func Verify(in io.Reader, em []byte, emBits uint32) (bool, error) {
	// verify the length of the encoded blob and split it in a
	// masked data block and hash components.
	emLen := intCeil(emBits, 8)
	if emLen < sha256.Len + saltLen + 2 {
		return false, errors.New("invalid msg len")
	}
	masked, h, err := splitEncoded(em, len(em) - 1)
	if err != nil {
		return false, err
	}

	// ensure that the (8 - emLen -emBits) most significant bits
	// of the masked data block are zero.
	if masked[0] >> byte(8 - (8 * emLen - emBits)) != 0 {
		return false, errors.New("invalid signature")
	}

	// recalculate the mask, and xor it to recover the original
	// data block, whose first byte should be 0x01.
	mask, err := mgf1(h, emLen - sha256.Len - 1)
	if err != nil {
		return false, err
	}
	mask[0] &= byte(0xff >> (8 * emLen - emBits))
	db := new(big.Int).Xor(byte2big(masked), byte2big(mask)).Bytes()
	if db[0] != 0x01 || len(db) != sha256.Len + 1 {
		return false, errors.New("invalid signature")
	}

	// hash the payload being verified, salt it with the recovered
	// data block, and rehash.
	mHash, err := sha256.DigestAll(in)
	if err != nil {
		return false, err
	}
	m := append(append(make([]byte, 8), mHash...), db[1:]...)
	t, err := sha256.DigestBytes(m)
	if err != nil {
		return false, err
	}

	return sha256.Equal(h, t), nil
}

license: ISC


text:
DESCRIPTION="Upstream's U-boot configured for sunxi devices"

require recipes-bsp/u-boot/u-boot.inc

DEPENDS += "dtc-native bison-native"

LICENSE = "GPLv2"

LIC_FILES_CHKSUM = "\
file://Licenses/Exceptions;md5=338a7cb1e52d0d1951f83e15319a3fe7 \
file://Licenses/bsd-2-clause.txt;md5=6a31f076f5773aabd8ff86191ad6fdd5 \
file://Licenses/bsd-3-clause.txt;md5=4a1190eac56a9db675d58ebe86eaf50c \
file://Licenses/eCos-2.0.txt;md5=b338cb12196b5175acd3aa63b0a0805c \
file://Licenses/gpl-2.0.txt;md5=b234ee4d69f5fce4486a80fdaf4a4263 \
file://Licenses/ibm-pibs.txt;md5=c49502a55e35e0a8a1dc271d944d6dba \
file://Licenses/isc.txt;md5=ec65f921308235311f34b79d844587eb \
file://Licenses/lgpl-2.0.txt;md5=5f30f0716dfdd0d91eb439ebec522ec2 \
file://Licenses/lgpl-2.1.txt;md5=4fbd65380cdd255951079008b364516c \
file://Licenses/x11.txt;md5=b46f176c847b8742db02126fb8af92e2 \
"

SRC_URI = " \
  git://git.denx.de/u-boot.git;branch=master \
  file://boot.cmd \
  file://Increase_Kernel_Image_Max_Size.patch \
  file://0001-sunxi-h3-Fix-PLL1-setup-to-never-use-dividers.patch \
  file://0002-mixtilehub.patch \
"

SRCREV = "0157013f4a4945bbdb70bb4d98d680e0845fd784"

PV = "v2018.11"

S = "${WORKDIR}/git"

SPL_BINARY="u-boot-sunxi-with-spl.bin"

UBOOT_ENV_SUFFIX = "scr"
UBOOT_ENV = "boot"

do_compile_append() {
    ${B}/tools/mkimage -C none -A arm -T script -d ${WORKDIR}/boot.cmd ${WORKDIR}/${UBOOT_ENV_BINARY}
}

repository: mixtile/mixtilehub-distro

repo_name: mixtile/mixtilehub-distro


text:
package state_test

import (
	"context"

	"github.com/golang/mock/gomock"
	. "github.com/onsi/ginkgo/v2"
	"github.com/openshift-psap/special-resource-operator/api/v1beta1"
	"github.com/openshift-psap/special-resource-operator/internal/controllers/state"
	"github.com/openshift-psap/special-resource-operator/pkg/clients"
	v1 "k8s.io/api/apps/v1"
	k8serrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
)

var _ = Describe("StatusUpdater", func() {
	var mockKubeClient *clients.MockClientsInterface

	BeforeEach(func() {
		ctrl := gomock.NewController(GinkgoT())
		mockKubeClient = clients.NewMockClientsInterface(ctrl)
	})

	Describe("UpdateWithState", func() {
		const (
			srName      = "sr-name"
			srNamespace = "sr-namespace"
		)

		It("should do nothing if the SpecialResource could not be found", func() {
			sr := &v1beta1.SpecialResource{
				ObjectMeta: metav1.ObjectMeta{
					Name:      srName,
					Namespace: srNamespace,
				},
			}

			mockKubeClient.
				EXPECT().
				Get(context.TODO(), types.NamespacedName{Name: srName, Namespace: srNamespace}, &v1beta1.SpecialResource{}).
				Return(k8serrors.NewNotFound(v1.Resource("specialresources"), srName))

			state.NewStatusUpdater(mockKubeClient).UpdateWithState(context.TODO(), sr, "test")
		})

		It("should update the SpecialResource in Kubernetes if it exists", func() {
			const newState = "test"

			sr := &v1beta1.SpecialResource{
				ObjectMeta: metav1.ObjectMeta{
					Name:      srName,
					Namespace: srNamespace,
				},
			}

			srWithState := sr.DeepCopy()
			srWithState.Status.State = newState

			gomock.InOrder(
				mockKubeClient.
					EXPECT().
					Get(context.TODO(), types.NamespacedName{Name: srName, Namespace: srNamespace}, &v1beta1.SpecialResource{}).
					Do(func(_ context.Context, _ types.NamespacedName, _ *v1beta1.SpecialResource) {
						sr.Status.State = newState
					}),
				mockKubeClient.EXPECT().StatusUpdate(context.TODO(), sr),
			)

			state.NewStatusUpdater(mockKubeClient).UpdateWithState(context.TODO(), sr, newState)
		})
	})
})

repository: zvonkok/special-resource-operator

repo_name: zvonkok/special-resource-operator