text:
/*
Copyright 2015 The Kubernetes Authors All rights reserved.

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

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

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

/**
 * Copyright 2016, Z Lab Corporation. All rights reserved.
 * Copyright 2017, nghttpx Ingress controller contributors
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

package nghttpx

import (
	"runtime"
	"strconv"
)

// Interface is the API to update underlying load balancer.
type Interface interface {
	// Start starts a nghttpx process using executable at path with configuration file at confPath, and wait.  If stopCh becomes
	// readable, kill nghttpx process, and return.
	Start(path, confPath string, stopCh <-chan struct{})
	// CheckAndReload checks whether the nghttpx configuration changed, and if so, make nghttpx reload its configuration.  If reloading
	// is required, and it successfully issues reloading, returns true.  If there is no need to reloading, it returns false.  On error,
	// it returns false, and non-nil error.
	CheckAndReload(ingressCfg *IngressConfig) (bool, error)
}

// IngressConfig describes an nghttpx configuration
type IngressConfig struct {
	Upstreams      []*Upstream
	TLS            bool
	DefaultTLSCred *TLSCred
	SubTLSCred     []*TLSCred
	// https://nghttp2.org/documentation/nghttpx.1.html#cmdoption-nghttpx-n
	// Set the number of worker threads.
	Workers string
	// ExtraConfig is the extra configurations in a format that nghttpx accepts in --conf.
	ExtraConfig string
	// MrubyFileContent is the extra mruby script.  It is saved in the container disk space, and will be referenced by mruby-file from
	// configuration file.
	MrubyFile *ChecksumFile
	// HealthPort is the port for health monitor endpoint.
	HealthPort int
	// APIPort is the port for API endpoint.
	APIPort int
	// ConfDir is the path to the directory which includes nghttpx configuration files.
	ConfDir string
	// HTTPPort is the port to listen to for HTTP (non-TLS) request.
	HTTPPort int
	// HTTPSPort is the port to listen to for HTTPS (TLS) request.
	HTTPSPort int
	// FetchOCSPRespFromSecret is true if OCSP response is fetched from TLS secret.
	FetchOCSPRespFromSecret bool
}

// NewIngressConfig returns new IngressConfig.  Workers is initialized as the number of CPU cores.
func NewIngressConfig() *IngressConfig {
	return &IngressConfig{
		Workers: strconv.Itoa(runtime.NumCPU()),
	}
}

// Upstream describes an nghttpx upstream
type Upstream struct {
	Name             string
	Host             string
	Path             string
	Backends         []UpstreamServer
	RedirectIfNotTLS bool
}

type Affinity string

const (
	AffinityNone = "none"
	AffinityIP   = "ip"
)

type Protocol string

const (
	// HTTP/2 protocol
	ProtocolH2 = "h2"
	// HTTP/1.1 protocol
	ProtocolH1 = "http/1.1"
)

// UpstreamServer describes a server in an nghttpx upstream
type UpstreamServer struct {
	Address  string
	Port     string
	Protocol Protocol
	TLS      bool
	SNI      string
	DNS      bool
	Affinity Affinity
}

// TLS server private key, certificate file path, and optionally OCSP response.  OCSP response must be DER encoded byte string.
type TLSCred struct {
	Key      ChecksumFile
	Cert     ChecksumFile
	OCSPResp ChecksumFile
}

// NewDefaultServer return an UpstreamServer to be use as default server that returns 503.
func NewDefaultServer() UpstreamServer {
	return UpstreamServer{
		Address: "127.0.0.1",
		Port:    "8181",
		// Update DefaultPortBackendConfig() too.
		Protocol: ProtocolH1,
		Affinity: AffinityNone,
	}
}

// backend configuration obtained from ingress annotation, specified per service port
type PortBackendConfig struct {
	// backend application protocol.  At the moment, this should be either ProtocolH2 or ProtocolH1.
	Proto Protocol `json:"proto,omitempty"`
	// true if backend connection requires TLS
	TLS bool `json:"tls,omitempty"`
	// SNI hostname for backend TLS connection
	SNI string `json:"sni,omitempty"`
	// DNS is true if backend hostname is resolved dynamically rather than start up or configuration reloading.
	DNS bool `json:"dns,omitempty"`
	// Affinity is session affinity method nghttpx supports.  See affinity parameter in backend option of nghttpx.
	Affinity Affinity `json:"affinity,omitempty"`
}

// ChecksumFile represents a file with path, its arbitrary content, and its checksum.
type ChecksumFile struct {
	Path     string
	Content  []byte
	Checksum string
}

repository: iosphere/nghttpx-ingress-lb

repo_name: iosphere/nghttpx-ingress-lb


text:
/*
Copyright 2018 Gravitational, 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 helpers

import (
	"context"
	"fmt"
	"net"
	"os"
	"os/exec"
	"os/user"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/google/uuid"
	"github.com/gravitational/trace"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/crypto/ssh/agent"

	"github.com/gravitational/teleport/api/breaker"
	"github.com/gravitational/teleport/api/client/proto"
	"github.com/gravitational/teleport/api/constants"
	apidefaults "github.com/gravitational/teleport/api/defaults"
	"github.com/gravitational/teleport/api/types"
	apievents "github.com/gravitational/teleport/api/types/events"
	"github.com/gravitational/teleport/api/utils/retryutils"
	"github.com/gravitational/teleport/lib"
	"github.com/gravitational/teleport/lib/auth"
	"github.com/gravitational/teleport/lib/backend"
	"github.com/gravitational/teleport/lib/client"
	"github.com/gravitational/teleport/lib/client/identityfile"
	"github.com/gravitational/teleport/lib/cloud"
	"github.com/gravitational/teleport/lib/defaults"
	"github.com/gravitational/teleport/lib/events"
	"github.com/gravitational/teleport/lib/multiplexer"
	"github.com/gravitational/teleport/lib/service"
	"github.com/gravitational/teleport/lib/service/servicecfg"
	"github.com/gravitational/teleport/lib/services"
	"github.com/gravitational/teleport/lib/teleagent"
	"github.com/gravitational/teleport/lib/utils"
)

// CommandOptions controls how the SSH command is built.
type CommandOptions struct {
	ForwardAgent bool
	ForcePTY     bool
	ControlPath  string
	SocketPath   string
	ProxyPort    string
	NodePort     string
	Command      string
}

// ExternalSSHCommand runs an external SSH command (if an external ssh binary
// exists) with the passed in parameters.
func ExternalSSHCommand(o CommandOptions) (*exec.Cmd, error) {
	var execArgs []string

	// Don't check the host certificate as part of the testing an external SSH
	// client, this is done elsewhere.
	execArgs = append(execArgs, "-oStrictHostKeyChecking=no")
	execArgs = append(execArgs, "-oUserKnownHostsFile=/dev/null")

	// ControlMaster is often used by applications like Ansible.
	if o.ControlPath != "" {
		execArgs = append(execArgs, "-oControlMaster=auto")
		execArgs = append(execArgs, "-oControlPersist=1s")
		execArgs = append(execArgs, "-oConnectTimeout=2")
		execArgs = append(execArgs, fmt.Sprintf("-oControlPath=%v", o.ControlPath))
	}

	// The -tt flag is used to force PTY allocation. It's often used by
	// applications like Ansible.
	if o.ForcePTY {
		execArgs = append(execArgs, "-tt")
	}

	// Connect to node on the passed in port.
	execArgs = append(execArgs, fmt.Sprintf("-p %v", o.NodePort))

	// Build proxy command.
	proxyCommand := []string{"ssh"}
	proxyCommand = append(proxyCommand, "-oStrictHostKeyChecking=no")
	proxyCommand = append(proxyCommand, "-oUserKnownHostsFile=/dev/null")
	if o.ForwardAgent {
		proxyCommand = append(proxyCommand, "-oForwardAgent=yes")
	}
	proxyCommand = append(proxyCommand, fmt.Sprintf("-p %v", o.ProxyPort))
	proxyCommand = append(proxyCommand, `%r@localhost -s proxy:%h:%p`)

	// Add in ProxyCommand option, needed for all Teleport connections.
	execArgs = append(execArgs, fmt.Sprintf("-oProxyCommand=%v", strings.Join(proxyCommand, " ")))

	// Add in the host to connect to and the command to run when connected.
	execArgs = append(execArgs, Host)
	execArgs = append(execArgs, o.Command)

	// Find the OpenSSH binary.
	sshpath, err := exec.LookPath("ssh")
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// Create an exec.Command and tell it where to find the SSH agent.
	cmd, err := exec.Command(sshpath, execArgs...), nil
	if err != nil {
		return nil, trace.Wrap(err)
	}
	cmd.Env = []string{fmt.Sprintf("SSH_AUTH_SOCK=%v", o.SocketPath)}

	return cmd, nil
}

// CreateAgent creates a SSH agent with the passed in private key and
// certificate that can be used in tests. This is useful so tests don't
// clobber your system agent.
func CreateAgent(me *user.User, key *client.Key) (*teleagent.AgentServer, string, string, error) {
	// create a path to the unix socket
	sockDirName := "int-test"
	sockName := "agent.sock"

	agentKey, err := key.AsAgentKey()
	if err != nil {
		return nil, "", "", trace.Wrap(err)
	}

	// create a (unstarted) agent and add the agent key(s) to it
	keyring, ok := agent.NewKeyring().(agent.ExtendedAgent)
	if !ok {
		return nil, "", "", trace.Errorf("unexpected keyring type: %T, expected agent.ExtendedKeyring", keyring)
	}

	if err := keyring.Add(agentKey); err != nil {
		return nil, "", "", trace.Wrap(err)
	}

	teleAgent := teleagent.NewServer(func() (teleagent.Agent, error) {
		return teleagent.NopCloser(keyring), nil
	})

	// start the SSH agent
	err = teleAgent.ListenUnixSocket(sockDirName, sockName, me)
	if err != nil {
		return nil, "", "", trace.Wrap(err)
	}
	go teleAgent.Serve()

	return teleAgent, teleAgent.Dir, teleAgent.Path, nil
}

func CloseAgent(teleAgent *teleagent.AgentServer, socketDirPath string) error {
	err := teleAgent.Close()
	if err != nil {
		return trace.Wrap(err)
	}

	err = os.RemoveAll(socketDirPath)
	if err != nil {
		return trace.Wrap(err)
	}

	return nil
}

// GetLocalIP gets the non-loopback IP address of this host.
func GetLocalIP() (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", trace.Wrap(err)
	}
	for _, addr := range addrs {
		var ip net.IP
		switch v := addr.(type) {
		case *net.IPNet:
			ip = v.IP
		case *net.IPAddr:
			ip = v.IP
		default:
			continue
		}
		if !ip.IsLoopback() && ip.IsPrivate() {
			return ip.String(), nil
		}
	}
	return "", trace.NotFound("No non-loopback local IP address found")
}

func MustCreateUserIdentityFile(t *testing.T, tc *TeleInstance, username string, ttl time.Duration) string {
	key, err := client.GenerateRSAKey()
	require.NoError(t, err)
	key.ClusterName = tc.Secrets.SiteName

	sshCert, tlsCert, err := tc.Process.GetAuthServer().GenerateUserTestCerts(auth.GenerateUserTestCertsRequest{
		Key:            key.MarshalSSHPublicKey(),
		Username:       username,
		TTL:            ttl,
		Compatibility:  constants.CertificateFormatStandard,
		RouteToCluster: tc.Secrets.SiteName,
	})
	require.NoError(t, err)

	key.Cert = sshCert
	key.TLSCert = tlsCert

	hostCAs, err := tc.Process.GetAuthServer().GetCertAuthorities(context.Background(), types.HostCA, false)
	require.NoError(t, err)
	key.TrustedCerts = auth.AuthoritiesToTrustedCerts(hostCAs)

	idPath := filepath.Join(t.TempDir(), "user_identity")
	_, err = identityfile.Write(context.Background(), identityfile.WriteConfig{
		OutputPath: idPath,
		Key:        key,
		Format:     identityfile.FormatFile,
	})
	require.NoError(t, err)
	return idPath
}

// WaitForProxyCount waits a set time for the proxy count in clusterName to
// reach some value.
func WaitForProxyCount(t *TeleInstance, clusterName string, count int) error {
	var counts map[string]int
	start := time.Now()
	for time.Since(start) < 17*time.Second {
		counts = t.RemoteClusterWatcher.Counts()
		if counts[clusterName] == count {
			return nil
		}

		time.Sleep(500 * time.Millisecond)
	}

	return trace.BadParameter("proxy count on %v: %v (wanted %v)", clusterName, counts[clusterName], count)
}

func WaitForAuditEventTypeWithBackoff(t *testing.T, cli *auth.Server, startTime time.Time, eventType string) []apievents.AuditEvent {
	max := time.Second
	timeout := time.After(max)
	bf, err := retryutils.NewLinear(retryutils.LinearConfig{
		Step: max / 10,
		Max:  max,
	})
	if err != nil {
		t.Fatalf("failed to create linear backoff: %v", err)
	}
	ctx := context.Background()
	for {
		events, _, err := cli.SearchEvents(ctx, events.SearchEventsRequest{
			From:       startTime,
			To:         time.Now().Add(time.Hour),
			EventTypes: []string{eventType},
			Limit:      100,
			Order:      types.EventOrderAscending,
		})
		if err != nil {
			t.Fatalf("failed to call SearchEvents: %v", err)
		}
		if len(events) != 0 {
			return events
		}
		select {
		case <-bf.After():
			bf.Inc()
		case <-timeout:
			t.Fatalf("event type %q not found after %v", eventType, max)
		}
	}
}

func MustGetCurrentUser(t *testing.T) *user.User {
	user, err := user.Current()
	require.NoError(t, err)
	return user
}

func WaitForDatabaseServers(t *testing.T, authServer *auth.Server, dbs []servicecfg.Database) {
	t.Helper()

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

	for {
		all, err := authServer.GetDatabaseServers(ctx, apidefaults.Namespace)
		require.NoError(t, err)

		// Count how many input "dbs" are registered.
		var registered int
		for _, db := range dbs {
			for _, a := range all {
				if a.GetName() == db.Name {
					registered++
					break
				}
			}
		}

		if registered == len(dbs) {
			return
		}

		select {
		case <-time.After(500 * time.Millisecond):
		case <-ctx.Done():
			require.Fail(t, "database servers not registered after 10s")
		}
	}
}

// CreatePROXYEnabledListener creates net.Listener that can handle receiving signed PROXY headers
func CreatePROXYEnabledListener(ctx context.Context, t *testing.T, address string, caGetter multiplexer.CertAuthorityGetter, clusterName string) (net.Listener, error) {
	t.Helper()

	listener, err := net.Listen("tcp", address)
	require.NoError(t, err)

	return multiplexer.NewPROXYEnabledListener(multiplexer.Config{
		Listener:            listener,
		Context:             ctx,
		CertAuthorityGetter: caGetter,
		LocalClusterName:    clusterName,
	})
}

// MakeTestServers starts an Auth and a Proxy Service.
// Besides those processes, it also returns a provision token which can be used to add other services.
func MakeTestServers(t *testing.T) (auth *service.TeleportProcess, proxy *service.TeleportProcess, provisionToken string) {
	provisionToken = uuid.NewString()
	var err error
	// Set up a test auth server.
	//
	// We need this to get a random port assigned to it and allow parallel
	// execution of this test.
	cfg := servicecfg.MakeDefaultConfig()
	cfg.CircuitBreakerConfig = breaker.NoopBreakerConfig()
	cfg.InstanceMetadataClient = cloud.NewDisabledIMDSClient()
	cfg.Hostname = "localhost"
	cfg.DataDir = t.TempDir()
	cfg.SetAuthServerAddress(cfg.Auth.ListenAddr)
	cfg.Auth.ListenAddr.Addr = NewListener(t, service.ListenerAuth, &cfg.FileDescriptors)
	cfg.Auth.Preference.SetSecondFactor(constants.SecondFactorOff)
	cfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)}
	cfg.Auth.StaticTokens, err = types.NewStaticTokens(types.StaticTokensSpecV2{
		StaticTokens: []types.ProvisionTokenV1{{
			Roles:   []types.SystemRole{types.RoleProxy, types.RoleDatabase, types.RoleTrustedCluster, types.RoleNode, types.RoleApp},
			Expires: time.Now().Add(time.Minute),
			Token:   provisionToken,
		}},
	})
	require.NoError(t, err)
	cfg.SSH.Enabled = false
	cfg.Auth.Enabled = true
	cfg.Proxy.Enabled = false
	cfg.Log = utils.NewLoggerForTests()

	auth, err = service.NewTeleport(cfg)
	require.NoError(t, err)
	require.NoError(t, auth.Start())

	t.Cleanup(func() {
		require.NoError(t, auth.Close())
		require.NoError(t, auth.Wait())
	})

	// Wait for proxy to become ready.
	_, err = auth.WaitForEventTimeout(30*time.Second, service.AuthTLSReady)
	// in reality, the auth server should start *much* sooner than this.  we use a very large
	// timeout here because this isn't the kind of problem that this test is meant to catch.
	require.NoError(t, err, "auth server didn't start after 30s")

	authAddr, err := auth.AuthAddr()
	require.NoError(t, err)

	// Set up a test proxy service.
	cfg = servicecfg.MakeDefaultConfig()
	cfg.CircuitBreakerConfig = breaker.NoopBreakerConfig()
	cfg.InstanceMetadataClient = cloud.NewDisabledIMDSClient()
	cfg.Hostname = "localhost"
	cfg.DataDir = t.TempDir()

	cfg.SetAuthServerAddress(*authAddr)
	cfg.SetToken(provisionToken)
	cfg.SSH.Enabled = false
	cfg.Auth.Enabled = false
	cfg.Proxy.Enabled = true
	cfg.Proxy.ReverseTunnelListenAddr.Addr = NewListener(t, service.ListenerProxyTunnel, &cfg.FileDescriptors)
	cfg.Proxy.WebAddr.Addr = NewListener(t, service.ListenerProxyWeb, &cfg.FileDescriptors)
	cfg.Proxy.PublicAddrs = []utils.NetAddr{
		cfg.Proxy.WebAddr,
	}
	cfg.Proxy.DisableWebInterface = true
	cfg.Log = utils.NewLoggerForTests()

	proxy, err = service.NewTeleport(cfg)
	require.NoError(t, err)
	require.NoError(t, proxy.Start())

	t.Cleanup(func() {
		require.NoError(t, proxy.Close())
		require.NoError(t, proxy.Wait())
	})

	// Wait for proxy to become ready.
	_, err = proxy.WaitForEventTimeout(30*time.Second, service.ProxyWebServerReady)
	require.NoError(t, err, "proxy web server didn't start after 10s")

	return auth, proxy, provisionToken
}

// MakeTestDatabaseServer creates a Database Service
// It receives the Proxy Address, a Token (to join the cluster) and a list of Datbases
func MakeTestDatabaseServer(t *testing.T, proxyAddr utils.NetAddr, token string, resMatchers []services.ResourceMatcher, dbs ...servicecfg.Database) (db *service.TeleportProcess) {
	// Proxy uses self-signed certificates in tests.
	lib.SetInsecureDevMode(true)

	cfg := servicecfg.MakeDefaultConfig()
	cfg.Hostname = "localhost"
	cfg.DataDir = t.TempDir()
	cfg.CircuitBreakerConfig = breaker.NoopBreakerConfig()
	cfg.InstanceMetadataClient = cloud.NewDisabledIMDSClient()
	cfg.SetAuthServerAddress(proxyAddr)
	cfg.SetToken(token)
	cfg.SSH.Enabled = false
	cfg.Auth.Enabled = false
	cfg.Proxy.Enabled = false
	cfg.Databases.Enabled = true
	cfg.Databases.Databases = dbs
	cfg.Databases.ResourceMatchers = resMatchers
	cfg.Log = utils.NewLoggerForTests()

	db, err := service.NewTeleport(cfg)
	require.NoError(t, err)
	require.NoError(t, db.Start())

	t.Cleanup(func() {
		assert.NoError(t, db.Close())
	})

	// Wait for database agent to start.
	_, err = db.WaitForEventTimeout(30*time.Second, service.DatabasesReady)
	require.NoError(t, err, "database server didn't start after 10s")

	return db
}

// MustCreateListener creates a tcp listener at 127.0.0.1 with random port.
func MustCreateListener(t *testing.T) net.Listener {
	t.Helper()

	listener, err := net.Listen("tcp", "127.0.0.1:0")
	require.NoError(t, err)

	t.Cleanup(func() {
		listener.Close()
	})
	return listener
}

func FindNodeWithLabel(t *testing.T, ctx context.Context, cl services.ResourceLister, key, value string) func() bool {
	t.Helper()
	return func() bool {
		servers, err := cl.ListResources(ctx, proto.ListResourcesRequest{
			ResourceType: types.KindNode,
			Namespace:    apidefaults.Namespace,
			Labels:       map[string]string{key: value},
			Limit:        1,
		})
		assert.NoError(t, err)
		return len(servers.Resources) >= 1
	}
}

repository: gravitational/teleport

license_type: permissive

repo_name: gravitational/teleport

branch_name: refs/heads/master

gha_language: Go

extension: go


text:
/* $Id$ */
#include "internal.h"
#include "log.h"
#include <stdlib.h>
#include <string.h>

#define VERBOSE 1

StringBuffer::StringBuffer() : next(NULL), string(NULL) {}

StringBuffer::~StringBuffer()
{
    delete [] string;
}

Header::Header() : next(NULL), index(0), data(NULL), size(0), major_version(0), string_buffer(NULL) {}

void Header::free_string_buffers()
{
    StringBuffer* current = this->string_buffer;
    this->string_buffer = NULL;

    while (current != NULL)
    {
        StringBuffer* next = current->next;
        delete current;
        current = next;
    }
}

Header::~Header()
{
    this->free_string_buffers();

    for (size_t i = 0; i < this->components.size(); i++)
        delete this->components[i];

    for (size_t i = 0; i < this->file_groups.size(); i++)
        delete this->file_groups[i];

    for (size_t i = 0; i < this->file_descriptors.size(); i++)
        delete this->file_descriptors[i];

    delete [] this->data;
}

UnshieldFileGroup::UnshieldFileGroup(Header* header, uint32_t offset)
{
  uint8_t* p = unshield_header_get_buffer(header, offset);

#if VERBOSE
  unshield_trace(L"File group descriptor offset: %08x", offset);
#endif

  this->name = unshield_header_get_string(header, READ_UINT32(p)); p += 4;

  if (header->major_version <= 5)
    p += 0x48;
  else
    p += 0x12;

  this->first_file = READ_UINT32(p); p += 4;
  this->last_file  = READ_UINT32(p); p += 4;

#if VERBOSE
  unshield_trace(L"File group %08x first file = %i, last file = %i",
      offset, this->first_file, this->last_file);
#endif

}

size_t Unshield::unshield_file_group_count() const
{
  Header* header = this->header_list;
  return header->file_groups.size();
}

UnshieldFileGroup* Unshield::unshield_file_group_get(size_t index)
{
  Header* header = this->header_list;

  if (index >= 0 && index < header->file_groups.size())
    return header->file_groups[index];
  else
    return NULL;
}

UnshieldFileGroup* Unshield::unshield_file_group_find(const char* name)
{
  Header* header = this->header_list;

  for (size_t i = 0; i < header->file_groups.size(); i++)
  {
    if (STREQ(header->file_groups[i]->name, name))
      return header->file_groups[i];
  }

  return NULL;
}

const char* Unshield::unshield_file_group_name(size_t index) const
{
  Header* header = this->header_list;

  if (index >= 0 && index < header->file_groups.size())
    return header->file_groups[index]->name;
  else
    return NULL;
}

license: MIT

gha_license_id: MIT

extension: cpp


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

package cmd

import (
	"github.com/spf13/cobra"
	keys "github.com/tepleton/go-crypto/keys"
)

const KeySubdir = "keys"

var (
	manager keys.Manager
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "keys",
	Short: "Key manager for tepleton clients",
	Long: `Keys allows you to manage your local keystore for tepleton.

These keys may be in any format supported by go-crypto and can be
used by light-clients, full nodes, or any other application that
needs to sign with a private key.`,
}

func init() {
	RootCmd.AddCommand(getCmd)
	RootCmd.AddCommand(listCmd)
	RootCmd.AddCommand(newCmd)
	RootCmd.AddCommand(updateCmd)
	RootCmd.AddCommand(deleteCmd)
	RootCmd.AddCommand(recoverCmd)
}

func RegisterServer() {
	RootCmd.AddCommand(serveCmd)
}

repository: tepletonteam/tepleton

repo_name: tepletonteam/tepleton


text:
@article{Colgan2012,
 abstract = {The distribution of woody biomass in savannas reflects spatial patterns fundamental to ecosystem processes, such as water flow, competition, and herbivory, and is a key contributor to savanna ecosystem services, such as fuelwood supply. While total precipitation sets an upper bound on savanna woody biomass, the extent to which substrate and terrain constrain trees and shrubs below this maximum remains poorly understood, often occluded by local-scale disturbances such as fire and trampling. Here we investigate the role of hillslope topography and soil properties in controlling woody plant aboveground biomass (AGB) in Kruger National Park, South Africa. Large-area sampling with airborne Light Detection and Ranging (LiDAR) provided a means to average across local-scale disturbances, revealing an unexpectedly linear relationship between AGB and hillslope-position on basalts, where biomass levels were lowest on crests, and linearly increased toward streams (R2 = 0.91). The observed pattern was different on granite substrates, where AGB exhibited a strongly non-linear relationship with hillslope position: AGB was high on crests, decreased midslope, and then increased near stream channels (R2 = 0.87). Overall, we observed 5-to-8-fold lower AGB on clayey, basalt-derived soil than on granites, and we suggest this is due to herbivore-fire interactions rather than lower hydraulic conductivity or clay shrinkage/swelling, as previously hypothesized. By mapping AGB within and outside fire and herbivore exclosures, we found that basalt-derived soils support tenfold higher AGB in the absence of fire and herbivory, suggesting high clay content alone is not a proximal limitation on AGB. Understanding how fire and herbivory contribute to AGB heterogeneity is critical to predicting future savanna carbon storage under a changing climate.},
 author = {Colgan, M. S. and Asner, G. P. and Levick, S. R. and Martin, R. E. and Chadwick, O. A.},
 doi = {10.5194/bg-9-1809-2012},
 issn = {17264170},
 journal = {Biogeosciences},
 number = {5},
 pages = {1809--1821},
 title = {Topo-edaphic controls over woody plant biomass in South African savannas},
 volume = {9},
 year = {2012}
}

repository: geospatialeco/SpatialDataScience

repo_name: geospatialeco/SpatialDataScience

extension: bib


text:
#
# Copyright (c) Siemens AG, 2020
#
# Authors:
#  Jan Kiszka <jan.kiszka@siemens.com>
#
# SPDX-License-Identifier: MIT

inherit dpkg-raw

DESCRIPTION = "This service generates an individual UUID for the rootfs during first boot"

DEBIAN_DEPENDS = "systemd, u-boot-script, fdisk, util-linux, uuid-runtime"

SRC_URI = " \
    file://regen-rootfs-uuid-on-first-boot.service \
    file://regen-rootfs-uuid.sh \
    file://postinst"

do_install() {
    install -d -m 755 ${D}/lib/systemd/system
    install -m 644 ${WORKDIR}/regen-rootfs-uuid-on-first-boot.service ${D}/lib/systemd/system/

    install -d -m 755 ${D}/usr/share/regen-rootfs-uuid
    install -m 755 ${WORKDIR}/regen-rootfs-uuid.sh ${D}/usr/share/regen-rootfs-uuid/
}

extension: bb


text:
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://LICENSE.GPL;md5=930e2a5f63425d8dd72dbd7391c43c46"

include kodi-git.inc

inherit gettext

do_configure () {
}

BUILD_CFLAGS += "-std=gnu99"
export PREFIX="${prefix}"

do_compile (){
    make -C ${S}/tools/depends/native/JsonSchemaBuilder/
}

do_install() {
    install -Dm 775 ${S}/tools/depends/native/JsonSchemaBuilder/bin/JsonSchemaBuilder ${D}${bindir}/JsonSchemaBuilder
}

BBCLASSEXTEND = "native nativesdk"

repository: smk-embedded/meta-kodi

repo_name: smk-embedded/meta-kodi


text:
file(REMOVE_RECURSE
  "CMakeFiles/sudoku_solver_hybrid.dir/server_hybrid.cc.o"
  "CMakeFiles/sudoku_solver_hybrid.dir/sudoku.cc.o"
  "../../bin/sudoku_solver_hybrid.pdb"
  "../../bin/sudoku_solver_hybrid"
)

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

gha_license_id: NOASSERTION

extension: cmake


text:
@article{Sun2017,
 abstract = {Land surface albedo is an essential variable for surface energy and climate modeling as it describes the proportion of incident solar radiant flux that is reflected from the Earth’s surface. To capture the temporal variability and spatial heterogeneity of the land surface, satellite remote sensing must be used to monitor albedo accurately at a global scale. However, large data gaps caused by cloud or ephemeral snow have slowed the adoption of satellite albedo products by the climate modeling community. To address the needs of this community, we used a number of temporal and spatial gap-filling strategies to improve the spatial and temporal coverage of the global land surface MODIS BRDF, albedo and NBAR products. A rigorous evaluation of the gap-filled values shows good agreement with original high quality data (RMSE = 0.027 for the NIR band albedo, 0.020 for the red band albedo). This global snow-free and cloud-free MODIS BRDF and albedo dataset (established from 2001 to 2015) offers unique opportunities to monitor and assess the impact of the changes on the Earth’s land surface.},
 author = {Sun, Qingsong and Wang, Zhuosen and Li, Zhan and Erb, Angela and Schaaf, Crystal B},
 copyright = {All rights reserved},
 doi = {10.1016/j.jag.2017.01.011},
 issn = {03032434},
 journal = {International Journal of Applied Earth Observation and Geoinformation},
 month = {June},
 note = {Publisher: Elsevier B.V.},
 pages = {36--49},
 title = {Evaluation of the global MODIS 30 arc-second spatially and temporally complete snow-free land surface albedo and reflectance anisotropy dataset},
 url = {http://linkinghub.elsevier.com/retrieve/pii/S0303243417300119},
 volume = {58},
 year = {2017}
}


text:
@article{RN55954,
   author = {Haberl, Helmut and Wiedenhofer, Dominik and Schug, Franz and Frantz, David and Virág, Doris and Plutzar, Christoph and Gruhler, Karin and Lederer, Jakob and Schiller, Georg and Fishman, Tomer and Lanau, Maud and Gattringer, Andreas and Kemper, Thomas and Liu, Gang and Tanikawa, Hiroki and van der Linden, Sebastian and Hostert, Patrick},
   geo = {Vienna, Austria (1, 2, 5, 6, 8, 12) and Berlin, Germany (3, 4, 17) and Dresden, Germany (7, 9) and Herzliya, Israel (10) and Odense, Denmark (11, 14) and Sheffield, UK (11) and Ispra, Italy (13) and Nagoya, Japan (15) and Greifswald, Germany (16)},
   year = {2021},
   title = {High-Resolution Maps of Material Stocks in Buildings and Infrastructures in Austria and Germany},
   journal = {Environmental Science & Technology},
   DOI = {10.1021/acs.est.0c05642},
   url = {https://doi.org/10.1021/acs.est.0c05642},
   abstract = {The dynamics of societal material stocks such as buildings and infrastructures and their spatial patterns drive surging resource use and emissions. Two main types of data are currently used to map stocks, night-time lights (NTL) from Earth-observing (EO) satellites and cadastral information. We present an alternative approach for broad-scale material stock mapping based on freely available high-resolution EO imagery and OpenStreetMap data. Maps of built-up surface area, building height, and building types were derived from optical Sentinel-2 and radar Sentinel-1 satellite data to map patterns of material stocks for Austria and Germany. Using material intensity factors, we calculated the mass of different types of buildings and infrastructures, distinguishing eight types of materials, at 10 m spatial resolution. The total mass of buildings and infrastructures in 2018 amounted to ∼5 Gt in Austria and ∼38 Gt in Germany (AT: ∼540 t/cap, DE: ∼450 t/cap). Cross-checks with independent data sources at various scales suggested that the method may yield more complete results than other data sources but could not rule out possible overestimations. The method yields thematic differentiations not possible with NTL, avoids the use of costly cadastral data, and is suitable for mapping larger areas and tracing trends over time.},
   type = {Journal Article}
}

repository: davidfrantz/academic-kickstart

repo_name: davidfrantz/academic-kickstart


text:
SUMMARY = "Arago TI SDK bootstrap base image for initramfs"

DESCRIPTION = "Image meant for basic system verification of linux kernel.\
 Intended as basic test system, this image does not package the kernel\
 in the standard /boot folder in rootfs. Instead, it provides a base\
 rootfs with enough basic board bringup utilities allowing kernel to be\
 deployed elsewhere (tftp/separate boot partition/jtag log etc..) and\
 maybe used for basic platform bringup (bootstrap) activities.\
"

require arago-tiny-image.inc

IMAGE_FSTYPES += "cpio cpio.xz"

ARAGO_BOOTSTRAP_IMAGE_EXTRA_INSTALL ?= ""

IMAGE_INSTALL += " \
	packagegroup-arago-bootstrap \
	${ARAGO_BOOTSTRAP_IMAGE_EXTRA_INSTALL} \
"

export IMAGE_BASENAME = "tisdk-bootstrap-base-image"

repository: rcn-ee/meta-arago

repo_name: rcn-ee/meta-arago


text:
@ARTICLE{7934445,
  author={Chang, Xiaojun and Ma, Zhigang and Lin, Ming and Yang, Yi and Hauptmann, Alexander G.},
  journal={IEEE Transactions on Image Processing},
  title={Feature Interaction Augmented Sparse Learning for Fast Kinect Motion Detection},
  year={2017},
  volume={26},
  number={8},
  pages={3911-3920},
  doi={10.1109/TIP.2017.2708506}}

branch_name: refs/heads/main


text:
package blockchain

import (
	"encoding/binary"
	"hash"
	"time"
)

type Block struct {
	PreviousHash   []byte
	CreatedTime    time.Time
	Index          int64
	MiningVariable int64
	Data           string
	Hash           []byte
}

type Blockchain []Block

func int64ToBytes(input int64) []byte {
	result := make([]byte, 8)
	binary.LittleEndian.PutUint64(result, uint64(input))
	return result
}

func (b Block) ComputeHash(hasher hash.Hash) ([]byte, error) {
	_, err := hasher.Write(b.PreviousHash)
	if nil != err {
		return nil, err
	}
	_, err = hasher.Write([]byte(b.CreatedTime.String()))
	if nil != err {
		return nil, err
	}
	_, err = hasher.Write([]byte(b.Data))
	if nil != err {
		return nil, err
	}
	_, err = hasher.Write(int64ToBytes(b.Index))
	if nil != err {
		return nil, err
	}
	_, err = hasher.Write(int64ToBytes(b.MiningVariable))
	if nil != err {
		return nil, err
	}
	hash := hasher.Sum(nil)
	return hash, nil
}

func NewBlock(previousHash []byte, previousIndex int64, miningVariable int64, data string, hasher hash.Hash) (Block, error) {
	result := Block{PreviousHash: previousHash, CreatedTime: time.Now(), Index: previousIndex + 1, MiningVariable: miningVariable, Data: data}
	hash, err := result.ComputeHash(hasher)
	if nil != err {
		return Block{}, err
	}
	result.Hash = hash
	return result, nil
}


text:
# base recipe: meta/recipes-graphics/xorg-lib/libxfixes_5.0.3.bb
# base branch: warrior
# base commit: 4ba923dbac2845aca5b4312a5f278ad886a7acc7

SUMMARY = "XFixes: X Fixes extension library"

DESCRIPTION = "X applications have often needed to work around various \
shortcomings in the core X window system.  This extension is designed to \
provide the minimal server-side support necessary to eliminate problems \
caused by these workarounds."

require ${COREBASE}/meta/recipes-graphics/xorg-lib/xorg-lib-common.inc

# clear SRC_URI
SRC_URI = ""
inherit debian-package
require recipes-debian/sources/libxfixes.inc
DEBIAN_PATCH_TYPE = "nopatch"
DEBIAN_UNPACK_DIR = "${WORKDIR}/${XORG_PN}-${PV}"

LICENSE = "MIT-style"
LIC_FILES_CHKSUM = "file://COPYING;md5=3c1ce42c334a6f5cccb0277556a053e0"

DEPENDS += "virtual/libx11 xorgproto"

XORG_PN = "libXfixes"

BBCLASSEXTEND = "native nativesdk"

repository: miraclelinux/meta-debian-extended

repo_name: miraclelinux/meta-debian-extended

branch_name: refs/heads/warrior

gha_language: BitBake


text:
package vm

import (
	"strings"

	"github.com/goby-lang/goby/compiler/bytecode"
	"github.com/goby-lang/goby/vm/classes"
	"github.com/goby-lang/goby/vm/errors"
)

type operation func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{})

type operationType = uint8

type setType = string

type instructionSet struct {
	name         string
	instructions []*bytecode.Instruction
	filename     filename
	paramTypes   *bytecode.ArgSet
}

var operations [bytecode.InstructionCount]operation

// This is for avoiding initialization loop
func init() {
	operations = [bytecode.InstructionCount]operation{
		bytecode.Pop: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			t.Stack.Pop()
		},
		bytecode.Dup: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			obj := t.Stack.top().Target
			t.Stack.Push(&Pointer{Target: obj})
		},
		bytecode.PutBoolean: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			object := t.vm.InitObjectFromGoType(args[0])
			t.Stack.Push(&Pointer{Target: object})
		},
		bytecode.PutObject: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			object := t.vm.InitObjectFromGoType(args[0])
			t.Stack.Push(&Pointer{Target: object})
		},
		bytecode.GetConstant: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			constName := args[0].(string)
			c := t.vm.lookupConstant(cf, constName)

			if c == nil {
				t.pushErrorObject(errors.NameError, sourceLine, "uninitialized constant %s", constName)
			}

			c.isNamespace = args[1].(bool)

			if t.Stack.top() != nil && t.Stack.top().isNamespace {
				t.Stack.Pop()
			}

			t.Stack.Push(c)
		},
		bytecode.GetLocal: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			depth := args[0].(int)
			index := args[1].(int)

			p := cf.getLCL(index, depth)

			if p == nil {
				t.Stack.Push(&Pointer{Target: NULL})
				return
			}

			t.Stack.Push(p)
		},
		bytecode.GetInstanceVariable: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			variableName := args[0].(string)
			v, ok := cf.self.InstanceVariableGet(variableName)
			if !ok {
				t.Stack.Push(&Pointer{Target: NULL})
				return
			}

			p := &Pointer{Target: v}
			t.Stack.Push(p)
		},
		bytecode.SetInstanceVariable: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			variableName := args[0].(string)
			p := t.Stack.Pop()
			cf.self.InstanceVariableSet(variableName, p.Target)

			var obj Object

			switch v := p.Target.(type) {
			case *HashObject:
				obj = v.copy()
			case *ArrayObject:
				obj = v.copy()
			case *ChannelObject:
				obj = v.copy()
			default:
				obj = v
			}

			t.Stack.Push(&Pointer{Target: obj})
		},
		bytecode.SetLocal: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			var optioned bool
			p := t.Stack.Pop()
			depth := args[0].(int)
			index := args[1].(int)

			if len(args) > 2 && args[2].(int) == 1 {
				optioned = true
			}

			if optioned {
				if cf.getLCL(index, depth) == nil {
					cf.insertLCL(index, depth, p.Target)
				}

				return
			}

			cf.insertLCL(index, depth, p.Target)

			var obj Object

			switch v := p.Target.(type) {
			case *HashObject:
				obj = v.copy()
			case *ArrayObject:
				obj = v.copy()
			case *ChannelObject:
				obj = v.copy()
			default:
				obj = v
			}

			t.Stack.Push(&Pointer{Target: obj})
		},
		bytecode.SetConstant: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			constName := args[0].(string)
			c := cf.lookupConstantInCurrentScope(constName)
			v := t.Stack.Pop()

			if c != nil {
				t.pushErrorObject(errors.ConstantAlreadyInitializedError, sourceLine, "Constant %s already been initialized. Can't assign value to a constant twice.", constName)
			}

			cf.storeConstant(constName, v)

		},
		bytecode.NewRange: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			rangeEnd := t.Stack.Pop().Target.(*IntegerObject).value
			rangeStart := t.Stack.Pop().Target.(*IntegerObject).value

			t.Stack.Push(&Pointer{Target: t.vm.initRangeObject(rangeStart, rangeEnd)})

		},
		bytecode.NewArray: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			argCount := args[0].(int)
			var elems []Object

			for i := 0; i < argCount; i++ {
				v := t.Stack.Pop()
				elems = append([]Object{v.Target}, elems...)
			}

			arr := t.vm.InitArrayObject(elems)
			t.Stack.Push(&Pointer{Target: arr})

		},
		bytecode.ExpandArray: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			arrLength := args[0].(int)
			arr, ok := t.Stack.Pop().Target.(*ArrayObject)

			if !ok {
				t.pushErrorObject(errors.TypeError, sourceLine, "Expect stack top's value to be an Array when executing 'expandarray' instruction.")
			}

			var elems []Object

			for i := 0; i < arrLength; i++ {
				var elem Object
				if i < len(arr.Elements) {
					elem = arr.Elements[i]
				} else {
					elem = NULL
				}

				elems = append([]Object{elem}, elems...)
			}

			for _, elem := range elems {
				t.Stack.Push(&Pointer{Target: elem})
			}

		},
		bytecode.SplatArray: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			obj := t.Stack.top().Target
			arr, ok := obj.(*ArrayObject)

			if !ok {
				return
			}

			arr.splat = true

		},
		bytecode.NewHash: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			argCount := args[0].(int)
			pairs := map[string]Object{}

			for i := 0; i < argCount/2; i++ {
				v := t.Stack.Pop()
				k := t.Stack.Pop()
				pairs[k.Target.(*StringObject).value] = v.Target
			}

			hash := t.vm.InitHashObject(pairs)
			t.Stack.Push(&Pointer{Target: hash})

		},
		bytecode.BranchUnless: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			v := t.Stack.Pop()
			bo, isBool := v.Target.(*BooleanObject)

			if isBool {
				if bo.value {
					return
				}

				line := args[0].(int)
				cf.pc = line
				return
			}

			_, isNull := v.Target.(*NullObject)

			if isNull {
				line := args[0].(int)
				cf.pc = line
				return
			}

		},
		bytecode.BranchIf: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			v := t.Stack.Pop()
			bo, isBool := v.Target.(*BooleanObject)

			if isBool && !bo.value {
				return
			}

			_, isNull := v.Target.(*NullObject)

			if isNull {
				return
			}

			line := args[0].(int)
			cf.pc = line
			return

		},
		bytecode.Jump: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			cf.pc = args[0].(int)

		},
		bytecode.Break: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			/*
				Normal frame. IS name: ProgramStart. is block: false. source line: 1
				Normal frame. IS name: 0. is block: true. ep: 17. source line: 5 <- The block source
				Go method frame. Method name: each. <- The method call with block
				Normal frame. IS name: 0. is block: true. ep: 17. source line: 5 <- The block execution
			*/

			if cf.IsBlock() {
				/*
				  1. Remove block execution frame
				  2. Remove method call frame
				  3. Remove block source frame
				*/
				for i := 0; i < 3; i++ {
					frame := t.callFrameStack.pop()
					frame.stopExecution()
					frame.setAsRemoved()
				}
			}

		},
		bytecode.PutSelf: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			t.Stack.Push(&Pointer{Target: cf.self})

		},
		bytecode.PutString: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			object := t.vm.InitObjectFromGoType(args[0])
			t.Stack.Push(&Pointer{Target: object})

		},
		bytecode.PutFloat: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			value := args[0].(float64)
			object := t.vm.initFloatObject(value)
			t.Stack.Push(&Pointer{Target: object})

		},
		bytecode.PutNull: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			t.Stack.Push(&Pointer{Target: NULL})

		},
		bytecode.DefMethod: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			argCount := args[0].(int)
			methodName := t.Stack.Pop().Target.(*StringObject).value
			is, ok := t.getMethodIS(methodName, cf.FileName())

			if !ok {
				t.pushErrorObject(errors.InternalError, sourceLine, "Can't get method %s's instruction set.", methodName)
			}

			method := &MethodObject{Name: methodName, argc: argCount, instructionSet: is, BaseObj: NewBaseObject(t.vm.TopLevelClass(classes.MethodClass))}

			t.vm.defineMethodOn(t.Stack.Pop().Target, method)
		},
		bytecode.DefSingletonMethod: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			argCount := args[0].(int)
			methodName := t.Stack.Pop().Target.(*StringObject).value
			is, _ := t.getMethodIS(methodName, cf.FileName())
			method := &MethodObject{Name: methodName, argc: argCount, instructionSet: is, BaseObj: NewBaseObject(t.vm.TopLevelClass(classes.MethodClass))}

			t.vm.defineSingletonMethodOn(t.Stack.Pop().Target, method)
		},
		bytecode.DefClass: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			subject := strings.Split(args[0].(string), ":")
			subjectType, subjectName := subject[0], subject[1]

			classPtr := cf.lookupConstantUnderAllScope(subjectName)

			if classPtr == nil {
				var class *RClass
				if subjectType == "module" {
					class = t.vm.initializeModule(subjectName)
				} else {
					class = t.vm.initializeClass(subjectName)
				}

				classPtr = cf.storeConstant(class.Name, class)

				if len(args) >= 2 {
					superClassName := args[1].(string)
					superClass := t.vm.lookupConstant(cf, superClassName)
					inheritedClass, ok := superClass.Target.(*RClass)

					if !ok {
						t.pushErrorObject(errors.InternalError, sourceLine, "Constant %s is not a class. got: %s", superClassName, string(superClass.Target.Class().ReturnName()))
					}

					if inheritedClass.isModule {
						t.pushErrorObject(errors.InternalError, sourceLine, "Module inheritance is not supported: %s", inheritedClass.Name)
					}

					class.inherits(inheritedClass)
				}
			}

			is := t.getClassIS(subjectName, cf.FileName())

			t.Stack.Pop()
			c := newNormalCallFrame(is, cf.FileName(), sourceLine)
			c.self = classPtr.Target
			t.callFrameStack.push(c)
			t.startFromTopFrame()

			t.Stack.Push(classPtr)

		},
		bytecode.Send: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			var blockFlag string

			methodName := args[0].(string)
			argCount := args[1].(int)
			blockFlag, ok := args[2].(string)

			if !ok {
				blockFlag = ""
			}

			argSet := args[3].(*bytecode.ArgSet)

			// Deal with splat arguments
			if arr, ok := t.Stack.top().Target.(*ArrayObject); ok && arr.splat {
				// Pop array
				t.Stack.Pop()
				// Can't count array itself, only the number of array elements
				argCount = argCount - 1 + len(arr.Elements)
				for _, elem := range arr.Elements {
					t.Stack.Push(&Pointer{Target: elem})
				}
			}

			argPr := t.Stack.pointer - argCount
			receiverPr := argPr - 1
			receiver := t.Stack.data[receiverPr].Target

			// Find Block
			blockFrame := t.retrieveBlock(cf.FileName(), blockFlag, cf.SourceLine())

			if blockFrame != nil {
				blockFrame.ep = cf
				blockFrame.self = cf.self
				blockFrame.sourceLine = sourceLine
				t.callFrameStack.push(blockFrame)
			}

			t.findAndCallMethod(receiver, methodName, receiverPr, argSet, argCount, argPr, sourceLine, blockFrame, cf.fileName)
		},
		bytecode.InvokeBlock: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			argCount := args[0].(int)
			argPr := t.Stack.pointer - argCount
			receiverPr := argPr - 1
			receiver := t.Stack.data[receiverPr].Target

			if cf.blockFrame == nil {
				t.pushErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
			}

			blockFrame := cf.blockFrame

			/*
				This is for such condition:

				```ruby
				def foo(x)
				  yield(x + 10)
				end

				def bar(y)
				  foo(y) do |f|
					yield(f) # <------- here
				  end
				end

				bar(100) do |b|
				  puts(b) #=> 110
				end
				```

				In this case the target frame is not first block frame we meet. It should be `bar`'s block.
				And bar's frame is foo block frame's ep, so our target frame is ep's block frame.
			*/
			if cf.blockFrame.ep == cf.ep {
				blockFrame = cf.blockFrame.ep.blockFrame
			}

			c := newNormalCallFrame(blockFrame.instructionSet, blockFrame.instructionSet.filename, sourceLine)
			c.blockFrame = blockFrame
			c.ep = blockFrame.ep
			c.self = receiver
			c.isBlock = true

			for i := 0; i < argCount; i++ {
				c.locals[i] = t.Stack.data[argPr+i]
			}

			t.callFrameStack.push(c)
			t.startFromTopFrame()

			t.Stack.Set(receiverPr, t.Stack.top())
			t.Stack.pointer = receiverPr + 1

		},
		bytecode.GetBlock: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			if cf.blockFrame == nil {
				t.pushErrorObject(errors.InternalError, sourceLine, "Can't get block without a block argument")
			}

			blockFrame := cf.blockFrame

			if cf.blockFrame.ep == cf.ep {
				blockFrame = cf.blockFrame.ep.blockFrame
			}

			blockObject := t.vm.initBlockObject(blockFrame.instructionSet, blockFrame.ep, t.Stack.data[t.Stack.pointer-1].Target)

			t.Stack.Push(&Pointer{Target: blockObject})

		},
		bytecode.Leave: func(t *Thread, sourceLine int, cf *normalCallFrame, args ...interface{}) {
			t.callFrameStack.pop()
			cf.stopExecution()

		},
	}
}

// InitObjectFromGoType creates an object based on Go's type
func (v *VM) InitObjectFromGoType(value interface{}) Object {
	switch val := value.(type) {
	case nil:
		return NULL
	case int:
		return v.InitIntegerObject(val)
	case int64:
		return v.InitIntegerObject(int(val))
	case int32:
		return v.InitIntegerObject(int(val))
	case float64:
		return v.initFloatObject(val)
	case []uint8:
		var bytes []byte

		for _, i := range val {
			bytes = append(bytes, byte(i))
		}

		return v.InitStringObject(string(bytes))
	case string:
		return v.InitStringObject(val)
	case bool:
		return toBooleanObject(val)
	case []interface{}:
		var objects []Object

		for _, elem := range val {
			objects = append(objects, v.InitObjectFromGoType(elem))
		}

		return v.InitArrayObject(objects)
	default:
		return v.initGoObject(value)
	}
}


text:
/********************************************************************
	created:	2014/01/15
	created:	15:1:2014   23:02
	filename: 	NaiveMethods.cpp
	file path:	GAGPL\GAGLIBRARY
	file base:	NaiveMethods
	file ext:	cpp
	author:		Han Hu

	purpose:
*********************************************************************/

#include <GAGPL/GAGLIBRARY/NaiveMethods.h>
#include <GAGPL/MATH/MassConversion.h>

namespace gag
{
  double NaiveMethods::calculateGoldenPairNum(const ModificationSequence& mod_seq)
  {
    std::multimap<MonoPeakPtr, NodeItem> filtered_data = this->filterData(mod_seq);

    int chain_length = gs->getBranchByID(0).getUnitNum();

    // The key consists of a vector of <mod_sites, mod_num> pairs.
    ModificationKeySet key_set;
    std::set<std::string> symbol_set = gs->getModificationTypes();

    int count = 0;

#ifdef _DEBUG
    std::vector<std::pair<ModificationKey, ModificationKey>> key_pool;
#endif // _DEBUG
    for(std::multimap<MonoPeakPtr, NodeItem>::iterator iter = filtered_data.begin(); iter != filtered_data.end(); iter++)
    {
      // Consider only terminal cleavage.
      if (iter->second.getCleavageNum() > 1) continue;

      const CleavageCollection& cc = iter->second.getFragment()->getCleavages();
      if(cc.size() == 0) continue;

      //std::string type = cc.begin()->first;

      // Consider both glycosidic-bond and cross-ring cleavages.
      //if(type == "A" || type == "X") continue;
#ifdef _DEBUG
      iter->second.getFragment()->printFragment();
#endif // _DEBUG

      ModificationKey mod_key, complement_key;

      double pass = true;
      // Store the results into key_vec.
      BOOST_FOREACH(std::string symbol, symbol_set)
      {
        int total_num = gs->getModificationConstraint(symbol);
        int mod_num = iter->second.getModificationNum(symbol);

        // Modification sites covered by the fragment.
        ModificationSites mod_sites = iter->second.getFragment()->getModificationSitesBySymbol(symbol, 1);

        // Should be all possible sites including the Ac sites.
        ModificationSites total_sites = gs->getModificationSitesBySymbol(symbol, 1);

#ifdef _DEBUG
        std::cout << "Symbol: " << symbol << "\n";
        std::cout << "Mod number: " << mod_num << "\n";
        printModificationSites(mod_sites);
#endif // _DEBUG
        // Skip meaningless fragments.
        if(mod_sites.size() == total_sites.size() || mod_sites.size() == 0) {
#ifdef _DEBUG
          std::cout << "Unqualified modification sites.  Pass the fragment!\n";
#endif // _DEBUG
          pass = false;
          break;
        }

        mod_key.addKey(mod_sites, mod_num);
        complement_key.addKey(getSiteDifference(total_sites, mod_sites), total_num - mod_num);

      }
#ifdef _DEBUG
      std::cout << "Key!\n";
      mod_key.print();
      std::cout << "\n";
      std::cout << "Complement key!\n";
      complement_key.print();
      std::cout << "\n";
#endif // _DEBUG

      if(!pass) continue;

      // 1. Determine if the key has been recorded.
      if(key_set.find(mod_key) == key_set.end()) {
#ifdef _DEBUG
        std::cout << "Key not recorded!\n";
#endif // _DEBUG
        // 2. If not, determine if there is a complementary one recorded.
        if(key_set.find(complement_key) == key_set.end()) {
#ifdef _DEBUG
          std::cout << "Comp key not recorded!\n";
#endif // _DEBUG
          // 3. If not, store the key.

        } else {
          // This is a match!
#ifdef _DEBUG
          std::cout << "There is a match!\n";
          key_pool.push_back(std::make_pair(complement_key, mod_key));
#endif // _DEBUG
          count++;
        }
        key_set.insert(mod_key);

      } else {
#ifdef _DEBUG
        std::cout << "Key recorded, skip it!\n";
#endif // _DEBUG
        continue;
      }

    }
// Check the key pair and see if there is overlapping.
#ifdef _DEBUG
    for(auto iter = key_pool.begin(); iter != key_pool.end(); iter++)
    {
      std::cout << iter->first.mod_key << "\t" << iter->second.mod_key << "\n";
    }
#endif // _DEBUG
    return (double)count;
  }

  double NaiveMethods::calculateCoverage(const ModificationSequence& mod_seq, int cleavage_num /*= 2*/ )
  {
    std::multimap<MonoPeakPtr, NodeItem> filtered_data = this->filterData(mod_seq);

    std::multimap<MonoPeakPtr, NodeItem>::iterator iter = filtered_data.begin();

    std::set<double> mass_set;
    for(; iter != filtered_data.end(); iter++)
    {
      if(iter->second.getCleavageNum() > (size_t)cleavage_num)
        continue;

      double mass = msmath::calculateMass(iter->first->mz, -1 * iter->first->z);
      mass_set.insert(mass);
    }

    return (double)mass_set.size();
  }

  std::multimap<MonoPeakPtr, NodeItem> NaiveMethods::filterData( const ModificationSequence& mod_seq )
  {
    std::multimap<MonoPeakPtr, NodeItem>::iterator iter = data.begin();
    std::multimap<MonoPeakPtr, NodeItem> new_data;

    // Get the modification types to check.
    std::set<std::string> mod_set = gs->getModificationTypes();
    //for(ModificationSequence::const_iterator const_iter = seq.begin(); const_iter != seq.end(); const_iter++)
    //mod_set.insert(const_iter->first);

    for(; iter != data.end(); iter++)
    {
#ifdef _DEBUG
      std::cout << "Fragment information:\n";
      iter->second.getFragment()->printFragment();
#endif // _DEBUG

      // Do not count internal cleavages.
      if(iter->second.getCleavageNum() == 2) {
#ifdef _DEBUG
        std::cout << "Unqualified cleavage number." << "\n\n";
#endif // _DEBUG
        continue;

      }

      // Decide if the number of modification meets with the sequence.
      bool pass = true;

      // Iterate over all modification types.
      for(std::set<std::string>::iterator mod_iter = mod_set.begin(); mod_iter!=mod_set.end(); mod_iter++) {
        // The modification number contained by the fragment.
        int mod_num = iter->second.getModificationNum(*mod_iter);

        // Check intersection of modification sites from seq and frag.
        ModificationSequence::const_iterator seq_iter = mod_seq.find(*mod_iter);

        // Available sites of the candidate sequence.
        ModificationSites mod_sites = seq_iter->second;

        // Available sites at this region.
        //ModificationSites region_sites = iter->second.getFragment()->getModificationSitesBySymbol(*mod_iter, 1);
        ModificationSites region_sites = iter->second.getFragment()->getModificationSitesBySymbol(*mod_iter, 1);

        ModificationSites region_mod_sites = getSiteIntersection(mod_sites, region_sites);

        int max_mod_num = (int)region_mod_sites.size();

#ifdef _DEBUG
        std::cout << "Symbol: " << *mod_iter << "\tNumber: " << mod_num << "\tMax: " << max_mod_num << "\n";
        std::cout << "Modification sites from specified sequence:\n";
        printModificationSites(mod_sites);
        std::cout << "Fragment sites:\n";
        printModificationSites(region_sites);
        std::cout << "Intersection:\n";
        printModificationSites(region_mod_sites);
#endif // _DEBUG

        // If status == true, need to specify a range of the modification number.
        if(*mod_iter == "Ac") {// No missing
          if(mod_num != max_mod_num) {
#ifdef _DEBUG
            std::cout << "Ac number does not match!\n";
#endif // _DEBUG
            pass = false;
            break;
          }
        } else if(*mod_iter == "SO3") { // Missing.

          if(status) { // Calculate based on residue level.
            // Adjust the upper_limit of sulfate number.
            std::string clv_type = iter->second.getFragment()->getFragmentType();
            if(clv_type == "A" || clv_type == "X") {
              ModificationSites expanded_sites = iter->second.getFragment()->getExpandedModificationSites(*mod_iter, 1);
              ModificationSites reduced_sites = iter->second.getFragment()->getReducedModificationSites(*mod_iter, 1);
              // The cross-ring part of the residue.
              ModificationSites cr_residue_sites = getSiteDifference(region_sites, reduced_sites);
              // The whole sites of the residue.
              ModificationSites residue_diff_sites = getSiteDifference(expanded_sites, reduced_sites);

              // Lower_bound.
              ModificationSites expanded_mod_sites1 = getSiteIntersection(mod_sites, reduced_sites);
              // Modification sites on the boundary residue.
              ModificationSites expanded_mod_sites2 = getSiteIntersection(mod_sites, residue_diff_sites);
              max_mod_num = (int)expanded_mod_sites1.size() + (int)std::min(cr_residue_sites.size(), expanded_mod_sites2.size());

#ifdef _DEBUG
              std::cout << "Fragment type: " << clv_type << "\n";
              std::cout << "Expanded fragment sites:\n";
              printModificationSites(expanded_sites);
              std::cout << "Lower_bound modified sites:\n";
              printModificationSites(expanded_mod_sites1);
              std::cout << "Cross-ring part modification sites:\n";
              printModificationSites(cr_residue_sites);
              std::cout << "Boundary Modified sites:\n";
              printModificationSites(expanded_mod_sites2);
              std::cout << "Updated max number: " << max_mod_num << "\n";
#endif // _DEBUG
            }
          }
          if(mod_num > max_mod_num) {
#ifdef _DEBUG
            std::cout << "SO3 number beyond boundary " << max_mod_num << "\n";
#endif // _DEBUG
            pass = false;
            break;
          }
        }

      }

      if(pass) {
#ifdef _DEBUG
        std::cout << "Accept new data!\n\n";
#endif // _DEBUG

        new_data.insert(*iter);
      } else {
#ifdef _DEBUG
        std::cout << "Reject new data!\n\n";
#endif // _DEBUG
      }
    }
#ifdef _DEBUG
    std::cout << "Old data size: " << data.size() << "\n";
    std::cout << "New data size: " << new_data.size() << "\n";
#endif // _DEBUG
    return new_data;
  }
}


text:
SUMMARY = "A convenience library for the geocoding"

LICENSE = "LGPL-2.0-only"
LIC_FILES_CHKSUM = "file://COPYING.LIB;md5=55ca817ccb7d5b5b66355690e9abc605"

GNOMEBASEBUILDCLASS = "meson"
GIR_MESON_OPTION = "enable-introspection"
GTKDOC_MESON_OPTION = "enable-gtk-doc"

inherit gnomebase gobject-introspection gettext gtk-doc upstream-version-is-even

DEPENDS = " \
    json-glib \
    libsoup-3.0 \
"

SRC_URI[archive.sha256sum] = "2d9a6826d158470449a173871221596da0f83ebdcff98b90c7049089056a37aa"

EXTRA_OEMESON = "-Denable-installed-tests=false -Dsoup2=false"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded


text:
#
# Copyright 2019, Data61
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# ABN 41 687 119 230.
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(DATA61_BSD)
#

cmake_minimum_required(VERSION 3.7.2)

set(project_dir "${CMAKE_CURRENT_LIST_DIR}/../../")
file(GLOB project_modules ${project_dir}/projects/*)
list(
    APPEND
        CMAKE_MODULE_PATH
        ${project_dir}/kernel
        ${project_dir}/tools/seL4/cmake-tool/helpers/
        ${project_dir}/tools/seL4/elfloader-tool/
        ${project_modules}
)

set(NANOPB_SRC_ROOT_FOLDER "${project_dir}/tools/nanopb" CACHE INTERNAL "")
set(BBL_PATH ${project_dir}/tools/riscv-pk CACHE STRING "BBL Folder location")

set(SEL4_CONFIG_DEFAULT_ADVANCED ON)

include(application_settings)

include(${CMAKE_CURRENT_LIST_DIR}/easy-settings.cmake)

correct_platform_strings()

find_package(seL4 REQUIRED)
sel4_configure_platform_settings()

set(valid_platforms ${KernelPlatform_all_strings} ${correct_platform_strings_platform_aliases})
set_property(CACHE PLATFORM PROPERTY STRINGS ${valid_platforms})
if(NOT "${PLATFORM}" IN_LIST valid_platforms)
    message(FATAL_ERROR "Invalid PLATFORM selected: \"${PLATFORM}\"
Valid platforms are: \"${valid_platforms}\"")
endif()

# Declare a cache variable that enables/disablings the forcing of cache variables to
# the specific test values. By default it is disabled
set(ChannelBenchAllowSettingsOverride OFF CACHE BOOL "Allow user to override configuration settings")
if(NOT ChannelBenchAllowSettingsOverride)
    # We use 'FORCE' when settings these values instead of 'INTERNAL' so that they still appear
    # in the cmake-gui to prevent excessively confusing users
    if(ARM_HYP)
        set(KernelArmHypervisorSupport ON CACHE BOOL "" FORCE)
    endif()

    if(SIMULATION)
        ApplyCommonSimulationSettings(${KernelArch})
    else()
        if(KernelArchX86)
            set(KernelIOMMU ON CACHE BOOL "" FORCE)
        endif()
    endif()

    # Check the hardware debug API non simulated (except for ia32, which can be simulated),
    # or platforms that don't support it.
    if(((NOT SIMULATION) OR KernelSel4ArchIA32) AND NOT KernelHardwareDebugAPIUnsupported)
        set(HardwareDebugAPI ON CACHE BOOL "" FORCE)
    else()
        set(HardwareDebugAPI OFF CACHE BOOL "" FORCE)
    endif()

    ApplyCommonReleaseVerificationSettings(${RELEASE} ${VERIFICATION})

	if(NUM_DOMAINS MATCHES "^[0-9]+$")
		set(KernelNumDomains ${NUM_DOMAINS} CACHE STRING "" FORCE)
    else()
        set(KernelNumDomains 1 CACHE STRING "" FORCE)
    endif()

    if(SMP)
        if(NUM_NODES MATCHES "^[0-9]+$")
            set(KernelMaxNumNodes ${NUM_NODES} CACHE STRING "" FORCE)
        else()
            set(KernelMaxNumNodes 4 CACHE STRING "" FORCE)
        endif()
    else()
        set(KernelMaxNumNodes 1 CACHE STRING "" FORCE)
    endif()

    if(MCS)
        set(KernelIsMCS ON CACHE BOOL "" FORCE)
    else()
        set(KernelIsMCS OFF CACHE BOOL "" FORCE)
    endif()

    if(KERNEL_IMAGES)
        set(KernelImages ON CACHE BOOL "" FORCE)
    else()
        set(KernelImages OFF CACHE BOOL "" FORCE)
    endif()

	if(DEBUG_RUN)
		set(KernelDangerousCodeInjection ON CACHE BOOL "" FORCE)
		set(KernelSkimWindow OFF CACHE BOOL "" FORCE)
	endif()
endif()

branch_name: refs/heads/timing

gha_language: C


text:
require rust.inc
require rust-source-${PV}.inc
require rust-snapshot-${PV}.inc

# These are extracted from rustc/src/bootstrap/Cargo.toml via cargo-bitbake
SRC_URI += " \
crate://crates.io/aho-corasick/0.6.4 \
crate://crates.io/ansi_term/0.11.0 \
crate://crates.io/ar/0.3.1 \
crate://crates.io/arrayvec/0.4.7 \
crate://crates.io/atty/0.2.8 \
crate://crates.io/backtrace-sys/0.1.16 \
crate://crates.io/backtrace/0.3.5 \
crate://crates.io/bitflags/0.7.0 \
crate://crates.io/bitflags/0.9.1 \
crate://crates.io/bitflags/1.0.1 \
crate://crates.io/bufstream/0.1.3 \
crate://crates.io/byteorder/1.2.1 \
crate://crates.io/cargo_metadata/0.2.3 \
crate://crates.io/cargo_metadata/0.5.3 \
crate://crates.io/cc/1.0.9 \
crate://crates.io/cfg-if/0.1.2 \
crate://crates.io/chrono/0.4.0 \
crate://crates.io/clap/2.31.2 \
crate://crates.io/cmake/0.1.29 \
crate://crates.io/commoncrypto-sys/0.2.0 \
crate://crates.io/commoncrypto/0.2.0 \
crate://crates.io/compiletest_rs/0.3.8 \
crate://crates.io/core-foundation-sys/0.5.1 \
crate://crates.io/core-foundation/0.5.1 \
crate://crates.io/crossbeam-deque/0.2.0 \
crate://crates.io/crossbeam-epoch/0.3.0 \
crate://crates.io/crossbeam-utils/0.2.2 \
crate://crates.io/crossbeam/0.3.2 \
crate://crates.io/crypto-hash/0.3.1 \
crate://crates.io/curl-sys/0.4.1 \
crate://crates.io/curl/0.4.11 \
crate://crates.io/derive-new/0.5.1 \
crate://crates.io/diff/0.1.11 \
crate://crates.io/dtoa/0.4.2 \
crate://crates.io/either/1.4.0 \
crate://crates.io/ena/0.9.2 \
crate://crates.io/endian-type/0.1.2 \
crate://crates.io/enum_primitive/0.1.1 \
crate://crates.io/env_logger/0.5.6 \
crate://crates.io/error-chain/0.11.0 \
crate://crates.io/failure/0.1.1 \
crate://crates.io/failure_derive/0.1.1 \
crate://crates.io/filetime/0.1.15 \
crate://crates.io/flate2/1.0.1 \
crate://crates.io/fnv/1.0.6 \
crate://crates.io/foreign-types-shared/0.1.1 \
crate://crates.io/foreign-types/0.3.2 \
crate://crates.io/fs2/0.4.3 \
crate://crates.io/fuchsia-zircon-sys/0.3.3 \
crate://crates.io/fuchsia-zircon/0.3.3 \
crate://crates.io/futures/0.1.17 \
crate://crates.io/getopts/0.2.15 \
crate://crates.io/git2-curl/0.8.1 \
crate://crates.io/git2/0.7.1 \
crate://crates.io/glob/0.2.11 \
crate://crates.io/globset/0.3.0 \
crate://crates.io/handlebars/0.29.1 \
crate://crates.io/hex/0.3.1 \
crate://crates.io/home/0.3.2 \
crate://crates.io/humantime/1.1.1 \
crate://crates.io/idna/0.1.4 \
crate://crates.io/if_chain/0.1.2 \
crate://crates.io/ignore/0.4.1 \
crate://crates.io/is-match/0.1.0 \
crate://crates.io/itertools/0.7.6 \
crate://crates.io/itoa/0.4.1 \
crate://crates.io/jobserver/0.1.11 \
crate://crates.io/json/0.11.12 \
crate://crates.io/jsonrpc-core/8.0.1 \
crate://crates.io/kernel32-sys/0.2.2 \
crate://crates.io/languageserver-types/0.35.0 \
crate://crates.io/lazy_static/0.2.11 \
crate://crates.io/lazy_static/1.0.0 \
crate://crates.io/lazycell/0.6.0 \
crate://crates.io/libc/0.2.40 \
crate://crates.io/libgit2-sys/0.7.1 \
crate://crates.io/libssh2-sys/0.2.6 \
crate://crates.io/libz-sys/1.0.18 \
crate://crates.io/log/0.3.9 \
crate://crates.io/log/0.4.1 \
crate://crates.io/log_settings/0.1.1 \
crate://crates.io/lzma-sys/0.1.9 \
crate://crates.io/matches/0.1.6 \
crate://crates.io/mdbook/0.1.2 \
crate://crates.io/memchr/2.0.1 \
crate://crates.io/memoffset/0.2.1 \
crate://crates.io/miniz-sys/0.1.10 \
crate://crates.io/miow/0.3.1 \
crate://crates.io/nibble_vec/0.0.3 \
crate://crates.io/nodrop/0.1.12 \
crate://crates.io/num-integer/0.1.36 \
crate://crates.io/num-iter/0.1.35 \
crate://crates.io/num-traits/0.1.43 \
crate://crates.io/num-traits/0.2.2 \
crate://crates.io/num/0.1.42 \
crate://crates.io/num_cpus/1.8.0 \
crate://crates.io/open/1.2.1 \
crate://crates.io/openssl-probe/0.1.2 \
crate://crates.io/openssl-sys/0.9.27 \
crate://crates.io/openssl/0.10.5 \
crate://crates.io/owning_ref/0.3.3 \
crate://crates.io/parking_lot/0.5.3 \
crate://crates.io/parking_lot_core/0.2.13 \
crate://crates.io/percent-encoding/1.0.1 \
crate://crates.io/pest/0.3.3 \
crate://crates.io/pkg-config/0.3.9 \
crate://crates.io/proc-macro2/0.2.3 \
crate://crates.io/pulldown-cmark/0.1.2 \
crate://crates.io/quick-error/1.2.1 \
crate://crates.io/quine-mc_cluskey/0.2.4 \
crate://crates.io/quote/0.3.15 \
crate://crates.io/quote/0.4.2 \
crate://crates.io/racer/2.0.13 \
crate://crates.io/radix_trie/0.1.2 \
crate://crates.io/rand/0.4.2 \
crate://crates.io/rayon-core/1.4.0 \
crate://crates.io/rayon/1.0.0 \
crate://crates.io/redox_syscall/0.1.37 \
crate://crates.io/redox_termios/0.1.1 \
crate://crates.io/regex-syntax/0.5.3 \
crate://crates.io/regex/0.2.10 \
crate://crates.io/remove_dir_all/0.5.0 \
crate://crates.io/rls-analysis/0.11.3 \
crate://crates.io/rls-blacklist/0.1.0 \
crate://crates.io/rls-data/0.15.0 \
crate://crates.io/rls-rustc/0.2.2 \
crate://crates.io/rls-span/0.4.0 \
crate://crates.io/rls-vfs/0.4.5 \
crate://crates.io/rustc-ap-rustc_cratesio_shim/94.0.0 \
crate://crates.io/rustc-ap-rustc_data_structures/94.0.0 \
crate://crates.io/rustc-ap-rustc_errors/94.0.0 \
crate://crates.io/rustc-ap-serialize/94.0.0 \
crate://crates.io/rustc-ap-syntax/94.0.0 \
crate://crates.io/rustc-ap-syntax_pos/94.0.0 \
crate://crates.io/rustc-demangle/0.1.7 \
crate://crates.io/rustc-serialize/0.3.24 \
crate://crates.io/same-file/1.0.2 \
crate://crates.io/schannel/0.1.11 \
crate://crates.io/scoped-tls/0.1.1 \
crate://crates.io/scopeguard/0.3.3 \
crate://crates.io/semver-parser/0.7.0 \
crate://crates.io/semver/0.9.0 \
crate://crates.io/serde/1.0.35 \
crate://crates.io/serde_derive/1.0.35 \
crate://crates.io/serde_derive_internals/0.22.1 \
crate://crates.io/serde_ignored/0.0.4 \
crate://crates.io/serde_json/1.0.13 \
crate://crates.io/shell-escape/0.1.3 \
crate://crates.io/shlex/0.1.1 \
crate://crates.io/smallvec/0.6.0 \
crate://crates.io/socket2/0.3.4 \
crate://crates.io/stable_deref_trait/1.0.0 \
crate://crates.io/strsim/0.7.0 \
crate://crates.io/syn/0.11.11 \
crate://crates.io/syn/0.12.14 \
crate://crates.io/synom/0.11.3 \
crate://crates.io/synstructure/0.6.1 \
crate://crates.io/syntex_errors/0.52.0 \
crate://crates.io/syntex_pos/0.52.0 \
crate://crates.io/syntex_syntax/0.52.0 \
crate://crates.io/tar/0.4.14 \
crate://crates.io/tempdir/0.3.7 \
crate://crates.io/tempfile/3.0.2 \
crate://crates.io/term/0.4.6 \
crate://crates.io/term/0.5.1 \
crate://crates.io/termcolor/0.3.6 \
crate://crates.io/termion/1.5.1 \
crate://crates.io/textwrap/0.9.0 \
crate://crates.io/thread_local/0.3.5 \
crate://crates.io/time/0.1.39 \
crate://crates.io/toml-query/0.6.0 \
crate://crates.io/toml/0.2.1 \
crate://crates.io/toml/0.4.5 \
crate://crates.io/ucd-util/0.1.1 \
crate://crates.io/unicode-bidi/0.3.4 \
crate://crates.io/unicode-normalization/0.1.5 \
crate://crates.io/unicode-segmentation/1.2.0 \
crate://crates.io/unicode-width/0.1.4 \
crate://crates.io/unicode-xid/0.0.3 \
crate://crates.io/unicode-xid/0.0.4 \
crate://crates.io/unicode-xid/0.1.0 \
crate://crates.io/unreachable/1.0.0 \
crate://crates.io/url/1.7.0 \
crate://crates.io/url_serde/0.2.0 \
crate://crates.io/userenv-sys/0.2.0 \
crate://crates.io/utf8-ranges/1.0.0 \
crate://crates.io/vcpkg/0.2.2 \
crate://crates.io/vec_map/0.8.0 \
crate://crates.io/void/1.0.2 \
crate://crates.io/walkdir/2.1.4 \
crate://crates.io/winapi-build/0.1.1 \
crate://crates.io/winapi-i686-pc-windows-gnu/0.4.0 \
crate://crates.io/winapi-x86_64-pc-windows-gnu/0.4.0 \
crate://crates.io/winapi/0.2.8 \
crate://crates.io/winapi/0.3.4 \
crate://crates.io/wincolor/0.1.6 \
crate://crates.io/xattr/0.1.11 \
crate://crates.io/xz2/0.1.4 \
crate://crates.io/yaml-rust/0.3.5 \
"

DEPENDS += "rust-llvm (=${PV})"

# Otherwise we'll depend on what we provide
INHIBIT_DEFAULT_RUST_DEPS_class-native = "1"
# We don't need to depend on gcc-native because yocto assumes it exists
PROVIDES_class-native = "virtual/${TARGET_PREFIX}rust"

BBCLASSEXTEND = "native"

repository: hongxu-jia/meta-rust

repo_name: hongxu-jia/meta-rust


text:
package jsobj

import "strings"

var functions = map[string]Function{}

type Function = func(args ...interface{}) (obj interface{}, err error)

func RegisterMethod(name string, function Function, caseNotSensitive ...bool) (err error) {
	if len(caseNotSensitive) > 0 && caseNotSensitive[0] {
		name = strings.ToLower(name)
	}
	functions[name] = function
	return
}

repository: johnwiichang/jsobj

repo_name: johnwiichang/jsobj


text:
# Imported as-is from
# https://github.com/labgrid-project/meta-labgrid/commit/74c43def975a32a5310af4441d6e8d86c85a6d71

inherit setuptools3
require python-py-ubjson.inc

SRC_URI[md5sum] = "ce17e26420f663edcd4962957dbcaa33"
SRC_URI[sha256sum] = "81784e64936c12e218afc49ff4fb90702f298ac16848971d9570c87595860762"

repository: jianchangfeng/meta-ros

repo_name: jianchangfeng/meta-ros


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/CvRGBCamera.dir/src/CvRGBCamera.cpp.o"
  "../../../lib/libCvRGBCamera.pdb"
  "../../../lib/libCvRGBCamera.so"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/CvRGBCamera.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)

repository: sophAi/GestureCV

repo_name: sophAi/GestureCV


text:
package invoice

import (
	"strings"
	"time"

	"github.com/jinzhu/now"
	"github.com/jung-kurt/gofpdf"
)

type Bill struct {
	pdf    *gofpdf.Fpdf
	config *BillingConfig
}

// NewBill begins generating an A4-sized Bill
func NewBill(config *BillingConfig) *Bill {
	bill := &Bill{
		pdf:    gofpdf.New("P", "mm", "A4", ""),
		config: config,
	}

	if len(config.Bill.Date) < 1 {
		config.Bill.Date = time.Now().String()
	}

	bill.pdf.SetHeaderFunc(bill.makeHeader())
	bill.pdf.SetFooterFunc(bill.makeFooter())
	bill.pdf.AddPage()

	return bill
}

// lightText sets the font color to the light branding color from
// the config file.
func (b *Bill) lightText() {
	b.pdf.SetTextColor(
		b.config.Colors.ColorLight.R,
		b.config.Colors.ColorLight.G,
		b.config.Colors.ColorLight.B,
	)
}

// darkText sets the font color to the dark branding color from
// the config file.
func (b *Bill) darkText() {
	b.pdf.SetTextColor(
		b.config.Colors.ColorDark.R,
		b.config.Colors.ColorDark.G,
		b.config.Colors.ColorDark.B,
	)
}

// blackText sets the text color to black
func (b *Bill) blackText() {
	b.pdf.SetTextColor(0, 0, 0)
}

// whiteText sets the text color to black
func (b *Bill) whiteText() {
	b.pdf.SetTextColor(255, 255, 255)
}

func (b *Bill) darkDrawColor() {
	b.pdf.SetDrawColor(
		b.config.Colors.ColorDark.R,
		b.config.Colors.ColorDark.G,
		b.config.Colors.ColorDark.B,
	)
}

func (b *Bill) lightFillColor() {
	b.pdf.SetFillColor(
		b.config.Colors.ColorLight.R,
		b.config.Colors.ColorLight.G,
		b.config.Colors.ColorLight.B,
	)
}

// makeHeader returns the function that will be called to build
// the page header. It allows wrapping up the Fpdf instance in
// the closure.
func (b *Bill) makeHeader() func() {
	return func() {
		// It's safe to MustParse here because we validated CLI args
		billTime := now.New(now.MustParse(b.config.Bill.Date))

		// Default to rounding to end of month. Use exact date if specified
		invoiceDate := billTime.EndOfMonth()
		if b.config.Bill.UseExactDate {
			invoiceDate = billTime.Time
		}

		b.pdf.SetFont(b.config.Business.SansFont, "BI", 28)
		b.pdf.ImageOptions(b.config.Business.ImageFile, 0, 10, 100, 0, false, gofpdf.ImageOptions{}, 0, "")

		// Invoice Text
		b.pdf.SetXY(140, 30)
		b.darkText()
		b.text(40, 0, "Invoice")

		// Date and Invoice #
		b.pdf.SetXY(140, 40)
		b.darkText()
		b.pdf.SetFont(b.config.Business.SerifFont, "", 12)
		b.text(20, 0, "Date:")
		b.lightText()
		b.text(20, 0, invoiceDate.Format("January 2, 2006"))

		b.pdf.SetXY(140, 45)
		b.darkText()
		b.text(20, 0, "Invoice #:")
		b.lightText()
		b.text(20, 0, invoiceDate.Format("Jan22006"))

		// Biller Name, Address
		b.pdf.SetXY(8, 40)
		b.darkText()
		b.pdf.SetFont(b.config.Business.SerifFont, "B", 14)
		b.text(40, 0, b.config.Business.Person)

		b.pdf.SetFont(b.config.Business.SerifFont, "", 10)
		b.pdf.SetXY(8, 45)
		b.text(40, 0, b.config.Business.Address)

		// Line Break
		b.pdf.Ln(10)
		b.darkDrawColor()
		b.pdf.Line(8, 50, 200, 50)
	}
}

// makeFooter returns the function that will be called to build
// the page footer. It allows wrapping up the Fpdf instance in
// the closure.
func (b *Bill) makeFooter() func() {
	return func() {
		b.pdf.Ln(10)
		b.darkDrawColor()
		b.pdf.Line(8, 275, 200, 275)
		b.pdf.SetXY(8.0, 280)
		b.darkText()
		b.text(143, 0, b.config.Business.Name)
		b.lightText()
		b.text(40, 0, "Generated: "+time.Now().UTC().Format("2006-01-02 15:04:05"))
	}
}

func (b *Bill) RenderToFile() error {
	b.drawBillTo()

	headers := []string{"Department", "Currency", "Payment Terms", "Due Date"}

	b.drawBillTable(headers, b.config.Bill.Strings())

	headers = []string{"Qty", "Description", "Unit Price", "Line Total"}
	widths := []float64{16, 125.5, 25, 25}

	b.drawBillablesTable(headers, b.config.Billables, b.config.Tax, widths)
	b.drawBankDetails()

	// It's safe to MustParse here because we validate args earlier
	billTime := now.New(now.MustParse(b.config.Bill.Date))

	outFileName := b.config.App.OutputDir + "/" + b.config.Business.Person + " " +
		strings.ToUpper(billTime.EndOfMonth().Format("Jan022006")) + ".pdf"

	err := b.pdf.OutputFileAndClose(outFileName)
	if err != nil {
		return err
	}

	return nil
}

// drawBillTo renders the Bill To part of the bill.
func (b *Bill) drawBillTo() {
	b.blackText()
	b.pdf.Ln(10)
	b.pdf.Ln(10)

	b.text(0, 0, "To: ")
	b.pdf.SetX(20)
	b.text(0, 0, b.config.BillTo.Email)
	b.pdf.Ln(5)
	b.pdf.SetX(20)
	b.text(0, 0, b.config.BillTo.Name)
	b.pdf.Ln(5)
	b.pdf.SetX(20)
	b.text(0, 0, b.config.BillTo.Street)
	b.pdf.Ln(5)
	b.pdf.SetX(20)
	b.text(0, 0, b.config.BillTo.CityStateZip)
	b.pdf.Ln(5)
	b.pdf.SetX(20)
	b.text(0, 0, b.config.BillTo.Country)
}

// drawBillTable renders the summary table for the bill showing the
// department, currency, and terms.
func (b *Bill) drawBillTable(headers []string, values []string) {
	b.pdf.SetFillColor(255, 0, 0)
	b.whiteText()
	b.pdf.SetDrawColor(64, 64, 64)
	b.lightFillColor()
	b.pdf.SetLineWidth(0.3)
	b.pdf.SetFont(b.config.Business.SerifFont, "B", 10)

	baseY := b.pdf.GetY() + 10
	b.pdf.SetY(baseY)
	for _, header := range headers {
		width := float64(len(header)) * 4.9
		b.textFormat(width, 5, header, "1", 0, "C", true, 0, "")
	}

	b.pdf.Ln(5)
	b.pdf.SetFillColor(255, 255, 255)
	b.blackText()
	b.pdf.SetFont(b.config.Business.SerifFont, "", 8)
	for i, val := range values {
		width := float64(len(headers[i])) * 4.9
		b.textFormat(width, 4, val, "1", 0, "L", true, 0, "")
	}

}

// drawBlanks is used to fill in the blank spaces in the table
// that precede, for example, the sub-total, tax, and total entries.
func (b *Bill) drawBlanks(billables []BillableItem, widths []float64) {
	emptyFields := len(billables[0].Strings()) - 2
	for i := 0; i < emptyFields; i++ {
		b.textFormat(widths[i], 4, "", "", 0, "C", true, 0, "")
	}
}

// drawBillableaTable renders the table containing one line each
// for the billable items described in the YAML file.
func (b *Bill) drawBillablesTable(headers []string, billables []BillableItem, taxDetails *TaxDetails, widths []float64) {
	b.pdf.SetFillColor(255, 0, 0)
	b.whiteText()
	b.pdf.SetDrawColor(64, 64, 64)
	b.lightFillColor()
	b.pdf.SetLineWidth(0.3)
	b.pdf.SetFont(b.config.Business.SerifFont, "B", 10)

	baseY := b.pdf.GetY() + 10
	b.pdf.SetY(baseY)
	for i, header := range headers {
		b.textFormat(widths[i], 5, header, "1", 0, "C", true, 0, "")
	}

	b.pdf.Ln(5)
	b.pdf.SetFillColor(255, 255, 255)
	b.blackText()
	b.pdf.SetFont(b.config.Business.SerifFont, "", 8)

	// Keep the sub-total as we run through it
	var subTotal float64

	// Draw the billable items
	for _, billable := range billables {
		for i, val := range billable.Strings() {
			b.textFormat(widths[i], 4, val, "1", 0, "R", true, 0, "")
		}
		subTotal += billable.Total()
		b.pdf.Ln(4)
	}

	// Calculate tax
	var tax float64
	if taxDetails != nil {
		tax = subTotal * taxDetails.DefaultPercentage
	}
	total := subTotal + tax

	// Draw the Sub-Total
	b.pdf.SetDrawColor(255, 255, 255)
	b.pdf.SetFont(b.config.Business.SerifFont, "", 8)
	b.pdf.Ln(2)
	b.drawBlanks(billables, widths)
	subTotalText := billables[0].Currency + " " + niceFloatStr(subTotal)
	b.textFormat(widths[len(widths)-2], 4, "Subtotal", "1", 0, "R", true, 0, "")
	b.textFormat(widths[len(widths)-1], 4, subTotalText, "1", 0, "R", true, 0, "")

	// Handle configurable tax name
	taxName := "Tax"
	if taxDetails != nil && taxDetails.TaxName != "" {
		taxName = taxDetails.TaxName
	}

	// Draw Tax
	b.pdf.Ln(4)
	b.drawBlanks(billables, widths)
	taxText := billables[0].Currency + " " + niceFloatStr(tax)
	b.textFormat(widths[len(widths)-2], 4, taxName, "1", 0, "R", true, 0, "")
	b.textFormat(widths[len(widths)-1], 4, taxText, "1", 0, "R", true, 0, "")

	// Draw Total
	b.pdf.Ln(4)
	b.drawBlanks(billables, widths)
	b.pdf.SetFont(b.config.Business.SerifFont, "B", 10)
	y := b.pdf.GetY()
	x := b.pdf.GetX()
	totalText := billables[0].Currency + " " + niceFloatStr(total)
	b.textFormat(widths[len(widths)-2], 6, "Total", "1", 0, "R", true, 0, "")
	b.textFormat(widths[len(widths)-1], 6, totalText, "1", 0, "R", true, 0, "")
	x2 := b.pdf.GetX()

	b.pdf.SetDrawColor(64, 64, 64)
	b.pdf.Line(x, y, x2, y)
}

// drawBankDetails renders the table that contains the bank details.
func (b *Bill) drawBankDetails() {
	b.pdf.Ln(20)
	b.pdf.SetFont(b.config.Business.SerifFont, "B", 14)
	b.darkText()
	b.text(40, 0, "Payment Details")
	b.pdf.Ln(5)
	b.pdf.SetFont(b.config.Business.SerifFont, "", 8)
	headers := []string{
		"Pay By", "Bank Name", "Address", "Account Type (checking/Savings)",
		"IBAN (international)", "Sort Code (international)", "SWIFT/BIC (international)",
	}

	b.pdf.SetDrawColor(64, 64, 64)
	b.lightFillColor()
	for i, v := range b.config.Bank.Strings() {
		if v == "" {
			continue
		}
		b.whiteText()
		b.pdf.SetFont(b.config.Business.SerifFont, "B", 10)
		b.textFormat(60, 5, headers[i], "1", 0, "R", true, 0, "")
		b.blackText()
		b.pdf.SetFont(b.config.Business.SerifFont, "", 10)
		b.textFormat(100, 5, v, "1", 0, "L", false, 0, "")
		b.pdf.Ln(5)
	}
}

func (b *Bill) text(x, y float64, txtStr string) {
	unicodeToPDF := b.pdf.UnicodeTranslatorFromDescriptor("")
	b.pdf.Cell(x, y, unicodeToPDF(txtStr))
}

func (b *Bill) textFormat(w, h float64, txtStr string, borderStr string, ln int,
	alignStr string, fill bool, link int, linkStr string) {
	unicodeToPDF := b.pdf.UnicodeTranslatorFromDescriptor("")
	b.pdf.CellFormat(w, h, unicodeToPDF(txtStr), borderStr, ln, alignStr, fill, link, linkStr)
}

repository: relistan/billmonger

repo_name: relistan/billmonger


text:
// -*- Mode: Eagle -*-
//
// Drill routines.
//

#include "nonvolatile.h"

string TOOL_FLD   = "tool";
string DRILL_FLD  = "drill_size";
string MIN_FLD    = "minimum";
string MAX_FLD    = "maximum";
string LENGTH_FLD = "length";
char DRILL_SEP  = '\t';
string g_rack[];
int g_num_drills;
int g_drill_sub_cnt[];
real g_mins[];
real g_maxs[];

int m_shut_up;
int m_last_match;
int m_have_rack = false;
string m_rack_file_name = "?";

if (get_nv_param("drill_shut_up", "NO", NO) == "YES") {
	m_shut_up = YES;
}
else {
	m_shut_up = NO;
}

void message(string msg)
{
    if(m_shut_up)
      return;

    msg = "Rack file: " + elided_path(m_rack_file_name, 30) + ":\n" + msg;

    switch(dlgMessageBox(msg, "Ok", "Shut up already", "Never ask again")) {
    case 1:
      m_shut_up = 1;
      break;
    case 2:
      m_shut_up = 1;
      set_nv_param("drill_shut_up", "YES");
      break;
    }
}

void read_rack_file(string drill_file)
{
	string VALID_DRILL_CHARS = "#+-.0123456789imntT\t";

	string drill_raw[];
	int num_raw_drills;
	string key;
	string temp;
	string drill_text;
	int i;

	/*
	* Remove comment lines from the rack file.
	*
	*/
	g_num_drills = 0;
	num_raw_drills = fileread(drill_raw, drill_file);
	string first_char;
	for (i=0; i<num_raw_drills; i++) {
		first_char = strsub(ltrim(drill_raw[i]), 0, 1);
		if (first_char != "#") {
			g_rack[g_num_drills++] = drill_raw[i];
			drill_text += drill_raw[i] + "\n";
		}
	}

	// g_num_drills--;
	// dlgMessageBox(drill_text);
	if (g_num_drills < 1) {
		dlgMessageBox("There are no drills defined in " + drill_file);
		exit(1);
	}

	m_have_rack = true;
	m_rack_file_name = drill_file;
}

void load_rack()
{
	string board_file;
	string drill_file;

	board(B) {
		board_file = B.name;
	}

	drill_file = filesetext(board_file, ".drl");
	if(filetime(drill_file)) {
		read_rack_file(drill_file);
	}
	else if (filetime(DEFAULT_DRILL_FILE)) {
		read_rack_file(DEFAULT_DRILL_FILE);
	}
	else if (filetime(g_path + "/settings/default.drl")) {
		read_rack_file(g_path + "/settings/default.drl");
	}
	else if (DEFAULT_DRILL_FILE != ""){
		dlgMessageBox("Cannot open the default drill rack file:" + EOL +
			DEFAULT_DRILL_FILE + EOL +
			"I also tried:" + EOL +
			g_path + "/settings/default.drl" + EOL +
 			"Please use setup to select a file, or clear the setting if you don't want to use one.");
		exit(1);
	}
}

load_rack();

/**
 * Returns a drill that the user has in stock,
 * based on the min and max values of the hole.
 *
**/
int g_did_subs;
int get_drill_for(int req_size)
{
	int i;
	string key;
	int drill_size;
	int minimum;
	int maximum;
	string str;
	real drill_inch;
	string temp_str;

	//
	// No longer complains about subs being available if there isn't a
	// rack file to begin with.
	//
	if (!m_have_rack) {
		return req_size;
	}

	m_last_match = -1;
	for(i = 0; i < g_num_drills; i++) {
		sprintf(key, "T%02d", i);
		drill_size  = conv_to_units(lookup(g_rack, key, DRILL_FLD, DRILL_SEP));
		minimum     = conv_to_units(lookup(g_rack, key, MIN_FLD, DRILL_SEP));
		maximum     = conv_to_units(lookup(g_rack, key, MAX_FLD, DRILL_SEP));
		sprintf(temp_str, "req = %f, %d min = %f, max = %f",
		u2inch(req_size), i, u2inch(minimum), u2inch(maximum));
		//dlgMessageBox(temp_str);

		if(in_range_int(req_size, minimum, maximum)) {
			if (g_drill_sub_cnt[i] == 0) {
				sprintf(str, "Using drill T%02d\nDrill size: %5.02fmm "
				"(%5.03fin)\nHole size: %5.02fmm (%5.03fin).\n",
				i, u2mm(drill_size), u2inch(drill_size),
				u2mm(req_size), u2inch(req_size));
				//        message(str);
			}
			drill_inch = u2inch(drill_size);
			if (g_mins[i] == 0) g_mins[i] = u2inch(req_size);
			g_mins[i] = min(g_mins[i], u2inch(req_size));
			g_maxs[i] = max(g_maxs[i], u2inch(req_size));
			g_drill_sub_cnt[i] += 1;
			//      sprintf(temp_str, "req = %f, %d min = %f, max = %f", u2inch(req_size), i, g_mins[i], g_maxs[i]);
			//      dlgMessageBox(temp_str);
			g_did_subs = 1;
			m_last_match = i;
			return drill_size;
		}
	}
	message("No drill sub for " + real_to_string(u2inch(req_size)) + "\" " +
		real_to_string(u2mm(req_size)) + "mm");

	return req_size;
}

/**
 * Returns a tool number for a given size, or
 * a default if the size isn't available, there is no
 * rack file, etc.
 *
**/
int get_tool_num_for(int req_size, int default_tool)
{
	if (!m_have_rack) {
		return default_tool;
	}
	get_drill_for(req_size);
	if (m_last_match == -1) m_last_match = default_tool;
	return m_last_match;
}

extension: h


text:
% Encoding: UTF-8

@Unpublished{,
  msbib-abbreviatedcasenumber = {abb},
  msbib-accessed              = {12.10.2015},
  msbib-broadcaster           = {broad},
  msbib-casenumber            = {case},
  msbib-court                 = {court},
  msbib-day                   = {5},
  msbib-distributor           = {dist},
  msbib-medium                = {med},
  msbib-periodical            = {peri},
  msbib-productioncompany     = {produktion},
  msbib-recordingnumber       = {record},
  msbib-reporter              = {rep},
  msbib-station               = {stat},
  msbib-theater               = {th},
  msbib-type                  = {type},
  owner                       = {Ich},
  paper                       = {paper},
  price                       = {10},
  school                      = {Gymnasium Unterrieden},
  series                      = {ser},
  shorttitle                  = {Turing},
  size                        = {1000},
  sourcetype                  = {Interview},
  timestamp                   = {2016.08.19},
  volumes                     = {10},
}

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

repository: JabRef/jabref

repo_name: JabRef/jabref

gha_language: Java


text:
##
## TODO: spark rules are only build tested
##

SUMMARY = "Library to abstract STB hardware. Supports Tripledragon, AZbox ME, Fulan Spark boxes as well as generic PC hardware and the Raspberry Pi right now."
DESCRIPTION = "Library to abstract STB hardware."
HOMEPAGE = "https://github.com/neutrino-mp"
SECTION = "libs"
LICENSE = "GPLv2+"
LIC_FILES_CHKSUM = "file://${THISDIR}/libstb-hal/COPYING.GPL;md5=751419260aa954499f7abaabaa882bbe"

# hack: make sure we do not try to build on coolstream
COMPATIBLE_MACHINE_coolstream = "none"
#
# this stuff really is machine specific, not CPU specific
PACKAGE_ARCH = "${MACHINE_ARCH}"

DEPENDS = "\
	openthreads \
	ffmpeg \
	glew \
	freeglut \
	libao \
	libaio \
"

# on coolstream, the same is provided by cs-drivers pkg (libcoolstream)
PROVIDES += "virtual/stb-hal-libs"

DEPENDS_append_spark = "tdt-driver libass"
DEPENDS_append_raspberrypi = "virtual/egl"
DEPENDS_append_raspberrypi2 = "virtual/egl"
DEPENDS_append_tripledragon = "directfb triple-sdk"

RDEPENDS_${PN} = "ffmpeg"
RDEPENDS_${PN}-dev_append_spark = " tdt-driver-dev"
RDEPENDS_${PN}-dev_append_tripledragon = " triple-sdk-dev"

SRCREV = "${AUTOREV}"
PV = "0.1+git${SRCPV}"

# prepend, or it will end up in -bin package...
PACKAGES_prepend_spark = "spark-fp "
# libstb-hal-bin package for testing binaries etc.
PACKAGES += "${PN}-bin"

LIBSTB_HAL_GIT ?= "git://git.slknet.de/test-libstb-hal-cst-next.git;protocol=https"

SRC_URI = " \
	${LIBSTB_HAL_GIT} \
	file://0001-fix-for-ffmpeg-3.1.3.patch \
	file://blank_480.mpg \
	file://blank_576.mpg \
	file://timer-wakeup.init \
"

S = "${WORKDIR}/git"

# the build system is not really broken wrt separate builddir,
# but I want it to build inside the source for various reasons :-)
inherit autotools-brokensep pkgconfig

# CFLAGS_append = " -Wall -W -Wshadow -g -O2 -fno-strict-aliasing -rdynamic -DNEW_LIBCURL"
CFLAGS_spark += "-funsigned-char"
CPPFLAGS_tripledragon += "-I${STAGING_DIR_HOST}/usr/include/hardware"

LDFLAGS = " -Wl,-rpath-link,${STAGING_DIR_HOST}/usr/lib -L${STAGING_DIR_HOST}/usr/lib -lrt"

EXTRA_OECONF += "\
	--enable-maintainer-mode \
	--disable-silent-rules \
	--enable-shared \
"

EXTRA_OECONF_append_spark += "--with-boxtype=spark"
EXTRA_OECONF_append_raspberrypi += "--with-boxtype=generic --with-boxmodel=raspi"
EXTRA_OECONF_append_raspberrypi2 += "--with-boxtype=generic --with-boxmodel=raspi"
EXTRA_OECONF_append_tripledragon += "--with-boxtype=tripledragon"

do_configure_prepend() {
	export AUTOMAKE="automake --foreign"
	sed -i "s|GLFramebuffer(x, y)|GLFramebuffer(1280, 960)|" ${S}/generic-pc/init.cpp
}

do_install_append() {
	install -d ${D}/${datadir}
}

do_install_append_tripledragon() {
	install -D -m 0644 ${WORKDIR}/blank_576.mpg ${D}/${datadir}/tuxbox/blank_576.mpg
	install -D -m 0644 ${WORKDIR}/blank_480.mpg ${D}/${datadir}/tuxbox/blank_480.mpg
}

do_install_append_spark() {
	install -D -m 0755 ${WORKDIR}/timer-wakeup.init ${D}/${sysconfdir}/init.d/timer-wakeup
	# neutrino is 99, so we put this at 98.
	update-rc.d -r ${D} timer-wakeup start 98 5 .
}

# pic2m2v is included in lib package, because it is always needed,
# libstb-hal-bin contains all other binaries, which are rather for testing only
FILES_${PN} = "\
	${libdir}/* \
	${bindir}/pic2m2v \
	${datadir} \
"

FILES_${PN}-dev += "${includedir}/libstb-hal/*"

FILES_spark-fp = " \
	${bindir}/spark_fp \
	${sysconfdir} \
"

pkg_postinst_${PN} () {
	# after updating libstb-hal, neutrino should be restarted.
	touch /tmp/.restart
}

branch_name: refs/heads/krogoth


text:
package ischema

// Code generated by xo. DO NOT EDIT.

import (
	"database/sql"
)

// Trigger represents a row from 'information_schema.triggers'.
type Trigger struct {
	TriggerCatalog          sql.NullString `json:"trigger_catalog"`            // trigger_catalog
	TriggerSchema           sql.NullString `json:"trigger_schema"`             // trigger_schema
	TriggerName             sql.NullString `json:"trigger_name"`               // trigger_name
	EventManipulation       sql.NullString `json:"event_manipulation"`         // event_manipulation
	EventObjectCatalog      sql.NullString `json:"event_object_catalog"`       // event_object_catalog
	EventObjectSchema       sql.NullString `json:"event_object_schema"`        // event_object_schema
	EventObjectTable        sql.NullString `json:"event_object_table"`         // event_object_table
	ActionOrder             sql.NullInt64  `json:"action_order"`               // action_order
	ActionCondition         sql.NullString `json:"action_condition"`           // action_condition
	ActionStatement         sql.NullString `json:"action_statement"`           // action_statement
	ActionOrientation       sql.NullString `json:"action_orientation"`         // action_orientation
	ActionTiming            sql.NullString `json:"action_timing"`              // action_timing
	ActionReferenceOldTable sql.NullString `json:"action_reference_old_table"` // action_reference_old_table
	ActionReferenceNewTable sql.NullString `json:"action_reference_new_table"` // action_reference_new_table
	ActionReferenceOldRow   sql.NullString `json:"action_reference_old_row"`   // action_reference_old_row
	ActionReferenceNewRow   sql.NullString `json:"action_reference_new_row"`   // action_reference_new_row
	Created                 sql.NullTime   `json:"created"`                    // created
}

repository: xo/xo

repo_name: xo/xo