text:
package legacy

import (
	"log"
	"net"
	"runtime"
	"strconv"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"go.octolab.org/fn"
	"go.octolab.org/strings"

	"go.octolab.org/ecosystem/guard/internal/config"
	"go.octolab.org/ecosystem/guard/internal/service/guard"
	"go.octolab.org/ecosystem/guard/internal/storage"
	"go.octolab.org/ecosystem/guard/internal/transport/grpc/gateway"
	"go.octolab.org/ecosystem/guard/internal/transport/grpc/rpc"
	"go.octolab.org/ecosystem/guard/internal/transport/http/api"
	"go.octolab.org/ecosystem/guard/internal/transport/http/monitor"
	"go.octolab.org/ecosystem/guard/internal/transport/http/profiler"
)

// Run starts HTTP server.
var Run = &cobra.Command{
	Use:   "run",
	Short: "Start HTTP server",
	RunE: func(cmd *cobra.Command, args []string) error {
		runtime.GOMAXPROCS(int(cnf.Union.ServerConfig.CPUCount))
		var (
			repository = storage.Must(
				storage.Database(cnf.Union.DatabaseConfig),
			)
			service = guard.New(cnf.Union.ServiceConfig, repository)
		)
		if err := startGRPCServer(cnf.Union.GRPCConfig, service, repository); err != nil {
			return err
		}
		if err := startMonitoring(cnf.Union.MonitoringConfig); err != nil {
			return err
		}
		if err := startProfiler(cnf.Union.ProfilingConfig); err != nil {
			return err
		}
		return startHTTPServer(cnf.Union.ServerConfig, service)
	},
}

func init() {
	v := viper.New()
	fn.Must(
		func() error { return v.BindEnv("max_cpus") },
		func() error { return v.BindEnv("bind") },
		func() error { return v.BindEnv("http_port") },
		func() error { return v.BindEnv("profiling_port") },
		func() error { return v.BindEnv("monitoring_port") },
		func() error { return v.BindEnv("grpc_port") },
		func() error { return v.BindEnv("grpc_gateway_port") },
		func() error { return v.BindEnv("read_timeout") },
		func() error { return v.BindEnv("read_header_timeout") },
		func() error { return v.BindEnv("write_timeout") },
		func() error { return v.BindEnv("idle_timeout") },
		func() error {
			v.SetDefault("max_cpus", defaults["max_cpus"])
			v.SetDefault("bind", defaults["bind"])
			v.SetDefault("http_port", defaults["http_port"])
			v.SetDefault("profiling_port", defaults["profiling_port"])
			v.SetDefault("monitoring_port", defaults["monitoring_port"])
			v.SetDefault("grpc_port", defaults["grpc_port"])
			v.SetDefault("grpc_gateway_port", defaults["grpc_gateway_port"])

			bind := v.GetString("bind")
			v.SetDefault("host", strings.Concat(bind, ":", strconv.Itoa(v.GetInt("http_port"))))
			v.SetDefault("profiling_host", strings.Concat(bind, ":", strconv.Itoa(v.GetInt("profiling_port"))))
			v.SetDefault("monitoring_host", strings.Concat(bind, ":", strconv.Itoa(v.GetInt("monitoring_port"))))
			v.SetDefault("grpc_host", strings.Concat(bind, ":", strconv.Itoa(v.GetInt("grpc_port"))))
			v.SetDefault("grpc_gateway_host", strings.Concat(bind, ":", strconv.Itoa(v.GetInt("grpc_gateway_port"))))

			v.SetDefault("read_timeout", defaults["read_timeout"])
			v.SetDefault("read_header_timeout", defaults["read_header_timeout"])
			v.SetDefault("write_timeout", defaults["write_timeout"])
			v.SetDefault("idle_timeout", defaults["idle_timeout"])
			return nil
		},
		func() error {
			flags := Run.Flags()
			flags.UintVarP(&cnf.Union.ServerConfig.CPUCount,
				"cpus", "C", uint(v.GetInt("max_cpus")), "maximum number of CPUs that can be executing simultaneously")
			flags.StringVarP(&cnf.Union.ServerConfig.Interface,
				"host", "H", v.GetString("host"), "web server host")
			flags.DurationVarP(&cnf.Union.ServerConfig.ReadTimeout,
				"read-timeout", "", v.GetDuration("read_timeout"),
				"maximum duration for reading the entire request, including the body")
			flags.DurationVarP(&cnf.Union.ServerConfig.ReadHeaderTimeout,
				"read-header-timeout", "", v.GetDuration("read_header_timeout"),
				"amount of time allowed to read request headers")
			flags.DurationVarP(&cnf.Union.ServerConfig.WriteTimeout,
				"write-timeout", "", v.GetDuration("write_timeout"),
				"maximum duration before timing out writes of the response")
			flags.DurationVarP(&cnf.Union.ServerConfig.IdleTimeout,
				"idle-timeout", "", v.GetDuration("idle_timeout"),
				"maximum amount of time to wait for the next request when keep-alive is enabled")
			flags.BoolVarP(&cnf.Union.ProfilingConfig.Enabled,
				"with-profiling", "", false, "enable pprof on /pprof/* and /debug/pprof/")
			flags.StringVarP(&cnf.Union.ProfilingConfig.Interface,
				"profiling-host", "", v.GetString("profiling_host"), "profiling host")
			flags.BoolVarP(&cnf.Union.MonitoringConfig.Enabled,
				"with-monitoring", "", false, "enable prometheus on /monitoring and expvar on /vars")
			flags.StringVarP(&cnf.Union.MonitoringConfig.Interface,
				"monitoring-host", "", v.GetString("monitoring_host"), "monitoring host")
			flags.StringVarP(&cnf.Union.GRPCConfig.RPC.Interface,
				"grpc-host", "", v.GetString("grpc_host"), "gRPC server host")
			flags.BoolVarP(&cnf.Union.GRPCConfig.Gateway.Enabled,
				"with-grpc-gateway", "", false, "enable RESTful JSON API above gRPC")
			flags.StringVarP(&cnf.Union.GRPCConfig.Gateway.Interface,
				"grpc-gateway-host", "", v.GetString("grpc_gateway_host"), "gRPC gateway server host")
			flags.BoolVarP(&cnf.Union.ServiceConfig.Disabled,
				"disabled", "", false, "disable any service barriers, only logging")
			return nil
		},
	)
	db(Run)
}

func startHTTPServer(cnf config.ServerConfig, service *guard.Guard) error {
	listener, err := net.Listen("tcp", cnf.Interface)
	if err != nil {
		return err
	}
	log.Println("start HTTP server at", listener.Addr())
	return api.New(cnf, service).Serve(listener)
}

func startGRPCServer(cnf config.GRPCConfig, service *guard.Guard, repository *storage.Storage) error {
	rpcListener, err := net.Listen("tcp", cnf.RPC.Interface)
	if err != nil {
		return err
	}
	gwListener, cascade := net.Listener(nil), make(chan struct{})
	if cnf.Gateway.Enabled {
		gwListener, err = net.Listen("tcp", cnf.Gateway.Interface)
		if err != nil {
			return err
		}
	}
	go func(listener net.Listener) {
		close(cascade)
		log.Println("start gRPC server at", listener.Addr())
		_ = rpc.New(cnf, service, repository).Serve(listener)
	}(rpcListener)
	go func(listener net.Listener) {
		if listener == nil {
			return
		}
		<-cascade
		log.Println("start gRPC gateway server at", listener.Addr())
		_ = gateway.New(cnf).Serve(listener)
	}(gwListener)
	return nil
}

func startMonitoring(cnf config.MonitoringConfig) error {
	if cnf.Enabled {
		listener, err := net.Listen("tcp", cnf.Interface)
		if err != nil {
			return err
		}
		go func(listener net.Listener) {
			log.Println("start monitoring server at", listener.Addr())
			_ = monitor.New(cnf).Serve(listener)
		}(listener)
	}
	return nil
}

func startProfiler(cnf config.ProfilingConfig) error {
	if cnf.Enabled {
		listener, err := net.Listen("tcp", cnf.Interface)
		if err != nil {
			return err
		}
		go func(listener net.Listener) {
			log.Println("start profiling server at", listener.Addr())
			_ = profiler.New(cnf).Serve(listener)
		}(listener)
	}
	return nil
}

repository: octopot/guard

repo_name: octopot/guard


text:
file(REMOVE_RECURSE
  "CMakeFiles/project.dir/Texture.cpp.obj"
  "CMakeFiles/project.dir/animation.cpp.obj"
  "CMakeFiles/project.dir/desk.cpp.obj"
  "CMakeFiles/project.dir/keyboard.cpp.obj"
  "CMakeFiles/project.dir/main.cpp.obj"
  "CMakeFiles/project.dir/monitor.cpp.obj"
  "CMakeFiles/project.dir/room.cpp.obj"
  "bin/project.exe"
  "bin/project.exe.manifest"
  "bin/project.pdb"
  "libproject.dll.a"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/project.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

license: MIT

repository: talentam/Computer-Graphics-Project

license_type: permissive

repo_name: talentam/Computer-Graphics-Project

branch_name: refs/heads/main

extension: cmake


text:
DESCRIPTION = "FFTW benchmarks"
SECTION = "libs"
LICENSE = "GPLv2"

# single precision fftw is called fftwf
DEPENDS = "fftwf"

SRC_URI = "http://www.fftw.org/benchfft/benchfft-${PV}.tar.gz"

EXTRA_OECONF = "--disable-fortran --enable-single --enable-shared"

inherit autotools pkgconfig

do_compile_prepend() {
    sed -i -e 's:all-recursive:$(RECURSIVE_TARGETS):g' ${S}/Makefile
}

SRC_URI[md5sum] = "9356e5e9dcb3f1481977009720a2ccf8"
SRC_URI[sha256sum] = "1b4a5b5e48ad5e61a21586b7b59d5c0a88691a981e73e2c6dc5868197461791b"

repository: ExorEmbedded/exor-workspace

repo_name: ExorEmbedded/exor-workspace

gha_language: Python

extension: bb


text:
@InProceedings{ralaivola09a,
  title = {Chromatic PAC-Bayes Bounds for Non-IID Data},
  author = {Liva Ralaivola and Marie Szafranski and Guillaume Stempfel},
  pages = {416--423},
  abstract = {Pac-Bayes bounds are among the most accurate    generalization bounds for classifiers learned with IID data, and it    is particularly so for margin classifiers.  However, there are many    practical cases where the training data show some dependencies and    where the traditional IID assumption does not apply. Stating    generalization bounds for such frameworks is therefore of the utmost    interest, both from theoretical and practical standpoints.  In this    work, we propose the first --~to the best of our knowledge~--    \pac-Bayes generalization bounds for classifiers trained on data    exhibiting dependencies. The approach undertaken to establish our    results is based on the decomposition of a so-called dependency    graph that encodes the dependencies within the data, in sets of    independent data, through the tool of graph fractional covers.  Our    bounds are very general, since being able to find an upper bound on    the (fractional) chromatic number of the dependency graph is    sufficient to get new \pac-Bayes bounds for specific settings.  We    show how our results can be used to derive bounds for bipartite    ranking and windowed prediction on sequential data.},
  pdf = {http://jmlr.org/proceedings/papers/v5/ralaivola09a/ralaivola09a.pdf},
}

repository: mreid/papersite

repo_name: mreid/papersite

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: TeX

extension: bib


text:
package types

type ProviderConfig struct {
	VaultDefaultPolicy    string
	VaultSecretPathPrefix string
	Datacenter            string
	ConsulAddress         string
	ConsulDNSEnabled      bool
}

repository: allbricks/faas-nomad

repo_name: allbricks/faas-nomad

extension: go


text:
package serv

// func Fuzz(data []byte) int {
// 	gql := string(data)
// 	graph.FastParse(gql)

// 	return 1
// }

repository: dosco/graphjin

repo_name: dosco/graphjin

gha_language: Go


text:
package chainedhotstuff

import (
	"context"
	"testing"

	"github.com/golang/mock/gomock"
	"github.com/relab/hotstuff"
	"github.com/relab/hotstuff/crypto"
	ecdsacrypto "github.com/relab/hotstuff/crypto/ecdsa"
	"github.com/relab/hotstuff/internal/mocks"
	"github.com/relab/hotstuff/internal/testutil"
)

func createKey(t *testing.T) *ecdsacrypto.PrivateKey {
	t.Helper()
	pk, err := crypto.GeneratePrivateKey()
	if err != nil {
		t.Errorf("Failed to generate private key: %v", err)
	}
	return &ecdsacrypto.PrivateKey{PrivateKey: pk}
}

// TestPropose checks that a leader broadcasts a new proposal, and then sends a vote to the next leader
func TestPropose(t *testing.T) {
	// Setup mocks
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	td := newTestData(t, ctrl, 4)

	// command queue that returns "foo"
	td.commands.EXPECT().GetCommand().DoAndReturn(func() *hotstuff.Command {
		cmd := hotstuff.Command("foo")
		return &cmd
	})

	td.acceptor.EXPECT().Accept(gomock.Any()).Return(true)

	td.synchronizer.EXPECT().OnPropose()

	// RULES:

	// leader should propose to other replicas.
	td.config.EXPECT().Propose(gomock.Any())

	// leader should send its own vote to the next leader.
	td.replicas[0].EXPECT().Vote(gomock.Any())

	// leader should ask synchronizer for the id of the next leader
	td.synchronizer.EXPECT().GetLeader(hotstuff.View(2)).Return(hotstuff.ID(1))

	hs := td.build()

	hs.Propose()

	if hs.LastVote() != 1 {
		t.Errorf("Wrong view: got: %d, want: %d", hs.LastVote(), 1)
	}
}

type testData struct {
	t        *testing.T
	replicas []*mocks.MockReplica
	configs  []*mocks.MockConfig
	signers  []hotstuff.Signer

	acceptor     *mocks.MockAcceptor
	commands     *mocks.MockCommandQueue
	config       *mocks.MockConfig
	executor     *mocks.MockExecutor
	synchronizer *mocks.MockViewSynchronizer
}

func (td testData) build() hotstuff.Consensus {
	td.t.Helper()

	return Builder{
		Acceptor:     td.acceptor,
		Config:       td.config,
		CommandQueue: td.commands,
		Executor:     td.executor,
		Synchronizer: td.synchronizer,
	}.Build()
}

func (td testData) createQC(block *hotstuff.Block) hotstuff.QuorumCert {
	td.t.Helper()

	return testutil.CreateQC(td.t, block, td.signers)
}

func (td testData) advanceView(hs hotstuff.Consensus, lastProposal *hotstuff.Block) *hotstuff.Block {
	td.t.Helper()

	qc := td.createQC(lastProposal)
	b := hotstuff.NewBlock(lastProposal.Hash(), qc, "foo", hs.LastVote()+1, 1)
	hs.OnPropose(b)
	return b
}

func newTestData(t *testing.T, ctrl *gomock.Controller, n int) testData {
	t.Helper()

	td := testData{
		t:        t,
		replicas: make([]*mocks.MockReplica, n-1),
		configs:  make([]*mocks.MockConfig, n-1),
		signers:  make([]hotstuff.Signer, n-1),
	}

	for i := 0; i < n-1; i++ {
		id := hotstuff.ID(i) + 1
		key := createKey(t)
		td.configs[i] = testutil.CreateMockConfig(t, ctrl, id, key)
		td.replicas[i] = testutil.CreateMockReplica(t, ctrl, id, key.PublicKey())
		signer, _ := ecdsacrypto.New(td.configs[i])
		td.signers[i] = signer
	}

	for _, config := range td.configs {
		for _, replica := range td.replicas {
			testutil.ConfigAddReplica(t, config, replica)
		}
	}

	pk := createKey(t)

	td.acceptor = mocks.NewMockAcceptor(ctrl)
	td.commands = mocks.NewMockCommandQueue(ctrl)
	td.config = testutil.CreateMockConfig(t, ctrl, hotstuff.ID(n), pk)
	td.executor = mocks.NewMockExecutor(ctrl)
	td.synchronizer = mocks.NewMockViewSynchronizer(ctrl)

	// basic configuration
	td.config.EXPECT().QuorumSize().AnyTimes().Return(n - (n-1)/3)
	td.synchronizer.EXPECT().Init(gomock.Any())

	r := testutil.CreateMockReplica(t, ctrl, hotstuff.ID(n), pk.PublicKey())
	testutil.ConfigAddReplica(t, td.config, r)

	for _, replica := range td.replicas {
		testutil.ConfigAddReplica(t, td.config, replica)
	}

	return td
}

// TestCommit checks that a replica commits and executes a valid branch
func TestCommit(t *testing.T) {
	// Create 3 signers, and then create at least 3 proposals to submit to the replica.
	// Then check that the replica has executed the first one.
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	td := newTestData(t, ctrl, 4)

	// create the needed blocks and QCs
	genesisQC := ecdsacrypto.NewQuorumCert(map[hotstuff.ID]*ecdsacrypto.Signature{}, hotstuff.GetGenesis().Hash())
	b1 := hotstuff.NewBlock(hotstuff.GetGenesis().Hash(), genesisQC, "1", 1, 1)
	b1QC := testutil.CreateQC(t, b1, td.signers)
	b2 := hotstuff.NewBlock(b1.Hash(), b1QC, "2", 2, 1)
	b2QC := testutil.CreateQC(t, b2, td.signers)
	b3 := hotstuff.NewBlock(b2.Hash(), b2QC, "3", 3, 1)
	b3QC := testutil.CreateQC(t, b3, td.signers)
	b4 := hotstuff.NewBlock(b3.Hash(), b3QC, "4", 4, 1)

	// the first replica will be the leader, so we expect it to receive votes
	td.replicas[0].EXPECT().Vote(gomock.Any()).AnyTimes()

	// executor will check that the correct command is executed
	td.executor.EXPECT().Exec(gomock.Any()).Do(func(arg interface{}) {
		if arg.(hotstuff.Command) != b1.Command() {
			t.Errorf("Wrong command executed: got: %s, want: %s", arg, b1.Command())
		}
	})

	// acceptor expects to receive the commands in order
	gomock.InOrder(
		td.acceptor.EXPECT().Accept(hotstuff.Command("1")).Return(true),
		td.acceptor.EXPECT().Accept(hotstuff.Command("2")).Return(true),
		td.acceptor.EXPECT().Accept(hotstuff.Command("3")).Return(true),
		td.acceptor.EXPECT().Accept(hotstuff.Command("4")).Return(true),
	)

	td.synchronizer.EXPECT().GetLeader(gomock.Any()).AnyTimes().Return(hotstuff.ID(1))
	td.synchronizer.EXPECT().OnPropose().AnyTimes()

	hs := td.build()

	hs.OnPropose(b1)
	hs.OnPropose(b2)
	hs.OnPropose(b3)
	hs.OnPropose(b4)
}

// TestVote checks that a leader can collect votes on a proposal to form a QC
func TestVote(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	td := newTestData(t, ctrl, 4)

	td.acceptor.EXPECT().Accept(gomock.Any()).Return(true)

	// synchronizer should expect one proposal and one finishQC
	td.synchronizer.EXPECT().OnPropose()
	td.synchronizer.EXPECT().OnFinishQC()
	td.synchronizer.EXPECT().GetLeader(gomock.Any()).AnyTimes().Return(hotstuff.ID(4))

	hs := td.build()

	b := hotstuff.NewBlock(hotstuff.GetGenesis().Hash(), hs.HighQC(), "test", 1, 1)

	hs.OnPropose(b)

	for _, signer := range td.signers {
		pc, err := signer.Sign(b)
		if err != nil {
			t.Fatalf("Failed to create partial certificate: %v", err)
		}
		hs.OnVote(pc)
	}

	if hs.HighQC().BlockHash() != b.Hash() {
		t.Errorf("HighQC was not updated.")
	}
}

// TestFetchBlock checks that a replica can fetch a block in order to create a QC
func TestFetchBlock(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	td := newTestData(t, ctrl, 4)

	// create test data
	votesSent := make(chan struct{})
	qcCreated := make(chan struct{})
	genesisQC := ecdsacrypto.NewQuorumCert(map[hotstuff.ID]*ecdsacrypto.Signature{}, hotstuff.GetGenesis().Hash())
	b := hotstuff.NewBlock(hotstuff.GetGenesis().Hash(), genesisQC, "foo", 1, 1)
	votes := testutil.CreatePCs(t, b, td.signers)

	hs := td.build()

	// configure mocks
	td.config.
		EXPECT().
		Fetch(gomock.Any(), gomock.AssignableToTypeOf(b.Hash())).
		Do(func(_ context.Context, h hotstuff.Hash) {
			// wait for all votes to be sent
			go func() {
				<-votesSent
				hs.OnDeliver(b)
			}()
		})

	td.synchronizer.EXPECT().OnFinishQC().Do(func() {
		close(qcCreated)
	})

	for _, vote := range votes {
		hs.OnVote(vote)
	}

	close(votesSent)
	<-qcCreated

	if hs.HighQC().BlockHash() != b.Hash() {
		t.Fatalf("A new QC was not created.")
	}
}

// TestForkingAttack shows that it is possible to execute a forking attack against HotStuff.
// A forking attack is when a proposal creates a fork in the block chain, leading to some commands never being executed.
// Such as scenario is illustrated in the diagram below.
// Let the arrows from the sides of the blocks represent parent links,
// while the arrows from the corners of the blocks represent QC links:
//          __________________________________
//         /                                  \
//        /                                    +---+
//       /       +-----------------------------| E |
//      / ___    |  ___       ___              +---+
//     / /   \   v /   \     /   \
//  +---+     +---+     +---+     +---+
//  | A |<----| B |<----| C |<----| D |
//  +---+     +---+     +---+     +---+
//
// Here, block E creates a new fork which means that blocks C and D will not be executed.
func TestForkingAttack(t *testing.T) {
	ctrl := gomock.NewController(t)
	td := newTestData(t, ctrl, 4)
	// configure mocks
	td.replicas[0].EXPECT().Vote(gomock.Any()).AnyTimes()
	td.synchronizer.EXPECT().OnPropose().AnyTimes()
	td.synchronizer.EXPECT().GetLeader(gomock.Any()).AnyTimes().Return(hotstuff.ID(1))
	td.acceptor.EXPECT().Accept(gomock.Any()).AnyTimes().Return(true)

	hs := td.build()

	genesisQC := ecdsacrypto.NewQuorumCert(make(map[hotstuff.ID]*ecdsacrypto.Signature), hotstuff.GetGenesis().Hash())
	a := hotstuff.NewBlock(hotstuff.GetGenesis().Hash(), genesisQC, "A", 1, 1)
	aQC := td.createQC(a)
	b := hotstuff.NewBlock(a.Hash(), aQC, "B", 2, 1)
	bQC := td.createQC(b)
	c := hotstuff.NewBlock(b.Hash(), bQC, "C", 3, 1)
	cQC := td.createQC(c)
	d := hotstuff.NewBlock(c.Hash(), cQC, "D", 4, 1)
	e := hotstuff.NewBlock(b.Hash(), aQC, "E", 5, 1)

	// expected order of execution
	gomock.InOrder(
		td.executor.EXPECT().Exec(a.Command()),
		td.executor.EXPECT().Exec(b.Command()),
		td.executor.EXPECT().Exec(e.Command()),
	)

	hs.OnPropose(a)
	hs.OnPropose(b)
	hs.OnPropose(c)
	hs.OnPropose(d)

	// sanity check
	if hs.(*chainedhotstuff).bLock != b {
		t.Fatalf("Not locked on B!")
	}

	hs.OnPropose(e)

	// advance views until E is executed
	block := td.advanceView(hs, e)
	block = td.advanceView(hs, block)
	_ = td.advanceView(hs, block)
}

repository: neilgiri/updatedconsensus

repo_name: neilgiri/updatedconsensus


text:
SUMMARY = "Shared library reduction script"
DESCRIPTION = "\
	mklibs produces cut-down shared libraries that contain only the	\
	routines required by a particular set of executables.  This is	\
	useful when building closed systems where disk space is at a premium, \
	such as the Debian installer. \
	"
PR = "r0"
inherit debian-package

LICENSE = "GPLv2+"
LIC_FILES_CHKSUM = "\
	file://src/mklibs-readelf/elf.cpp;beginline=1;endline=19;md5=f29887abbf3222cc072c0de27d7a5017 \
	"
inherit autotools-brokensep gettext pkgconfig
DEPENDS += "libtimedate-perl-native"

PACKAGES =+ "${PN}-copy"

FILES_${PN}-copy += "\
	${bindir}/mklibs-copy ${bindir}/mklibs-readelf \
	${libdir}/mklibs/* ${docdir}/mklibs-copy/* \
	${mandir}/man1/mklibs-copy.1.gz ${mandir}/man1/mklibs-readelf.1.gz \
"

repository: nghiaht-tsdv/meta-debian

repo_name: nghiaht-tsdv/meta-debian

branch_name: refs/heads/jethro

gha_language: BitBake


text:
package model

import (
	"github.com/SmallTianTian/dingtalk/model/taobao"
	"github.com/SmallTianTian/dingtalk/utils"
)

func NewOapiRoleVisibleGetRequest() *OapiRoleVisibleGetRequest {
	return &OapiRoleVisibleGetRequest{}
}

type OapiRoleVisibleGetRequest struct {
	taobao.SimpleTaobaoRequest
	taobao.SimpleResponse
	Resp            OapiRoleVisibleGetResponse
	Offset          int64
	RoleId          int64
	Size            int64
	TopHttpMethod   string
	TopResponseType string
}

func (this *OapiRoleVisibleGetRequest) GetTopHttpMethod() string {
	return "POST"
}
func (this *OapiRoleVisibleGetRequest) GetTopResponseType() string {
	return taobao.RESPONSE_TYPE_DINGTALK_OAPI
}
func (this *OapiRoleVisibleGetRequest) SetOffset(offset2 int64) {
	this.Offset = offset2
}
func (this *OapiRoleVisibleGetRequest) GetOffset() int64 {
	return this.Offset
}
func (this *OapiRoleVisibleGetRequest) SetRoleId(roleId2 int64) {
	this.RoleId = roleId2
}
func (this *OapiRoleVisibleGetRequest) GetRoleId() int64 {
	return this.RoleId
}
func (this *OapiRoleVisibleGetRequest) SetSize(size2 int64) {
	this.Size = size2
}
func (this *OapiRoleVisibleGetRequest) GetSize() int64 {
	return this.Size
}
func (this *OapiRoleVisibleGetRequest) GetApiMethodName() string {
	return "dingtalk.oapi.role.visible.get"
}
func (this *OapiRoleVisibleGetRequest) SetTopResponseType(topResponseType2 string) {
	this.TopResponseType = topResponseType2
}
func (this *OapiRoleVisibleGetRequest) GetTopApiCallType() string {
	return "oapi"
}
func (this *OapiRoleVisibleGetRequest) SetTopHttpMethod(topHttpMethod2 string) {
	this.TopHttpMethod = topHttpMethod2
}
func (this *OapiRoleVisibleGetRequest) SetHttpMethod(httpMethod string) {
	this.SetTopHttpMethod(httpMethod)
}
func (this *OapiRoleVisibleGetRequest) GetTextParams() map[string]interface{} {
	txtParams := make(map[string]interface{})
	txtParams["offset"] = this.Offset
	txtParams["role_id"] = this.RoleId
	txtParams["size"] = this.Size
	return txtParams
}
func (this *OapiRoleVisibleGetRequest) Check() *taobao.ApiRuleError {
	if err := utils.CheckNotEmpty(this.RoleId, "roleId"); err != nil {
		return err
	}
	return nil
}
func (this *OapiRoleVisibleGetRequest) GetRespInstance() interface{} {
	return &this.Resp
}
func (this *OapiRoleVisibleGetRequest) GetTaobaoResp() *taobao.TaobaoResponse {
	return &this.Resp.TaobaoResponse
}

type OapiRoleVisibleGetResponse struct {
	taobao.TaobaoResponse
	Result PageVo `json:"result,omitempty"`
}

repository: SmallTianTian/dingtalk

repo_name: SmallTianTian/dingtalk


text:
SUMMARY  = "A Python enumeration package."
DESCRIPTION = "The flufl.enum library is a Python enumeration package. Its goal is to provide simple, \
specific, concise semantics in an easy to read and write syntax. flufl.enum has just enough of the \
features needed to make enumerations useful, but without a lot of extra baggage to weigh them down. "

LICENSE = "LGPLv3"
LIC_FILES_CHKSUM = "file://PKG-INFO;startline=8;endline=9;md5=250adb4c74c359b7049abcd9d6b115e7"

SRC_URI[md5sum] = "461779384c07ed2b5f554a5d51a000c4"
SRC_URI[sha256sum] = "94da1413ba085473652f81565847913ea1543d1739972ecbd6afe57d7b1b68b4"

PYPI_PACKAGE = "flufl.enum"
inherit pypi setuptools

PACKAGES =+ "\
    ${PN}-test \
"

FILES_${PN}-doc += "\
    ${libdir}/${PYTHON_DIR}/site-packages/flufl/enum/*.rst \
    ${libdir}/${PYTHON_DIR}/site-packages/flufl/enum/docs \
"

FILES_${PN}-test += "${libdir}/${PYTHON_DIR}/site-packages/flufl/enum/tests"

repository: reMarkable/meta-openembedded

repo_name: reMarkable/meta-openembedded

branch_name: refs/heads/zero-gravitas


text:
SUMMARY = "Redkite is a small free software GUI toolkit"
LICENSE = "GPL-3.0-only"
LIC_FILES_CHKSUM = "file://LICENSE;md5=84216b5b30fa50e81f28b8f28feb2e10"

DEPENDS = "cairo"

inherit cmake features_check

REQUIRED_DISTRO_FEATURES = "x11"

SRC_URI = "git://github.com/iurie-sw/redkite.git;branch=master;protocol=https"
SRCREV = "5ff4841320716e93a27b5be7c8557df8b333492a"
PV = "1.3.1"
S = "${WORKDIR}/git"

BBCLASSEXTEND = "native"

repository: schnitzeltony/meta-musicians

repo_name: schnitzeltony/meta-musicians


text:
package callbackhandler

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"sync"

	"github.com/evt/callback/internal/model"
)

// CallbackHandler is a callback handler.
type CallbackHandler struct {
	objectService ObjectService
	testerService TesterService
}

// New creates a new callback service.
func New(service ObjectService, testerService TesterService) *CallbackHandler {
	return &CallbackHandler{
		objectService: service,
		testerService: testerService,
	}
}

// Post handles POST /callback requests
func (h *CallbackHandler) Post(w http.ResponseWriter, r *http.Request) {
	// using default context as client waits for 5 seconds only which is not enough to complete
	defaultCtx := context.Background()

	var request model.CallbackRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		http.Error(w, fmt.Sprintf("invalid request: %s", err), http.StatusBadRequest)
	}

	if len(request.ObjectIDs) == 0 {
		http.Error(w, "no object IDs provided", http.StatusBadRequest)
	}

	// this is a group of requests back to tester service for object details
	var wg sync.WaitGroup
	receivedObjects := make(chan model.TesterObject, len(request.ObjectIDs))

	for i := range request.ObjectIDs {
		wg.Add(1)

		objectID := request.ObjectIDs[i]

		// log.Printf("=> Next object ID: %d\n", objectID)

		go func() {
			defer wg.Done()

			object, err := h.testerService.GetObject(defaultCtx, objectID)
			if err != nil {
				log.Printf("[id: %d, total: %d] testerService.GetObject failed: %s\n", object.ID, len(request.ObjectIDs), err)

				return
			}

			// log.Printf("[id: %d, total: %d] testerService.GetObject passed (online=%t)\n", object.ID, len(request.ObjectIDs), object.Online)

			receivedObjects <- object
		}()
	}

	go func() {
		wg.Wait()
		close(receivedObjects)
	}()

	var totalUpdated, totalReceived int

	for object := range receivedObjects {
		totalReceived++

		if !object.Online {
			continue
		}

		h.objectService.UpdateObject(defaultCtx, &model.DBObject{
			ID: object.ID,
		})

		totalUpdated++
	}

	log.Printf("objects: received=%d, updated(=online) = %d\n", totalReceived, totalUpdated)

	w.Write([]byte("ok"))
}

repository: tiranosaur/note

repo_name: tiranosaur/note


text:
package qlog

import (
	"encoding/json"
	"os"
	"strconv"
	"testing"
	"time"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
)

func TestQlog(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "qlog Suite")
}

//nolint:unparam
func scaleDuration(t time.Duration) time.Duration {
	scaleFactor := 1
	if f, err := strconv.Atoi(os.Getenv("TIMESCALE_FACTOR")); err == nil { // parsing "" errors, so this works fine if the env is not set
		scaleFactor = f
	}
	Expect(scaleFactor).ToNot(BeZero())
	return time.Duration(scaleFactor) * t
}

func checkEncoding(data []byte, expected map[string]interface{}) {
	// unmarshal the data
	m := make(map[string]interface{})
	ExpectWithOffset(2, json.Unmarshal(data, &m)).To(Succeed())
	ExpectWithOffset(2, m).To(HaveLen(len(expected)))
	for key, value := range expected {
		switch v := value.(type) {
		case bool, string, map[string]interface{}:
			ExpectWithOffset(1, m).To(HaveKeyWithValue(key, v))
		case int:
			ExpectWithOffset(1, m).To(HaveKeyWithValue(key, float64(v)))
		case [][]float64: // used in the ACK frame
			ExpectWithOffset(1, m).To(HaveKey(key))
			for i, l := range v {
				for j, s := range l {
					ExpectWithOffset(1, m[key].([]interface{})[i].([]interface{})[j].(float64)).To(Equal(s))
				}
			}
		default:
			Fail("unexpected type")
		}
	}
}

repository: fbzhong/quic-go

repo_name: fbzhong/quic-go


text:
@inproceedings{ISI:000243124500023,
 author = {Mazzoni, Stefano and Cerbino, Roberto and Vailati, Alberto and Giglio,
Marzio},
 booktitle = {INTERDISCIPLINARY TRANSPORT PHENOMENA IN THE SPACE SCIENCES},
 doi = {10.1196/annals.1362.029},
 editor = {Sadhal, SS},
 isbn = {1-57331-615-6},
 issn = {0077-8923},
 note = {Conference on Interdisciplinary Transport Phenomena in Microgravity and
Space Sciences IV, Tomar, PORTUGAL, AUG 07-12, 2005},
 orcid-numbers = {Mazzoni, Stefano/0000-0001-5176-4391
Cerbino, Roberto/0000-0003-0434-7741
Vailati, Alberto/0000-0002-3119-6021},
 pages = {351-364},
 researcherid-numbers = {Mazzoni, Stefano/I-5865-2012
Mazzoni, Stefano/P-7521-2019
Cerbino, Roberto/A-2286-2008
Vailati, Alberto/B-2299-2009},
 series = {ANNALS OF THE NEW YORK ACADEMY OF SCIENCES},
 times-cited = {5},
 title = {Fluctuations in diffusion processes in microgravity},
 unique-id = {ISI:000243124500023},
 volume = {1077},
 year = {2006}
}

repository: rcerbino/starter-academic

repo_name: rcerbino/starter-academic


text:
SECTION = "x11/base"
LICENSE = "MIT"
SRC_URI = "http://dri.freedesktop.org/libdrm/libdrm-${PV}.tar.bz2"
PROVIDES = "drm"

inherit autotools pkgconfig

do_stage() {
	autotools_stage_all
}


text:
package main

import (
	"fmt"
	"strconv"
	"time"
)
//const (
//	Nanosecond  Duration = 1  // 纳秒
//	Microsecond          = 1000 * Nanosecon //微妙
//	Millisecond          = 1000 * Microsecond //毫秒
//	Second               = 1000 * Millisecond
//	Minute               = 60 * Second
//	Hour                 = 60 * Minute
//)

func testTime()  {
	str := ""
	for i :=0;i<1000000;i++{
		str +="hello"+strconv.Itoa(i)
	}
}

func main()  {

	fmt.Println("123")
	// 获取当前时间
	now := time.Now()
	fmt.Printf("now=%T and now=%v\n",now,now)

	// 2. 通过now 获取年月日，时分秒
	fmt.Printf("年=%v\n",now.Year())
	//fmt.Printf("月=%v\n",now.Month()) // December
	fmt.Printf("月=%v\n",int(now.Month()))

	fmt.Printf("日=%v\n",now.Day())
	fmt.Printf("时=%v\n",now.Hour())
	fmt.Printf("分=%v\n",now.Minute())
	fmt.Printf("秒=%v\n",now.Second())

	//格式化 日期时间
	fmt.Printf("当前时间： %d-%d-%d %d:%d:%d \n",now.Year(),now.Month(),
		now.Day(),now.Hour(),now.Minute(),now.Second(),
		)
	dateStr := fmt.Sprintf("当前时间： %d-%d-%d %d:%d:%d \n",now.Year(),now.Month(),
		now.Day(),now.Hour(),now.Minute(),now.Second(),
	)
	fmt.Println(dateStr)

	// 方法二
	fmt.Printf(now.Format("2006/01/02 15:04:05\n"))  // 数字不能更改，符号可以随意改， 不然格式不出
	fmt.Printf(now.Format("2006-01-02 15:04:05\n"))
	fmt.Printf(now.Format("2006-01-02\n"))
	fmt.Printf(now.Format("01\n")) //只拿月

	// 时间的常量，   在程序运行中 获取指定的时间
	i :=0
	for {
		i++
		fmt.Println(i)
		// 0.1秒 不能是Second*0.1不然不通过
		//time.Sleep(time.Second)
		time.Sleep(time.Microsecond * 100)
		if i==10{
			break
		}
	}
	// Unix 时间戳 秒的
	// UnixNano  纳秒时间戳
	fmt.Printf("unxs时间戳=%v，UnixNano时间戳=%v",now.Unix(),now.UnixNano())

	star:=time.Now().Unix()
	testTime()
	end:=time.Now().Unix()
	fmt.Printf("\n%v秒\n",end-star)

}

repository: kensmaster/StudyNotes

path: /Go语言/Go语法基础/src/字符串数字操作/字符串时间.go

path: /Go语言/Go语法基础/src/字符串数字操作/字符串时间.go

repo_name: kensmaster/StudyNotes


text:
@inproceedings{cotterell+al.arxiv18,
 title = {On the Diachronic Stability of Irregularity in Inflectional Morphology},
 author = {Cotterell, Ryan and
Kirov, Christo and
Hulden, Mans and
Eisner, Jason},
 booktitle = {arXiv preprint arXiv:1804.08262},
 year = {2018},
 url = {https://arxiv.org/abs/1804.08262},
 arxiv = {https://arxiv.org/abs/1804.08262}
}

repository: rycolab/website

repo_name: rycolab/website


text:
# This script can be used to clear the content of a directory except for a list of entries.
# The entries can be files or subdirectories. Subdirectories are deleted recursively.
#
# Arguments
# ARGUMENT_FILE	- The absolute path to a file that contains the arguments of the script.
#	DIRECTORY	- A cmake variable in the argument file that contains the absolute path to the directory that shall be cleared.
#	ENTRIES		- A cmake variable in the argument file that contains the entries that shall not be deleted from the directory.

include(${CMAKE_CURRENT_LIST_DIR}/../cpfInit.cmake)
include(cpfMiscUtilities)
include(cpfListUtilities)

cpfAssertScriptArgumentDefined(ARGUMENT_FILE)

include("${ARGUMENT_FILE}")

cpfAssertScriptArgumentDefined(DIRECTORY)
cpfAssertScriptArgumentDefined(ENTRIES)

file(GLOB existingDirEntriesFull "${DIRECTORY}/*")
set(existingDirEntries)
foreach( fullEntry ${existingDirEntriesFull})
	file(RELATIVE_PATH shortEntry "${DIRECTORY}" "${fullEntry}" )
	cpfListAppend( existingDirEntries ${shortEntry})
endforeach()

set(deletedEntries)
foreach( entry ${existingDirEntries})
	cpfContains( isPersistentEntry "${ENTRIES}" ${entry})
	if(NOT isPersistentEntry)
		cpfListAppend( deletedEntries "${DIRECTORY}/${entry}")
	endif()
endforeach()

if(deletedEntries)
	file(REMOVE_RECURSE ${deletedEntries})
endif()

repository: Knitschi/CPFCMake

repo_name: Knitschi/CPFCMake


text:
package utils

import (
	"time"
)

// UnixToStr change int to strc
func UnixToStr(i int64) string {
	// return time.Unix(i,0).Location().String()
	return time.Unix(i, 0).Local().Format("2006-01-02 15:04:05")

}

// StrToUnix change str to unix
func StrToUnix(t string) int64 {
	tparse, err := time.Parse("2006-01-02 15:04:05", t)
	if err != nil {
		tparse, err = time.Parse("2006-01-02T15:04:05Z", t)
		if err != nil {
			return 0
		}
	}
	return tparse.Unix()
}

repository: Monkey-Pro/crocodile

repo_name: Monkey-Pro/crocodile

branch_name: refs/heads/dev


text:
package model

import (
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/utils"

	"strings"
)

// ListAutoLaunchGroupsRequest Request Object
type ListAutoLaunchGroupsRequest struct {

	// 查询返回智能购买组的数量限制 取值范围：1-1000。
	Limit *int32 `json:"limit,omitempty"`

	// 取值为上一页数据的最后一条记录的唯一标识
	Marker *string `json:"marker,omitempty"`

	// 智能购买组名称
	Name *string `json:"name,omitempty"`

	// 请求开始时间，按照时间范围过滤 按照ISO8601标准表示，并使用UTC +0时间，格式为yyyy-MM-ddTHH:mm:ssZ
	ValidSince *string `json:"valid_since,omitempty"`

	// 请求结束时间,按照时间范围过滤 按照ISO8601标准表示，并使用UTC +0时间，格式为yyyy-MM-ddTHH:mm:ssZ
	ValidUntil *string `json:"valid_until,omitempty"`
}

func (o ListAutoLaunchGroupsRequest) String() string {
	data, err := utils.Marshal(o)
	if err != nil {
		return "ListAutoLaunchGroupsRequest struct{}"
	}

	return strings.Join([]string{"ListAutoLaunchGroupsRequest", string(data)}, " ")
}

gha_license_id: NOASSERTION


text:
#
# base recipe: meta/recipes-extended/less/less_458.bb
# base branch: daisy
#

PR = "r0"

inherit debian-package

# Including email author giving permissing to use BSD
#
# From: Mark Nudelman <markn@greenwoodsoftware.com>
# To: Elizabeth Flanagan <elizabeth.flanagan@intel.com
# Date: 12/19/11
#
# Hi Elizabeth,
# Using a generic BSD license for less is fine with me.
# Thanks,
#
# --Mark
#
LICENSE = "GPLv3+ | BSD-2-Clause"
LIC_FILES_CHKSUM = " \
	file://COPYING;md5=d32239bcb673463ab874e80d47fae504 \
	file://LICENSE;md5=866cc220f330b04ae4661fc3cdfedea7 \
"

DEPENDS = "ncurses"

inherit autotools update-alternatives

# On Debian, binary files are installed to /bin
EXTRA_OECONF += "--bindir=${base_bindir}"

# Follow debian/rules
do_install_append() {
	install -d ${D}${bindir}
	install -m 0755 ${S}/debian/lesspipe ${D}${base_bindir}/lesspipe
	ln -s lesspipe ${D}${base_bindir}/lessfile
	ln -s ../../bin/lesspipe ${D}${bindir}/lessfile
	ln -s ../../bin/lesspipe ${D}${bindir}/lesspipe
	ln -s ../../bin/lesskey ${D}${bindir}/lesskey
	ln -s ../../bin/lessecho ${D}${bindir}/lessecho
	ln -s ../../bin/less ${D}${bindir}/less

	mkdir -p ${D}${libdir}/mime/packages
	install -m 0644 ${S}/debian/mime ${D}${libdir}/mime/packages/less
}

FILES_${PN} += "${libdir}/*"

# Add update-alternatives definitions to avoid conflict with busybox
ALTERNATIVE_${PN} = "less"
ALTERNATIVE_PRIORITY[less] = "100"
ALTERNATIVE_LINK_NAME[less] = "${base_bindir}/less"

# Follow debian/postinst
ALTERNATIVE_${PN} += "pager"
ALTERNATIVE_TARGET[pager] = "${base_bindir}/less.${DPN}"
ALTERNATIVE_LINK_NAME[pager] = "${bindir}/pager"
ALTERNATIVE_PRIORITY[pager] = "77"


text:
@book{imbalanced-classification,
  author    = {Bartosz Krawczyk and Mikel Galar and Łukasz Jelen and Francisco Herrera},
  title     = {\textit{Evolutionary undersampling boosting for imbalanced classification of breast cancer malignancy}},
  year      = {2015},
  publisher = {Elsevier}
}

@misc{neural-networks,
  author    = {Raul Rojas},
  title     = {\textit{Neural Networks - A Systematic Introduction}},
  year      = {1996},
  howpublished = {\url{https://page.mi.fu-berlin.de/rojas/neural/}}
}

@misc{elm,
  author    = {Guang-Bin Huang},
  title     = {\textit{What are Extreme Learning Machines?}},
  year      = {2015},
  howpublished = {\url{http://www.ntu.edu.sg/home/egbhuang/pdf/ELM-Rosenblatt-Neumann.pdf}}
}

@misc{neural-deeplearning,
  title        = {Neural Networks and Deep Learning},
  howpublished = {\url{http://neuralnetworksanddeeplearning.com/}},
  note         = {Aktualne dnia: 2016-06-01}
}

@misc{scikit-learn-docs,
  title        = {Scikit-learn documentation},
  howpublished = {\url{http://scikit-learn.org/dev/documentation.html}},
  note         = {Aktualne dnia: 2016-06-01}
}

@misc{intro-to-machine-learning,
  author    = {Alex Krot},
  title        = {Introduction to Machine Learning with Python and Scikit-Learn},
  howpublished = {\url{http://kukuruku.co/hub/python/introduction-to-machine-learning-with-python-andscikit-learn}},
  note         = {Aktualne dnia: 2016-06-01}
}

repository: kmachnicki/ann

repo_name: kmachnicki/ann


text:
package actions

import (
	"context"
	"log"
	"strings"
	"time"

	"github.com/dustin/go-humanize"
	actions_proto "www.velocidex.com/golang/velociraptor/actions/proto"
	artifacts "www.velocidex.com/golang/velociraptor/artifacts"
	config "www.velocidex.com/golang/velociraptor/config"
	crypto_proto "www.velocidex.com/golang/velociraptor/crypto/proto"
	"www.velocidex.com/golang/velociraptor/responder"
	vql_networking "www.velocidex.com/golang/velociraptor/vql/networking"
	"www.velocidex.com/golang/vfilter"
)

type LogWriter struct {
	responder *responder.Responder
}

func (self *LogWriter) Write(b []byte) (int, error) {
	err := self.responder.Log("%s", string(b))
	if err != nil {
		return 0, err
	}
	return len(b), nil
}

type VQLClientAction struct{}

func (self *VQLClientAction) Run(
	config_obj *config.Config,
	ctx context.Context,
	msg *crypto_proto.GrrMessage,
	output chan<- *crypto_proto.GrrMessage) {
	responder := responder.NewResponder(msg, output)
	arg, pres := responder.GetArgs().(*actions_proto.VQLCollectorArgs)
	if !pres {
		responder.RaiseError("Request should be of type VQLCollectorArgs")
		return
	}

	if arg.MaxWait == 0 {
		arg.MaxWait = 10
	}

	self.StartQuery(config_obj, ctx, responder, arg)
}

func (self *VQLClientAction) StartQuery(
	config_obj *config.Config,
	ctx context.Context,
	responder *responder.Responder,
	arg *actions_proto.VQLCollectorArgs) {
	if arg.Query == nil {
		responder.RaiseError("Query should be specified.")
		return
	}

	// Create a new query environment and store some useful
	// objects in there. VQL plugins may then use the environment
	// to communicate with the server.
	uploader := &vql_networking.VelociraptorUploader{
		Responder: responder,
	}

	env := vfilter.NewDict().
		Set("$responder", responder).
		Set("$uploader", uploader).
		Set("config", config_obj)

	for _, env_spec := range arg.Env {
		env.Set(env_spec.Key, env_spec.Value)
	}

	// Clients do not have a copy of artifacts so they need to be
	// sent all artifacts from the server.
	repository := artifacts.NewRepository()
	for _, artifact := range arg.Artifacts {
		repository.Set(artifact)
	}
	scope := artifacts.MakeScope(repository).AppendVars(env)
	scope.Logger = log.New(&LogWriter{responder},
		"vql: ", log.Lshortfile)

	// All the queries will use the same scope. This allows one
	// query to define functions for the next query in order.
	for query_idx, query := range arg.Query {
		now := uint64(time.Now().UTC().UnixNano() / 1000)
		vql, err := vfilter.Parse(query.VQL)
		if err != nil {
			responder.RaiseError(err.Error())
			return
		}

		// Use defaults for MaxRow if not defined.
		max_rows := int(arg.MaxRow)
		if max_rows == 0 {
			max_rows = 10000
		}

		max_wait := int(arg.MaxWait)
		if max_wait == 0 {
			// Start to send data after at most 100
			// seconds.
			max_wait = 10
		}

		result_chan := vfilter.GetResponseChannel(
			vql, ctx, scope, max_rows, max_wait)
		for {
			result, ok := <-result_chan
			if !ok {
				break
			}

			// Skip let queries since they never produce results.
			if strings.HasPrefix(strings.ToLower(query.VQL), "let") {
				continue
			}
			response := &actions_proto.VQLResponse{
				Query:     query,
				QueryId:   uint64(query_idx),
				Part:      uint64(result.Part),
				Response:  string(result.Payload),
				Timestamp: uint64(time.Now().UTC().UnixNano() / 1000),
			}

			responder.Log("Time %v: %s: Sending response part %d %s (%d rows).",
				(response.Timestamp-now)/1000000,
				query.Name,
				result.Part,
				humanize.Bytes(uint64(len(result.Payload))),
				result.TotalRows,
			)
			response.Columns = result.Columns
			responder.AddResponse(response)
		}
	}

	if uploader.Count > 0 {
		responder.Log("Uploaded %v files.", uploader.Count)
	}

	responder.Return()
}

repository: jmckinlay/velociraptor

repo_name: jmckinlay/velociraptor


text:
SUMMARY = "PulseAudio configuration which doesn't load module-router"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = "file://soundmanager.pa"

do_install () {
    install -d ${D}${sysconfdir}/pulse/default.d
    install -m 0644 ${WORKDIR}/soundmanager.pa ${D}${sysconfdir}/pulse/default.d/
}

PROVIDES_${PN} += "virtual/pulseaudio-config"


text:
package smartcharge

import (
	"net/http"
	"strconv"
)

type InvoiceService struct {
	client *Client
}

type InvoiceResult struct {
	Result Data `json:"Result"`
}

type Data struct {
	Data    InvoiceData `json:"datas"`
	Success bool        `json:"sucess"`
}

type InvoiceData struct {
	Invoices []Invoice
}

type Invoice struct {
	Id         int     `json:"PK_InvoiceID"`
	TotalPrice float64 `json:"TotalPrice"`
	TotalVAT   float64 `json:"TotalVAT"`
	DateIssued string  `json:"DateIssued"`
	TotalKWH   float64 `json:"TotalKWH"`
}

func (i *InvoiceService) GetInvoices(customerId int) (*InvoiceResult, *http.Response, error) {

	reqUrl := "v2/Invoices/GetInvoicesByCustomer/" + strconv.Itoa(customerId)
	req, err := i.client.NewRequest("GET", reqUrl, nil)
	if err != nil {
		return nil, nil, err
	}

	invoiceResult := &InvoiceResult{}
	resp, err := i.client.Do(req, invoiceResult)
	if err != nil {
		return nil, resp, err
	}

	return invoiceResult, resp, err
}

license: ISC

repository: sjurtf/smartcharge-go

repo_name: sjurtf/smartcharge-go


text:
# Robin Sebastian (https://github.com/robseb) (git@robseb.de) 2019-2021

SUMMARY = "Reset the FPGA Fabric"
DESCRIPTION = "Tool to remove via the Intel FPGA Manager the FPGA Fabric configuration by putting it to reset"
SECTION = "rstools"
LICENSE = "GPL-2"
PR = "r0"
LIC_FILES_CHKSUM = "file://CHECKSUMFILE;md5=bff2b7959c4b3958a8ae19f6a39a59ac"
SRC_URI = "gitsm://github.com/robseb/rstoolsA10.git;protocol=https"
SRCREV = "${AUTOREV}"
# use  git rev-parse HEAD to update

# This Version is for the Intel Arria 10 SoC-FPGA
COMPATIBLE_MACHINE = 'arria10'

inherit cmake

S = "${WORKDIR}/git/FPGA-resetFabric"
FILES_${PN} += "${bindir}"

do_install() {
    install -d ${D}${bindir}
    install -m 0755 FPGA-resetFabric ${D}${bindir}
}

repository: BobAfwata/meta-intelfpga

repo_name: BobAfwata/meta-intelfpga


text:
require linux-opi.inc

FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}/${PN}z:"

LIC_FILES_CHKSUM = "file://COPYING;md5=bbea815ee2795b2f4230826c0c6b8814"

COMPATIBLE_MACHINE = "(orange-pi-zero)"

SRCREV = "84df9525b0c27f3ebc2ebb1864fa62a97fdedb7d"

SRC_URI = " \
  git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git;protocol=git;branch=master \
  file://defconfig \
  file://0001-Enable_Spi_Nor_Flash.patch \
  file://0002-Add_WiFi_To_Dts.patch \
"

repository: xlloss/orange-pi-distro

repo_name: xlloss/orange-pi-distro


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

package w32

import (
    "unsafe"
)

type (
    BOOL         int
    ATOM         uint16
    DWORD        uint32
    HANDLE       uintptr
    HINSTANCE    HANDLE
    HACCEL       HANDLE
    HCURSOR      HANDLE
    HDWP         HANDLE
    HICON        HANDLE
    HMENU        HANDLE
    HWND         HANDLE
    HBRUSH       HANDLE
    HRESULT      int32
    HFONT        HANDLE
    HDC          HANDLE
    HGDIOBJ      HANDLE
    HDROP        HANDLE
    HENHMETAFILE HANDLE
    HBITMAP      HANDLE
    HPEN         HANDLE
    HKEY         HANDLE
    HIMAGELIST   HANDLE
    HGLOBAL      HANDLE
    HMODULE      HANDLE
    HRSRC        HANDLE
    COLORREF     DWORD
)

type POINT struct {
    X, Y int
}

type RECT struct {
    Left, Top, Right, Bottom int
}

type WNDCLASSEX struct {
    Size       uint
    Style      uint
    WndProc    uintptr
    ClsExtra   int
    WndExtra   int
    Instance   HINSTANCE
    Icon       HICON
    Cursor     HCURSOR
    Background HBRUSH
    MenuName   *uint16
    ClassName  *uint16
    IconSm     HICON
}

type MSG struct {
    Hwnd    HWND
    Message uint
    WParam  uintptr
    LParam  uintptr
    Time    uint
    Pt      POINT
}

type LOGFONT struct {
    Height         int
    Width          int
    Escapement     int
    Orientation    int
    Weight         int
    Italic         byte
    Underline      byte
    StrikeOut      byte
    CharSet        byte
    OutPrecision   byte
    ClipPrecision  byte
    Quality        byte
    PitchAndFamily byte
    FaceName       [LF_FACESIZE]uint16
}

type OPENFILENAME struct {
    StructSize      uint
    Owner           HWND
    Instance        HINSTANCE
    Filter          *uint16
    CustomFilter    *uint16
    MaxCustomFilter uint
    FilterIndex     uint
    File            *uint16
    MaxFile         uint
    FileTitle       *uint16
    MaxFileTitle    uint
    InitialDir      *uint16
    Title           *uint16
    Flags           uint
    FileOffset      uint16
    FileExtension   uint16
    DefExt          *uint16
    CustData        uintptr
    FnHook          uintptr
    TemplateName    *uint16
    PvReserved      unsafe.Pointer
    DwReserved      uint
    FlagsEx         uint
}

type BROWSEINFO struct {
    Owner        HWND
    Root         *uint16
    DisplayName  *uint16
    Title        *uint16
    Flags        uint
    CallbackFunc uintptr
    LParam       uintptr
    Image        int
}

type GUID struct {
    Data1 uint
    Data2 uint16
    Data3 uint16
    Data4 [8]byte
}

type VARIANT struct {
    VT         uint16 //  2
    WReserved1 uint16 //  4
    WReserved2 uint16 //  6
    WReserved3 uint16 //  8
    Val        int64  // 16
}

type DISPPARAMS struct {
    Rgvarg            uintptr
    RgdispidNamedArgs uintptr
    CArgs             uint
    CNamedArgs        uint
}

type EXCEPINFO struct {
    WCode             uint16
    WReserved         uint16
    BstrSource        *uint16
    BstrDescription   *uint16
    BstrHelpFile      *uint16
    DwHelpContext     uint
    PvReserved        uintptr
    PfnDeferredFillIn uintptr
    Scode             int
}

type LOGBRUSH struct {
    LbStyle uint
    LbColor COLORREF
    LbHatch uintptr
}

type DEVMODE struct {
    DmDeviceName       [CCHDEVICENAME]uint16
    DmSpecVersion      uint16
    DmDriverVersion    uint16
    DmSize             uint16
    DmDriverExtra      uint16
    DmFields           uint
    DmOrientation      int16
    DmPaperSize        int16
    DmPaperLength      int16
    DmPaperWidth       int16
    DmScale            int16
    DmCopies           int16
    DmDefaultSource    int16
    DmPrintQuality     int16
    DmColor            int16
    DmDuplex           int16
    DmYResolution      int16
    DmTTOption         int16
    DmCollate          int16
    DmFormName         [CCHFORMNAME]uint16
    DmLogPixels        uint16
    DmBitsPerPel       uint
    DmPelsWidth        uint
    DmPelsHeight       uint
    DmDisplayFlags     uint
    DmDisplayFrequency uint
    DmICMMethod        uint
    DmICMIntent        uint
    DmMediaType        uint
    DmDitherType       uint
    DmReserved1        uint
    DmReserved2        uint
    DmPanningWidth     uint
    DmPanningHeight    uint
}

type BITMAPINFOHEADER struct {
    BiSize          uint
    BiWidth         int
    BiHeight        int
    BiPlanes        uint16
    BiBitCount      uint16
    BiCompression   uint
    BiSizeImage     uint
    BiXPelsPerMeter int
    BiYPelsPerMeter int
    BiClrUsed       uint
    BiClrImportant  uint
}

type RGBQUAD struct {
    RgbBlue     byte
    RgbGreen    byte
    RgbRed      byte
    RgbReserved byte
}

type BITMAPINFO struct {
    BmiHeader BITMAPINFOHEADER
    BmiColors *RGBQUAD
}

type BITMAP struct {
    BmType       int32
    BmWidth      int32
    BmHeight     int32
    BmWidthBytes int32
    BmPlanes     uint16
    BmBitsPixel  uint16
    BmBits       unsafe.Pointer
}

type DIBSECTION struct {
    DsBm        BITMAP
    DsBmih      BITMAPINFOHEADER
    DsBitfields [3]uint32
    DshSection  HANDLE
    DsOffset    uint32
}

type ENHMETAHEADER struct {
    IType          uint
    NSize          uint
    RclBounds      RECT
    RclFrame       RECT
    DSignature     uint
    NVersion       uint
    NBytes         uint
    NRecords       uint
    NHandles       uint16
    SReserved      uint16
    NDescription   uint
    OffDescription uint
    NPalEntries    uint
    SzlDevice      SIZE
    SzlMillimeters SIZE
    CbPixelFormat  uint
    OffPixelFormat uint
    BOpenGL        uint
    SzlMicrometers SIZE
}

type SIZE struct {
    CX, CY int
}

type TEXTMETRIC struct {
    TmHeight           int
    TmAscent           int
    TmDescent          int
    TmInternalLeading  int
    TmExternalLeading  int
    TmAveCharWidth     int
    TmMaxCharWidth     int
    TmWeight           int
    TmOverhang         int
    TmDigitizedAspectX int
    TmDigitizedAspectY int
    TmFirstChar        uint16
    TmLastChar         uint16
    TmDefaultChar      uint16
    TmBreakChar        uint16
    TmItalic           byte
    TmUnderlined       byte
    TmStruckOut        byte
    TmPitchAndFamily   byte
    TmCharSet          byte
}

type DOCINFO struct {
    CbSize       int
    LpszDocName  *uint16
    LpszOutput   *uint16
    LpszDatatype *uint16
    FwType       uint
}

type NMHDR struct {
    HwndFrom HWND
    IdFrom   uintptr
    Code     uint
}

type LVCOLUMN struct {
    Mask       uint
    Fmt        int
    Cx         int
    PszText    *uint16
    CchTextMax int
    ISubItem   int
    IImage     int
    IOrder     int
}

type LVITEM struct {
    Mask       uint
    IItem      int
    ISubItem   int
    State      uint
    StateMask  uint
    PszText    *uint16
    CchTextMax int
    IImage     int
    LParam     uintptr
    IIndent    int
    IGroupId   int
    CColumns   uint
    PuColumns  uint
}

type LVHITTESTINFO struct {
    Pt       POINT
    Flags    uint
    IItem    int
    ISubItem int
    IGroup   int
}

type NMITEMACTIVATE struct {
    Hdr       NMHDR
    IItem     int
    ISubItem  int
    UNewState uint
    UOldState uint
    UChanged  uint
    PtAction  POINT
    LParam    uintptr
    UKeyFlags uint
}

type NMLISTVIEW struct {
    Hdr       NMHDR
    IItem     int
    ISubItem  int
    UNewState uint
    UOldState uint
    UChanged  uint
    PtAction  POINT
    LParam    uintptr
}

type NMLVDISPINFO struct {
    Hdr  NMHDR
    Item LVITEM
}

type INITCOMMONCONTROLSEX struct {
    DwSize uint
    DwICC  uint
}

type TOOLINFO struct {
    CbSize     uint
    UFlags     uint
    Hwnd       HWND
    UId        uintptr
    Rect       RECT
    Hinst      HINSTANCE
    LpszText   *uint16
    LParam     uintptr
    LpReserved unsafe.Pointer
}

type TRACKMOUSEEVENT struct {
    CbSize      uint
    DwFlags     uint
    HwndTrack   HWND
    DwHoverTime uint
}

type GdiplusStartupInput struct {
    GdiplusVersion           uint32
    DebugEventCallback       uintptr
    SuppressBackgroundThread BOOL
    SuppressExternalCodecs   BOOL
}

type GdiplusStartupOutput struct {
    NotificationHook   uintptr
    NotificationUnhook uintptr
}

type PAINTSTRUCT struct {
    Hdc         HDC
    FErase      BOOL
    RcPaint     RECT
    FRestore    BOOL
    FIncUpdate  BOOL
    RgbReserved [32]byte
}

type EVENTLOGRECORD struct {
    Length              uint32
    Reserved            uint32
    RecordNumber        uint32
    TimeGenerated       uint32
    TimeWritten         uint32
    EventID             uint32
    EventType           uint16
    NumStrings          uint16
    EventCategory       uint16
    ReservedFlags       uint16
    ClosingRecordNumber uint32
    StringOffset        uint32
    UserSidLength       uint32
    UserSidOffset       uint32
    DataLength          uint32
    DataOffset          uint32
}

type SERVICE_STATUS struct {
    DwServiceType             DWORD
    DwCurrentState            DWORD
    DwControlsAccepted        DWORD
    DwWin32ExitCode           DWORD
    DwServiceSpecificExitCode DWORD
    DwCheckPoint              DWORD
    DwWaitHint                DWORD
}

type MODULEENTRY32 struct {
    Size         uint32
    ModuleID     uint32
    ProcessID    uint32
    GlblcntUsage uint32
    ProccntUsage uint32
    ModBaseAddr  *uint8
    ModBaseSize  uint32
    HModule      HMODULE
    SzModule     [MAX_MODULE_NAME32 + 1]uint16
    SzExePath    [MAX_PATH]uint16
}

type FILETIME struct {
    DwLowDateTime  DWORD
    DwHighDateTime DWORD
}

type COORD struct {
    X, Y int16
}

type SMALL_RECT struct {
    Left, Top, Right, Bottom int16
}

type CONSOLE_SCREEN_BUFFER_INFO struct {
    DwSize              COORD
    DwCursorPosition    COORD
    WAttributes         uint16
    SrWindow            SMALL_RECT
    DwMaximumWindowSize COORD
}


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

package package_go_proto // import "github.com/grafeas/grafeas/proto/v1beta1/package_go_proto"

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

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

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

// Instruction set architectures supported by various package managers.
type Architecture int32

const (
	// Unknown architecture.
	Architecture_ARCHITECTURE_UNSPECIFIED Architecture = 0
	// X86 architecture.
	Architecture_X86 Architecture = 1
	// X64 architecture.
	Architecture_X64 Architecture = 2
)

var Architecture_name = map[int32]string{
	0: "ARCHITECTURE_UNSPECIFIED",
	1: "X86",
	2: "X64",
}
var Architecture_value = map[string]int32{
	"ARCHITECTURE_UNSPECIFIED": 0,
	"X86":                      1,
	"X64":                      2,
}

func (x Architecture) String() string {
	return proto.EnumName(Architecture_name, int32(x))
}
func (Architecture) EnumDescriptor() ([]byte, []int) {
	return fileDescriptor_package_c1e02d1b9928fa98, []int{0}
}

// Whether this is an ordinary package version or a sentinel MIN/MAX version.
type Version_VersionKind int32

const (
	// Unknown.
	Version_VERSION_KIND_UNSPECIFIED Version_VersionKind = 0
	// A standard package version.
	Version_NORMAL Version_VersionKind = 1
	// A special version representing negative infinity.
	Version_MINIMUM Version_VersionKind = 2
	// A special version representing positive infinity.
	Version_MAXIMUM Version_VersionKind = 3
)

var Version_VersionKind_name = map[int32]string{
	0: "VERSION_KIND_UNSPECIFIED",
	1: "NORMAL",
	2: "MINIMUM",
	3: "MAXIMUM",
}
var Version_VersionKind_value = map[string]int32{
	"VERSION_KIND_UNSPECIFIED": 0,
	"NORMAL":                   1,
	"MINIMUM":                  2,
	"MAXIMUM":                  3,
}

func (x Version_VersionKind) String() string {
	return proto.EnumName(Version_VersionKind_name, int32(x))
}
func (Version_VersionKind) EnumDescriptor() ([]byte, []int) {
	return fileDescriptor_package_c1e02d1b9928fa98, []int{5, 0}
}

// This represents a particular channel of distribution for a given package.
// E.g., Debian's jessie-backports dpkg mirror.
type Distribution struct {
	// Required. The cpe_uri in [CPE format](https://cpe.mitre.org/specification/)
	// denoting the package manager version distributing a package.
	CpeUri string `protobuf:"bytes,1,opt,name=cpe_uri,json=cpeUri,proto3" json:"cpe_uri,omitempty"`
	// The CPU architecture for which packages in this distribution channel were
	// built.
	Architecture Architecture `protobuf:"varint,2,opt,name=architecture,proto3,enum=grafeas.v1beta1.package.Architecture" json:"architecture,omitempty"`
	// The latest available version of this package in this distribution channel.
	LatestVersion *Version `protobuf:"bytes,3,opt,name=latest_version,json=latestVersion,proto3" json:"latest_version,omitempty"`
	// A freeform string denoting the maintainer of this package.
	Maintainer string `protobuf:"bytes,4,opt,name=maintainer,proto3" json:"maintainer,omitempty"`
	// The distribution channel-specific homepage for this package.
	Url string `protobuf:"bytes,5,opt,name=url,proto3" json:"url,omitempty"`
	// The distribution channel-specific description of this package.
	Description          string   `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *Distribution) Reset()         { *m = Distribution{} }
func (m *Distribution) String() string { return proto.CompactTextString(m) }
func (*Distribution) ProtoMessage()    {}
func (*Distribution) Descriptor() ([]byte, []int) {
	return fileDescriptor_package_c1e02d1b9928fa98, []int{0}
}
func (m *Distribution) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Distribution.Unmarshal(m, b)
}
func (m *Distribution) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Distribution.Marshal(b, m, deterministic)
}
func (dst *Distribution) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Distribution.Merge(dst, src)
}
func (m *Distribution) XXX_Size() int {
	return xxx_messageInfo_Distribution.Size(m)
}
func (m *Distribution) XXX_DiscardUnknown() {
	xxx_messageInfo_Distribution.DiscardUnknown(m)
}

var xxx_messageInfo_Distribution proto.InternalMessageInfo

func (m *Distribution) GetCpeUri() string {
	if m != nil {
		return m.CpeUri
	}
	return ""
}

func (m *Distribution) GetArchitecture() Architecture {
	if m != nil {
		return m.Architecture
	}
	return Architecture_ARCHITECTURE_UNSPECIFIED
}

func (m *Distribution) GetLatestVersion() *Version {
	if m != nil {
		return m.LatestVersion
	}
	return nil
}

func (m *Distribution) GetMaintainer() string {
	if m != nil {
		return m.Maintainer
	}
	return ""
}

func (m *Distribution) GetUrl() string {
	if m != nil {
		return m.Url
	}
	return ""
}

func (m *Distribution) GetDescription() string {
	if m != nil {
		return m.Description
	}
	return ""
}

// An occurrence of a particular package installation found within a system's
// filesystem. E.g., glibc was found in `/var/lib/dpkg/status`.
type Location struct {
	// Required. The CPE URI in [CPE format](https://cpe.mitre.org/specification/)
	// denoting the package manager version distributing a package.
	CpeUri string `protobuf:"bytes,1,opt,name=cpe_uri,json=cpeUri,proto3" json:"cpe_uri,omitempty"`
	// The version installed at this location.
	Version *Version `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"`
	// The path from which we gathered that this package/version is installed.
	Path                 string   `protobuf:"bytes,3,opt,name=path,proto3" json:"path,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *Location) Reset()         { *m = Location{} }
func (m *Location) String() string { return proto.CompactTextString(m) }
func (*Location) ProtoMessage()    {}
func (*Location) Descriptor() ([]byte, []int) {
	return fileDescriptor_package_c1e02d1b9928fa98, []int{1}
}
func (m *Location) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Location.Unmarshal(m, b)
}
func (m *Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Location.Marshal(b, m, deterministic)
}
func (dst *Location) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Location.Merge(dst, src)
}
func (m *Location) XXX_Size() int {
	return xxx_messageInfo_Location.Size(m)
}
func (m *Location) XXX_DiscardUnknown() {
	xxx_messageInfo_Location.DiscardUnknown(m)
}

var xxx_messageInfo_Location proto.InternalMessageInfo

func (m *Location) GetCpeUri() string {
	if m != nil {
		return m.CpeUri
	}
	return ""
}

func (m *Location) GetVersion() *Version {
	if m != nil {
		return m.Version
	}
	return nil
}

func (m *Location) GetPath() string {
	if m != nil {
		return m.Path
	}
	return ""
}

// This represents a particular package that is distributed over various
// channels. E.g., glibc (aka libc6) is distributed by many, at various
// versions.
type Package struct {
	// Required. Immutable. The name of the package.
	Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
	// The various channels by which a package is distributed.
	Distribution         []*Distribution `protobuf:"bytes,10,rep,name=distribution,proto3" json:"distribution,omitempty"`
	XXX_NoUnkeyedLiteral struct{}        `json:"-"`
	XXX_unrecognized     []byte          `json:"-"`
	XXX_sizecache        int32           `json:"-"`
}

func (m *Package) Reset()         { *m = Package{} }
func (m *Package) String() string { return proto.CompactTextString(m) }
func (*Package) ProtoMessage()    {}
func (*Package) Descriptor() ([]byte, []int) {
	return fileDescriptor_package_c1e02d1b9928fa98, []int{2}
}
func (m *Package) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Package.Unmarshal(m, b)
}
func (m *Package) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Package.Marshal(b, m, deterministic)
}
func (dst *Package) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Package.Merge(dst, src)
}
func (m *Package) XXX_Size() int {
	return xxx_messageInfo_Package.Size(m)
}
func (m *Package) XXX_DiscardUnknown() {
	xxx_messageInfo_Package.DiscardUnknown(m)
}

var xxx_messageInfo_Package proto.InternalMessageInfo

func (m *Package) GetName() string {
	if m != nil {
		return m.Name
	}
	return ""
}

func (m *Package) GetDistribution() []*Distribution {
	if m != nil {
		return m.Distribution
	}
	return nil
}

// Details of a package occurrence.
type Details struct {
	// Required. Where the package was installed.
	Installation         *Installation `protobuf:"bytes,1,opt,name=installation,proto3" json:"installation,omitempty"`
	XXX_NoUnkeyedLiteral struct{}      `json:"-"`
	XXX_unrecognized     []byte        `json:"-"`
	XXX_sizecache        int32         `json:"-"`
}

func (m *Details) Reset()         { *m = Details{} }
func (m *Details) String() string { return proto.CompactTextString(m) }
func (*Details) ProtoMessage()    {}
func (*Details) Descriptor() ([]byte, []int) {
	return fileDescriptor_package_c1e02d1b9928fa98, []int{3}
}
func (m *Details) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Details.Unmarshal(m, b)
}
func (m *Details) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Details.Marshal(b, m, deterministic)
}
func (dst *Details) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Details.Merge(dst, src)
}
func (m *Details) XXX_Size() int {
	return xxx_messageInfo_Details.Size(m)
}
func (m *Details) XXX_DiscardUnknown() {
	xxx_messageInfo_Details.DiscardUnknown(m)
}

var xxx_messageInfo_Details proto.InternalMessageInfo

func (m *Details) GetInstallation() *Installation {
	if m != nil {
		return m.Installation
	}
	return nil
}

// This represents how a particular software package may be installed on a
// system.
type Installation struct {
	// Output only. The name of the installed package.
	Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
	// Required. All of the places within the filesystem versions of this package
	// have been found.
	Location             []*Location `protobuf:"bytes,2,rep,name=location,proto3" json:"location,omitempty"`
	XXX_NoUnkeyedLiteral struct{}    `json:"-"`
	XXX_unrecognized     []byte      `json:"-"`
	XXX_sizecache        int32       `json:"-"`
}

func (m *Installation) Reset()         { *m = Installation{} }
func (m *Installation) String() string { return proto.CompactTextString(m) }
func (*Installation) ProtoMessage()    {}
func (*Installation) Descriptor() ([]byte, []int) {
	return fileDescriptor_package_c1e02d1b9928fa98, []int{4}
}
func (m *Installation) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Installation.Unmarshal(m, b)
}
func (m *Installation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Installation.Marshal(b, m, deterministic)
}
func (dst *Installation) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Installation.Merge(dst, src)
}
func (m *Installation) XXX_Size() int {
	return xxx_messageInfo_Installation.Size(m)
}
func (m *Installation) XXX_DiscardUnknown() {
	xxx_messageInfo_Installation.DiscardUnknown(m)
}

var xxx_messageInfo_Installation proto.InternalMessageInfo

func (m *Installation) GetName() string {
	if m != nil {
		return m.Name
	}
	return ""
}

func (m *Installation) GetLocation() []*Location {
	if m != nil {
		return m.Location
	}
	return nil
}

// Version contains structured information about the version of a package.
type Version struct {
	// Used to correct mistakes in the version numbering scheme.
	Epoch int32 `protobuf:"varint,1,opt,name=epoch,proto3" json:"epoch,omitempty"`
	// Required only when version kind is NORMAL. The main part of the version
	// name.
	Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
	// The iteration of the package build from the above version.
	Revision string `protobuf:"bytes,3,opt,name=revision,proto3" json:"revision,omitempty"`
	// Required. Distinguishes between sentinel MIN/MAX versions and normal
	// versions.
	Kind                 Version_VersionKind `protobuf:"varint,4,opt,name=kind,proto3,enum=grafeas.v1beta1.package.Version_VersionKind" json:"kind,omitempty"`
	XXX_NoUnkeyedLiteral struct{}            `json:"-"`
	XXX_unrecognized     []byte              `json:"-"`
	XXX_sizecache        int32               `json:"-"`
}

func (m *Version) Reset()         { *m = Version{} }
func (m *Version) String() string { return proto.CompactTextString(m) }
func (*Version) ProtoMessage()    {}
func (*Version) Descriptor() ([]byte, []int) {
	return fileDescriptor_package_c1e02d1b9928fa98, []int{5}
}
func (m *Version) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Version.Unmarshal(m, b)
}
func (m *Version) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Version.Marshal(b, m, deterministic)
}
func (dst *Version) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Version.Merge(dst, src)
}
func (m *Version) XXX_Size() int {
	return xxx_messageInfo_Version.Size(m)
}
func (m *Version) XXX_DiscardUnknown() {
	xxx_messageInfo_Version.DiscardUnknown(m)
}

var xxx_messageInfo_Version proto.InternalMessageInfo

func (m *Version) GetEpoch() int32 {
	if m != nil {
		return m.Epoch
	}
	return 0
}

func (m *Version) GetName() string {
	if m != nil {
		return m.Name
	}
	return ""
}

func (m *Version) GetRevision() string {
	if m != nil {
		return m.Revision
	}
	return ""
}

func (m *Version) GetKind() Version_VersionKind {
	if m != nil {
		return m.Kind
	}
	return Version_VERSION_KIND_UNSPECIFIED
}

func init() {
	proto.RegisterType((*Distribution)(nil), "grafeas.v1beta1.package.Distribution")
	proto.RegisterType((*Location)(nil), "grafeas.v1beta1.package.Location")
	proto.RegisterType((*Package)(nil), "grafeas.v1beta1.package.Package")
	proto.RegisterType((*Details)(nil), "grafeas.v1beta1.package.Details")
	proto.RegisterType((*Installation)(nil), "grafeas.v1beta1.package.Installation")
	proto.RegisterType((*Version)(nil), "grafeas.v1beta1.package.Version")
	proto.RegisterEnum("grafeas.v1beta1.package.Architecture", Architecture_name, Architecture_value)
	proto.RegisterEnum("grafeas.v1beta1.package.Version_VersionKind", Version_VersionKind_name, Version_VersionKind_value)
}

func init() {
	proto.RegisterFile("proto/v1beta1/package.proto", fileDescriptor_package_c1e02d1b9928fa98)
}

var fileDescriptor_package_c1e02d1b9928fa98 = []byte{
	// 544 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x54, 0xf1, 0x8e, 0xd2, 0x4e,
	0x10, 0xfe, 0xb5, 0x05, 0x0a, 0x03, 0x3f, 0xd2, 0x6c, 0x8c, 0xd7, 0xa8, 0x31, 0xb5, 0x89, 0x09,
	0x31, 0xa6, 0xe4, 0xd0, 0x5c, 0xd4, 0x44, 0x23, 0x02, 0x9e, 0xcd, 0x1d, 0x1c, 0xee, 0xc1, 0xe5,
	0xa2, 0x7f, 0x34, 0x4b, 0x59, 0x61, 0x43, 0x69, 0x9b, 0xed, 0xc2, 0x6b, 0xf8, 0x0e, 0x3e, 0x9b,
	0x0f, 0x62, 0xba, 0x14, 0x52, 0xf4, 0x40, 0xff, 0xda, 0x99, 0xf9, 0xe6, 0xfb, 0x66, 0x67, 0x66,
	0x5b, 0x78, 0x18, 0xf3, 0x48, 0x44, 0xcd, 0xf5, 0xe9, 0x84, 0x0a, 0x72, 0xda, 0x8c, 0x89, 0xbf,
	0x20, 0x33, 0xea, 0xc8, 0x28, 0x3a, 0x99, 0x71, 0xf2, 0x8d, 0x92, 0xc4, 0xc9, 0x60, 0x27, 0x83,
	0xed, 0xef, 0x2a, 0xd4, 0xba, 0x2c, 0x11, 0x9c, 0x4d, 0x56, 0x82, 0x45, 0x21, 0x3a, 0x01, 0xdd,
	0x8f, 0xa9, 0xb7, 0xe2, 0xcc, 0x54, 0x2c, 0xa5, 0x51, 0xc1, 0x25, 0x3f, 0xa6, 0x63, 0xce, 0x90,
	0x0b, 0x35, 0xc2, 0xfd, 0x39, 0x13, 0xd4, 0x17, 0x2b, 0x4e, 0x4d, 0xd5, 0x52, 0x1a, 0xf5, 0xd6,
	0x53, 0xe7, 0x80, 0xb2, 0xd3, 0xce, 0x25, 0xe3, 0x3d, 0x2a, 0x3a, 0x87, 0x7a, 0x40, 0x04, 0x4d,
	0x84, 0xb7, 0xa6, 0x3c, 0x61, 0x51, 0x68, 0x6a, 0x96, 0xd2, 0xa8, 0xb6, 0xac, 0x83, 0x62, 0x37,
	0x9b, 0x3c, 0xfc, 0xff, 0x86, 0x97, 0xb9, 0xe8, 0x31, 0xc0, 0x92, 0xb0, 0x50, 0x10, 0x16, 0x52,
	0x6e, 0x16, 0xe4, 0x7d, 0x73, 0x11, 0x64, 0x80, 0xb6, 0xe2, 0x81, 0x59, 0x94, 0x40, 0x6a, 0x22,
	0x0b, 0xaa, 0x53, 0x9a, 0xf8, 0x9c, 0xc5, 0x69, 0xb7, 0x66, 0x49, 0x22, 0xf9, 0x90, 0x9d, 0x40,
	0xf9, 0x32, 0xf2, 0xc9, 0xf1, 0x61, 0xbc, 0x01, 0x7d, 0x7b, 0x75, 0xf5, 0x1f, 0xaf, 0xbe, 0x25,
	0x20, 0x04, 0x85, 0x98, 0x88, 0xb9, 0xec, 0xb9, 0x82, 0xa5, 0x6d, 0xcf, 0x41, 0x1f, 0x6e, 0xf2,
	0x53, 0x38, 0x24, 0x4b, 0x9a, 0x15, 0x94, 0x76, 0x3a, 0xfb, 0x69, 0x6e, 0x49, 0x26, 0x58, 0x5a,
	0xa3, 0x7a, 0x64, 0xf6, 0xf9, 0x8d, 0xe2, 0x3d, 0xaa, 0x3d, 0x02, 0xbd, 0x4b, 0x05, 0x61, 0x41,
	0x92, 0xaa, 0xb2, 0x30, 0x11, 0x24, 0x08, 0x64, 0xb7, 0xb2, 0xe2, 0x31, 0x55, 0x37, 0x97, 0x8c,
	0xf7, 0xa8, 0x36, 0x81, 0x5a, 0x1e, 0xbd, 0xb3, 0x89, 0xb7, 0x50, 0x0e, 0xb2, 0xc1, 0x9a, 0xaa,
	0x6c, 0xe0, 0xc9, 0xc1, 0x52, 0xdb, 0x0d, 0xe0, 0x1d, 0xc5, 0xfe, 0xa9, 0x80, 0xbe, 0xdd, 0xfb,
	0x3d, 0x28, 0xd2, 0x38, 0xf2, 0xe7, 0x52, 0xbf, 0x88, 0x37, 0xce, 0xae, 0xa8, 0x9a, 0x2b, 0xfa,
	0x00, 0xca, 0x9c, 0xae, 0xd9, 0xee, 0x91, 0x55, 0xf0, 0xce, 0x47, 0xef, 0xa1, 0xb0, 0x60, 0xe1,
	0x54, 0xbe, 0x9b, 0x7a, 0xeb, 0xf9, 0xdf, 0x36, 0xb8, 0x3d, 0x2f, 0x58, 0x38, 0xc5, 0x92, 0x69,
	0x7f, 0x86, 0x6a, 0x2e, 0x88, 0x1e, 0x81, 0x79, 0xd3, 0xc3, 0xd7, 0xee, 0xd5, 0xc0, 0xbb, 0x70,
	0x07, 0x5d, 0x6f, 0x3c, 0xb8, 0x1e, 0xf6, 0x3a, 0xee, 0x47, 0xb7, 0xd7, 0x35, 0xfe, 0x43, 0x00,
	0xa5, 0xc1, 0x15, 0xee, 0xb7, 0x2f, 0x0d, 0x05, 0x55, 0x41, 0xef, 0xbb, 0x03, 0xb7, 0x3f, 0xee,
	0x1b, 0xaa, 0x74, 0xda, 0xb7, 0xd2, 0xd1, 0x9e, 0xbd, 0x83, 0x5a, 0xfe, 0xcb, 0x49, 0x35, 0xdb,
	0xb8, 0xf3, 0xc9, 0x1d, 0xf5, 0x3a, 0xa3, 0x31, 0xee, 0xfd, 0xa6, 0xa9, 0x83, 0x76, 0xfb, 0xea,
	0xcc, 0x50, 0xa4, 0x71, 0xf6, 0xd2, 0x50, 0x3f, 0x7c, 0x85, 0xfb, 0x2c, 0xfa, 0xb3, 0x95, 0xc5,
	0x6c, 0xa8, 0x7c, 0x79, 0x3d, 0x63, 0x62, 0xbe, 0x9a, 0x38, 0x7e, 0xb4, 0x6c, 0x66, 0x19, 0xbb,
	0xf3, 0xce, 0xbf, 0x87, 0x37, 0x8b, 0x3c, 0x09, 0xfc, 0x50, 0xb5, 0x73, 0xdc, 0x9e, 0x94, 0xa4,
	0xf3, 0xe2, 0x57, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb4, 0xeb, 0x17, 0x87, 0x6c, 0x04, 0x00, 0x00,
}

repository: twistlock/grafeas

repo_name: twistlock/grafeas


text:
package util

import (
	"reflect"
)

// ReflectValue returns reflect value underlying given value, unwrapping pointer and slice
func ReflectValue(v interface{}) reflect.Value {
	rv, ok := v.(reflect.Value)
	if !ok {
		rv = reflect.ValueOf(v)
	}
	for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Slice {
		rv = rv.Elem()
	}
	return rv
}

// ReflectType returns reflect type underlying given value, unwrapping pointer and slice
func ReflectType(v interface{}) reflect.Type {
	var rt reflect.Type
	if rvt, ok := v.(reflect.Type); ok {
		rt = rvt
	} else {
		rv, ok := v.(reflect.Value)
		if !ok {
			rv = reflect.ValueOf(v)
		}
		rt = rv.Type()
	}
	for rt.Kind() == reflect.Ptr || rt.Kind() == reflect.Slice {
		rt = rt.Elem()
	}
	return rt
}

repository: pilagod/gorm-cursor-paginator

repo_name: pilagod/gorm-cursor-paginator


text:
file(REMOVE_RECURSE
  "CMakeFiles/example_connected_components.dir/connected_components.cpp.o"
  "../../bin/cpp-example-connected_components.pdb"
  "../../bin/cpp-example-connected_components"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/example_connected_components.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

repository: rajkataria/ReliableResectioning

repo_name: rajkataria/ReliableResectioning


text:
LICENSE     = "LGPL"
DESCRIPTION = "libgpewidget contains a collection of widgets and other common code shared by many GPE applications."
SECTION     = "gpe/libs"
PRIORITY    = "optional"
DEPENDS     = "gtk+ cairo libxrender gtk-doc intltool-native"
MAINTAINER  = "Florian Boor <florian.boor@kernelconcepts.de>"
PR          = "r1"

PACKAGES =+ "libgpewidget-bin"

PARALLEL_MAKE = ""

SRC_URI = "${GPE_MIRROR}/${PN}-${PV}.tar.bz2 \
           file://pkgconfig.patch;patch=1;pnum=0"

inherit pkgconfig autotools

FILES_libgpewidget-bin = "${bindir}"

EXTRA_OECONF = "--enable-cairo"

LDFLAGS += " -L${STAGING_LIBDIR}"

do_stage () {
	autotools_stage_all
}

do_configure () {
	autotools_do_configure
}

repository: Terentyev/familiar-linux

repo_name: Terentyev/familiar-linux


text:
package storegateway

import (
	"context"

	"github.com/go-kit/log"
	"github.com/go-kit/log/level"
	"github.com/oklog/ulid"
	"github.com/thanos-io/objstore"
	"github.com/thanos-io/thanos/pkg/block"
	"github.com/thanos-io/thanos/pkg/block/metadata"

	"github.com/cortexproject/cortex/pkg/ring"
	cortex_tsdb "github.com/cortexproject/cortex/pkg/storage/tsdb"
	"github.com/cortexproject/cortex/pkg/util"
)

const (
	shardExcludedMeta = "shard-excluded"
)

type ShardingStrategy interface {
	// FilterUsers whose blocks should be loaded by the store-gateway. Returns the list of user IDs
	// that should be synced by the store-gateway.
	FilterUsers(ctx context.Context, userIDs []string) []string

	// FilterBlocks filters metas in-place keeping only blocks that should be loaded by the store-gateway.
	// The provided loaded map contains blocks which have been previously returned by this function and
	// are now loaded or loading in the store-gateway.
	FilterBlocks(ctx context.Context, userID string, metas map[ulid.ULID]*metadata.Meta, loaded map[ulid.ULID]struct{}, synced block.GaugeVec) error
}

// ShardingLimits is the interface that should be implemented by the limits provider,
// limiting the scope of the limits to the ones required by sharding strategies.
type ShardingLimits interface {
	StoreGatewayTenantShardSize(userID string) float64
}

// NoShardingStrategy is a no-op strategy. When this strategy is used, no tenant/block is filtered out.
type NoShardingStrategy struct{}

func NewNoShardingStrategy() *NoShardingStrategy {
	return &NoShardingStrategy{}
}

func (s *NoShardingStrategy) FilterUsers(_ context.Context, userIDs []string) []string {
	return userIDs
}

func (s *NoShardingStrategy) FilterBlocks(_ context.Context, _ string, _ map[ulid.ULID]*metadata.Meta, _ map[ulid.ULID]struct{}, _ block.GaugeVec) error {
	return nil
}

// DefaultShardingStrategy is a sharding strategy based on the hash ring formed by store-gateways.
// Not go-routine safe.
type DefaultShardingStrategy struct {
	r            *ring.Ring
	instanceAddr string
	logger       log.Logger
}

// NewDefaultShardingStrategy creates DefaultShardingStrategy.
func NewDefaultShardingStrategy(r *ring.Ring, instanceAddr string, logger log.Logger) *DefaultShardingStrategy {
	return &DefaultShardingStrategy{
		r:            r,
		instanceAddr: instanceAddr,
		logger:       logger,
	}
}

// FilterUsers implements ShardingStrategy.
func (s *DefaultShardingStrategy) FilterUsers(_ context.Context, userIDs []string) []string {
	return userIDs
}

// FilterBlocks implements ShardingStrategy.
func (s *DefaultShardingStrategy) FilterBlocks(_ context.Context, _ string, metas map[ulid.ULID]*metadata.Meta, loaded map[ulid.ULID]struct{}, synced block.GaugeVec) error {
	filterBlocksByRingSharding(s.r, s.instanceAddr, metas, loaded, synced, s.logger)
	return nil
}

// ShuffleShardingStrategy is a shuffle sharding strategy, based on the hash ring formed by store-gateways,
// where each tenant blocks are sharded across a subset of store-gateway instances.
type ShuffleShardingStrategy struct {
	r            *ring.Ring
	instanceID   string
	instanceAddr string
	limits       ShardingLimits
	logger       log.Logger

	zoneStableShuffleSharding bool
}

// NewShuffleShardingStrategy makes a new ShuffleShardingStrategy.
func NewShuffleShardingStrategy(r *ring.Ring, instanceID, instanceAddr string, limits ShardingLimits, logger log.Logger, zoneStableShuffleSharding bool) *ShuffleShardingStrategy {
	return &ShuffleShardingStrategy{
		r:            r,
		instanceID:   instanceID,
		instanceAddr: instanceAddr,
		limits:       limits,
		logger:       logger,

		zoneStableShuffleSharding: zoneStableShuffleSharding,
	}
}

// FilterUsers implements ShardingStrategy.
func (s *ShuffleShardingStrategy) FilterUsers(_ context.Context, userIDs []string) []string {
	var filteredIDs []string

	for _, userID := range userIDs {
		subRing := GetShuffleShardingSubring(s.r, userID, s.limits, s.zoneStableShuffleSharding)

		// Include the user only if it belongs to this store-gateway shard.
		if subRing.HasInstance(s.instanceID) {
			filteredIDs = append(filteredIDs, userID)
		}
	}

	return filteredIDs
}

// FilterBlocks implements ShardingStrategy.
func (s *ShuffleShardingStrategy) FilterBlocks(_ context.Context, userID string, metas map[ulid.ULID]*metadata.Meta, loaded map[ulid.ULID]struct{}, synced block.GaugeVec) error {
	subRing := GetShuffleShardingSubring(s.r, userID, s.limits, s.zoneStableShuffleSharding)
	filterBlocksByRingSharding(subRing, s.instanceAddr, metas, loaded, synced, s.logger)
	return nil
}

func filterBlocksByRingSharding(r ring.ReadRing, instanceAddr string, metas map[ulid.ULID]*metadata.Meta, loaded map[ulid.ULID]struct{}, synced block.GaugeVec, logger log.Logger) {
	bufDescs, bufHosts, bufZones := ring.MakeBuffersForGet()

	for blockID := range metas {
		key := cortex_tsdb.HashBlockID(blockID)

		// Check if the block is owned by the store-gateway
		set, err := r.Get(key, BlocksOwnerSync, bufDescs, bufHosts, bufZones)

		// If an error occurs while checking the ring, we keep the previously loaded blocks.
		if err != nil {
			if _, ok := loaded[blockID]; ok {
				level.Warn(logger).Log("msg", "failed to check block owner but block is kept because was previously loaded", "block", blockID.String(), "err", err)
			} else {
				level.Warn(logger).Log("msg", "failed to check block owner and block has been excluded because was not previously loaded", "block", blockID.String(), "err", err)

				// Skip the block.
				synced.WithLabelValues(shardExcludedMeta).Inc()
				delete(metas, blockID)
			}

			continue
		}

		// Keep the block if it is owned by the store-gateway.
		if set.Includes(instanceAddr) {
			continue
		}

		// The block is not owned by the store-gateway. However, if it's currently loaded
		// we can safely unload it only once at least 1 authoritative owner is available
		// for queries.
		if _, ok := loaded[blockID]; ok {
			// The ring Get() returns an error if there's no available instance.
			if _, err := r.Get(key, BlocksOwnerRead, bufDescs, bufHosts, bufZones); err != nil {
				// Keep the block.
				continue
			}
		}

		// The block is not owned by the store-gateway and there's at least 1 available
		// authoritative owner available for queries, so we can filter it out (and unload
		// it if it was loaded).
		synced.WithLabelValues(shardExcludedMeta).Inc()
		delete(metas, blockID)
	}
}

// GetShuffleShardingSubring returns the subring to be used for a given user. This function
// should be used both by store-gateway and querier in order to guarantee the same logic is used.
func GetShuffleShardingSubring(ring *ring.Ring, userID string, limits ShardingLimits, zoneStableShuffleSharding bool) ring.ReadRing {
	shardSize := util.DynamicShardSize(limits.StoreGatewayTenantShardSize(userID), ring.InstancesCount())

	// A shard size of 0 means shuffle sharding is disabled for this specific user,
	// so we just return the full ring so that blocks will be sharded across all store-gateways.
	if shardSize <= 0 {
		return ring
	}

	if zoneStableShuffleSharding {
		// Zone stability is required for store gateway when shuffle shard, see
		// https://github.com/cortexproject/cortex/issues/5467 for more details.
		return ring.ShuffleShardWithZoneStability(userID, shardSize)
	}
	return ring.ShuffleShard(userID, shardSize)
}

type shardingMetadataFilterAdapter struct {
	userID   string
	strategy ShardingStrategy

	// Keep track of the last blocks returned by the Filter() function.
	lastBlocks map[ulid.ULID]struct{}
}

func NewShardingMetadataFilterAdapter(userID string, strategy ShardingStrategy) block.MetadataFilter {
	return &shardingMetadataFilterAdapter{
		userID:     userID,
		strategy:   strategy,
		lastBlocks: map[ulid.ULID]struct{}{},
	}
}

// Filter implements block.MetadataFilter.
// This function is NOT safe for use by multiple goroutines concurrently.
func (a *shardingMetadataFilterAdapter) Filter(ctx context.Context, metas map[ulid.ULID]*metadata.Meta, synced block.GaugeVec, _ block.GaugeVec) error {
	if err := a.strategy.FilterBlocks(ctx, a.userID, metas, a.lastBlocks, synced); err != nil {
		return err
	}

	// Keep track of the last filtered blocks.
	a.lastBlocks = make(map[ulid.ULID]struct{}, len(metas))
	for blockID := range metas {
		a.lastBlocks[blockID] = struct{}{}
	}

	return nil
}

type shardingBucketReaderAdapter struct {
	objstore.InstrumentedBucketReader

	userID   string
	strategy ShardingStrategy
}

func NewShardingBucketReaderAdapter(userID string, strategy ShardingStrategy, wrapped objstore.InstrumentedBucketReader) objstore.InstrumentedBucketReader {
	return &shardingBucketReaderAdapter{
		InstrumentedBucketReader: wrapped,
		userID:                   userID,
		strategy:                 strategy,
	}
}

// Iter implements objstore.BucketReader.
func (a *shardingBucketReaderAdapter) Iter(ctx context.Context, dir string, f func(string) error, options ...objstore.IterOption) error {
	// Skip iterating the bucket if the tenant doesn't belong to the shard. From the caller
	// perspective, this will look like the tenant has no blocks in the storage.
	if len(a.strategy.FilterUsers(ctx, []string{a.userID})) == 0 {
		return nil
	}

	return a.InstrumentedBucketReader.Iter(ctx, dir, f, options...)
}

repository: cortexproject/cortex

repo_name: cortexproject/cortex