text:
// +build goleveldbtests

package leveldb

import (
	"encoding/binary"
	"math/rand"
	"reflect"
	"sync"
	"testing"
	"time"

	"github.com/onsi/gomega"
	"github.com/pkt-cash/pktd/goleveldb/leveldb/storage"
	"github.com/pkt-cash/pktd/goleveldb/leveldb/testutil"
)

type testFileRec struct {
	level int
	num   int64
}

func TestVersionStaging(t *testing.T) {
	gomega.RegisterTestingT(t)
	stor := testutil.NewStorage()
	defer stor.Close()
	s, err := newSession(stor, nil)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		s.close()
		s.release()
	}()

	v := newVersion(s)
	v.newStaging()

	tmp := make([]byte, 4)
	mik := func(i uint64) []byte {
		binary.BigEndian.PutUint32(tmp, uint32(i))
		return []byte(makeInternalKey(nil, tmp, 0, keyTypeVal))
	}

	for i, x := range []struct {
		add, del []testFileRec
		trivial  bool
		levels   [][]int64
	}{
		{
			add: []testFileRec{
				{1, 1},
			},
			levels: [][]int64{
				{},
				{1},
			},
		},
		{
			add: []testFileRec{
				{1, 1},
			},
			levels: [][]int64{
				{},
				{1},
			},
		},
		{
			del: []testFileRec{
				{1, 1},
			},
			levels: [][]int64{},
		},
		{
			add: []testFileRec{
				{0, 1},
				{0, 3},
				{0, 2},
				{2, 5},
				{1, 4},
			},
			levels: [][]int64{
				{3, 2, 1},
				{4},
				{5},
			},
		},
		{
			add: []testFileRec{
				{1, 6},
				{2, 5},
			},
			del: []testFileRec{
				{0, 1},
				{0, 4},
			},
			levels: [][]int64{
				{3, 2},
				{4, 6},
				{5},
			},
		},
		{
			del: []testFileRec{
				{0, 3},
				{0, 2},
				{1, 4},
				{1, 6},
				{2, 5},
			},
			levels: [][]int64{},
		},
		{
			add: []testFileRec{
				{0, 1},
			},
			levels: [][]int64{
				{1},
			},
		},
		{
			add: []testFileRec{
				{1, 2},
			},
			levels: [][]int64{
				{1},
				{2},
			},
		},
		{
			add: []testFileRec{
				{0, 3},
			},
			levels: [][]int64{
				{3, 1},
				{2},
			},
		},
		{
			add: []testFileRec{
				{6, 9},
			},
			levels: [][]int64{
				{3, 1},
				{2},
				{},
				{},
				{},
				{},
				{9},
			},
		},
		{
			del: []testFileRec{
				{6, 9},
			},
			levels: [][]int64{
				{3, 1},
				{2},
			},
		},
		// memory compaction
		{
			add: []testFileRec{
				{0, 5},
			},
			trivial: true,
			levels: [][]int64{
				{5, 3, 1},
				{2},
			},
		},
		// memory compaction
		{
			add: []testFileRec{
				{0, 4},
			},
			trivial: true,
			levels: [][]int64{
				{5, 4, 3, 1},
				{2},
			},
		},
		// table compaction
		{
			add: []testFileRec{
				{1, 6},
				{1, 7},
				{1, 8},
			},
			del: []testFileRec{
				{0, 3},
				{0, 4},
				{0, 5},
			},
			trivial: true,
			levels: [][]int64{
				{1},
				{2, 6, 7, 8},
			},
		},
	} {
		rec := &sessionRecord{}
		for _, f := range x.add {
			ik := mik(uint64(f.num))
			rec.addTable(f.level, f.num, 1, ik, ik)
		}
		for _, f := range x.del {
			rec.delTable(f.level, f.num)
		}
		vs := v.newStaging()
		vs.commit(rec)
		v = vs.finish(x.trivial)
		if len(v.levels) != len(x.levels) {
			t.Fatalf("#%d: invalid level count: want=%d got=%d", i, len(x.levels), len(v.levels))
		}
		for j, want := range x.levels {
			tables := v.levels[j]
			if len(want) != len(tables) {
				t.Fatalf("#%d.%d: invalid tables count: want=%d got=%d", i, j, len(want), len(tables))
			}
			got := make([]int64, len(tables))
			for k, t := range tables {
				got[k] = t.fd.Num
			}
			if !reflect.DeepEqual(want, got) {
				t.Fatalf("#%d.%d: invalid tables: want=%v got=%v", i, j, want, got)
			}
		}
	}
}

func TestVersionReference(t *testing.T) {
	gomega.RegisterTestingT(t)
	stor := testutil.NewStorage()
	defer stor.Close()
	s, err := newSession(stor, nil)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		s.close()
		s.release()
	}()

	tmp := make([]byte, 4)
	mik := func(i uint64) []byte {
		binary.BigEndian.PutUint32(tmp, uint32(i))
		return []byte(makeInternalKey(nil, tmp, 0, keyTypeVal))
	}

	// Test normal version task correctness
	refc := make(chan map[int64]int)

	for i, x := range []struct {
		add, del []testFileRec
		expect   map[int64]int
		failed   bool
	}{
		{
			[]testFileRec{{0, 1}, {0, 2}},
			nil,
			map[int64]int{1: 1, 2: 1},
			false,
		},
		{
			[]testFileRec{{0, 3}, {0, 4}},
			[]testFileRec{{0, 1}},
			map[int64]int{2: 1, 3: 1, 4: 1},
			false,
		},
		{
			[]testFileRec{{0, 1}, {0, 5}, {0, 6}, {0, 7}},
			[]testFileRec{{0, 2}, {0, 3}, {0, 4}},
			map[int64]int{1: 1, 5: 1, 6: 1, 7: 1},
			false,
		},
		{
			nil,
			nil,
			map[int64]int{1: 1, 5: 1, 6: 1, 7: 1},
			true,
		},
		{
			[]testFileRec{{0, 1}, {0, 5}, {0, 6}, {0, 7}},
			nil,
			map[int64]int{1: 2, 5: 2, 6: 2, 7: 2},
			false,
		},
		{
			nil,
			[]testFileRec{{0, 1}, {0, 5}, {0, 6}, {0, 7}},
			map[int64]int{1: 1, 5: 1, 6: 1, 7: 1},
			false,
		},
		{
			[]testFileRec{{0, 0}},
			[]testFileRec{{0, 1}, {0, 5}, {0, 6}, {0, 7}},
			map[int64]int{0: 1},
			false,
		},
	} {
		rec := &sessionRecord{}
		for n, f := range x.add {
			rec.addTable(f.level, f.num, 1, mik(uint64(i+n)), mik(uint64(i+n)))
		}
		for _, f := range x.del {
			rec.delTable(f.level, f.num)
		}

		// Simulate some read operations
		var wg sync.WaitGroup
		readN := rand.Intn(300)
		for i := 0; i < readN; i++ {
			wg.Add(1)
			go func() {
				v := s.version()
				time.Sleep(time.Millisecond * time.Duration(rand.Intn(300)))
				v.release()
				wg.Done()
			}()
		}

		v := s.version()
		vs := v.newStaging()
		vs.commit(rec)
		nv := vs.finish(false)

		if x.failed {
			s.abandon <- nv.id
		} else {
			s.setVersion(rec, nv)
		}
		v.release()

		// Wait all read operations
		wg.Wait()

		time.Sleep(100 * time.Millisecond) // Wait lazy reference finish tasks

		s.fileRefCh <- refc
		ref := <-refc
		if !reflect.DeepEqual(ref, x.expect) {
			t.Errorf("case %d failed, file reference mismatch, GOT %v, WANT %v", i, ref, x.expect)
		}
	}

	// Test version task overflow
	var longV = s.version() // This version is held by some long-time operation
	var exp = map[int64]int{0: 1, maxCachedNumber: 1}
	for i := 1; i <= maxCachedNumber; i++ {
		rec := &sessionRecord{}
		rec.addTable(0, int64(i), 1, mik(uint64(i)), mik(uint64(i)))
		rec.delTable(0, int64(i-1))
		v := s.version()
		vs := v.newStaging()
		vs.commit(rec)
		nv := vs.finish(false)
		s.setVersion(rec, nv)
		v.release()
	}
	time.Sleep(100 * time.Millisecond) // Wait lazy reference finish tasks

	s.fileRefCh <- refc
	ref := <-refc
	if !reflect.DeepEqual(exp, ref) {
		t.Errorf("file reference mismatch, GOT %v, WANT %v", ref, exp)
	}

	longV.release()
	s.fileRefCh <- refc
	ref = <-refc
	delete(exp, 0)
	if !reflect.DeepEqual(exp, ref) {
		t.Errorf("file reference mismatch, GOT %v, WANT %v", ref, exp)
	}
}

func BenchmarkVersionStagingNonTrivial(b *testing.B) {
	benchmarkVersionStaging(b, false, 100000)
}

func BenchmarkVersionStagingTrivial(b *testing.B) {
	benchmarkVersionStaging(b, true, 100000)
}

func benchmarkVersionStaging(b *testing.B, trivial bool, size int) {
	stor := storage.NewMemStorage()
	defer stor.Close()
	s, err := newSession(stor, nil)
	if err != nil {
		b.Fatal(err)
	}
	defer func() {
		s.close()
		s.release()
	}()

	tmp := make([]byte, 4)
	mik := func(i uint64) []byte {
		binary.BigEndian.PutUint32(tmp, uint32(i))
		return []byte(makeInternalKey(nil, tmp, 0, keyTypeVal))
	}

	rec := &sessionRecord{}
	for i := 0; i < size; i++ {
		ik := mik(uint64(i))
		rec.addTable(1, int64(i), 1, ik, ik)
	}

	v := newVersion(s)
	vs := v.newStaging()
	vs.commit(rec)
	v = vs.finish(false)

	b.ResetTimer()
	b.ReportAllocs()

	for i := 0; i < b.N; i++ {
		rec := &sessionRecord{}
		index := rand.Intn(size)
		ik := mik(uint64(index))

		cnt := 0
		for j := index; j < size && cnt <= 3; j++ {
			rec.addTable(1, int64(i), 1, ik, ik)
			cnt += 1
		}
		vs := v.newStaging()
		vs.commit(rec)
		vs.finish(trivial)
	}
}

repository: pkt-cash/pktd

repo_name: pkt-cash/pktd

gha_license_id: ISC


text:
// Copyright 2016 The LUCI Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

// Package main is an Isolate server client.
//
// It can efficiently download and upload files from/to an Isolate server. It
// is significantly faster than the original python implementation.
//
// The reference server python implementation documentation can be found at
// https://github.com/luci/luci-py/tree/master/appengine/isolate/doc
package main

repository: mithro/luci-go

license_type: permissive

repo_name: mithro/luci-go

branch_name: refs/heads/master

gha_language: Go

extension: go


text:
/*
Copyright 2023 The Kubernetes Authors.

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

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

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

package key

import (
	"context"
	"os"

	"github.com/go-openapi/strfmt"
	"github.com/spf13/cobra"

	"github.com/IBM/vpc-go-sdk/vpcv1"

	"sigs.k8s.io/cluster-api-provider-ibmcloud/cmd/capibmadm/clients/vpc"
	"sigs.k8s.io/cluster-api-provider-ibmcloud/cmd/capibmadm/options"
	"sigs.k8s.io/cluster-api-provider-ibmcloud/cmd/capibmadm/printer"
	"sigs.k8s.io/cluster-api-provider-ibmcloud/cmd/capibmadm/utils"
	pkgUtils "sigs.k8s.io/cluster-api-provider-ibmcloud/pkg/cloud/services/utils"
)

// ListCommand vpc key list command.
func ListCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "list",
		Short: "List VPC key",
		Example: `
# List key in VPC
export IBMCLOUD_API_KEY=<api-key>
capibmadm vpc key list --region <region> --resource-group-name <resource-group-name>`,
	}

	options.AddCommonFlags(cmd)

	cmd.RunE = func(cmd *cobra.Command, args []string) error {
		return listKeys(cmd.Context())
	}

	return cmd
}

func listKeys(ctx context.Context) error {
	v1, err := vpc.NewV1Client(options.GlobalOptions.VPCRegion)
	if err != nil {
		return err
	}

	var keyNesList []*vpcv1.KeyCollection
	f := func(start string) (bool, string, error) {
		var listKeyOpt vpcv1.ListKeysOptions

		if start != "" {
			listKeyOpt.Start = &start
		}

		keyL, _, err := v1.ListKeysWithContext(ctx, &listKeyOpt)
		if err != nil {
			return false, "", err
		}
		keyNesList = append(keyNesList, keyL)

		if keyL.Next != nil && *keyL.Next.Href != "" {
			return false, *keyL.Next.Href, nil
		}

		return true, "", nil
	}

	if err = pkgUtils.PagingHelper(f); err != nil {
		return err
	}

	return display(keyNesList)
}

func display(keyNesList []*vpcv1.KeyCollection) error {
	var keyListToDisplay List
	for _, keyL := range keyNesList {
		for _, key := range keyL.Keys {
			keyToAppend := Key{
				CreatedAt:   utils.DereferencePointer(key.CreatedAt).(strfmt.DateTime),
				ID:          utils.DereferencePointer(key.ID).(string),
				Name:        utils.DereferencePointer(key.Name).(string),
				Type:        utils.DereferencePointer(key.Type).(string),
				Length:      utils.DereferencePointer(key.Length).(int64),
				FingerPrint: utils.DereferencePointer(key.Fingerprint).(string),
			}

			if key.ResourceGroup != nil {
				keyToAppend.ResourceGroup = utils.DereferencePointer(key.ResourceGroup.Name).(string)
			}

			keyListToDisplay = append(keyListToDisplay, keyToAppend)
		}
	}

	printkeys, err := printer.New(options.GlobalOptions.Output, os.Stdout)

	if err != nil {
		return err
	}

	switch options.GlobalOptions.Output {
	case printer.PrinterTypeJSON:
		err = printkeys.Print(keyListToDisplay)
	default:
		table := keyListToDisplay.ToTable()
		err = printkeys.Print(table)
	}

	return err
}

branch_name: refs/heads/main


text:
@article{stewart:2020,
	Author = {Charles Stewart III and R. Michael Alvarez and Stephen Pettigrew and Cameron Wimpy},
	Date-Modified = {2020-03-17 20:17:31 -0500},
	Journal = {Social Science Quarterly},
	Pages = {1--15},
	Title = {Abstention, Protest, and Residual Votes in the 2016 Election},
	Url = {https://doi.org/10.1111/ssqu.12757},
	Year = {2020}}

license: MIT

repository: cwimpy/website

repo_name: cwimpy/website

extension: bib


text:
package tcc

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"reflect"
	"sync"
	"time"

	"github.com/lovego/sqlmq"
)

type Engine struct {
	sqlmq       *sqlmq.SqlMQ
	mqName      string
	mqTableName string
	actions     map[string]Action
	mutex       sync.RWMutex
}

type Action interface {
	Name() string
	Try() error
	Confirm() error
	Cancel() error
}

// name must be unique for the same mq.
func NewEngine(name string, mq *sqlmq.SqlMQ) *Engine {
	stdTable := mq.Table.(*sqlmq.StdTable)
	engine := &Engine{
		sqlmq:       mq,
		mqName:      "tcc-" + name,
		mqTableName: stdTable.Name(),
		actions:     make(map[string]Action),
	}
	if err := mq.Register(engine.mqName, engine.handle); err != nil {
		panic(time.Now().Format(time.RFC3339Nano) + " " + err.Error())
	}
	return engine
}

func (engine *Engine) Register(actions ...Action) {
	engine.mutex.Lock()
	defer engine.mutex.Unlock()
	for _, action := range actions {
		if name := action.Name(); engine.actions[name] != nil {
			panic(time.Now().Format(time.RFC3339Nano) + " action " + name + " already registered")
		} else {
			engine.actions[name] = action
		}
	}
}

var errTccId = errors.New("tcc id error")

func (engine *Engine) New(timeout time.Duration, concurrent bool) (*TCC, error) {
	now := time.Now()

	msg := &sqlmq.StdMessage{
		Queue: engine.mqName,
		Data: &tccData{
			Status:     statusTrying,
			Concurrent: concurrent,
		},
		CreatedAt: now,
		RetryAt:   now.Add(timeout),
	}
	if err := engine.sqlmq.Produce(nil, msg); err != nil {
		return nil, err
	}
	if msg.Id <= 0 {
		return nil, errTccId
	}
	return &TCC{engine: engine, msg: msg}, nil
}

func (engine *Engine) Run(timeout time.Duration, concurrent bool, actions ...Action) error {
	tcc, err := engine.New(timeout, concurrent)
	if err != nil {
		return err
	}
	for _, action := range actions {
		if err := tcc.Try(action); err != nil {
			if err2 := tcc.Cancel(); err2 != nil {
				engine.sqlmq.Logger.Error(err2)
			}
			return err
		}
	}
	return tcc.Confirm()
}

func (engine *Engine) checkAction(tried Action) error {
	name := tried.Name()
	engine.mutex.RLock()
	registered := engine.actions[name]
	engine.mutex.RUnlock()

	if registered == nil {
		return fmt.Errorf("action %s is not registered", name)
	}
	if reflect.TypeOf(registered) != reflect.TypeOf(tried) {
		return fmt.Errorf(
			`action %s has been registered with type "%T", but tried with type "%T"`,
			name, registered, tried,
		)
	}
	return nil
}

func (engine *Engine) handle(ctx context.Context, tx *sql.Tx, message sqlmq.Message) (
	time.Duration, bool, error,
) {
	msg := message.(*sqlmq.StdMessage)
	data := &tccData{}
	if err := json.Unmarshal(msg.Data.([]byte), &data); err != nil {
		return time.Hour, true, err
	}
	msg.Data = data
	if retryAfter, canCommit, err := (&TCC{engine: engine, msg: msg}).confirmOrCancel(tx); err != nil {
		if retryAfter <= 0 {
			retryAfter = sqlmq.GetRetryWait(msg.TriedCount)
		}
		return retryAfter, canCommit, err
	}
	return 0, true, nil
}

var errActionNotRegistered = errors.New("action not registered")

func (engine *Engine) unmarshalAction(name string, b []byte) (Action, error) {
	engine.mutex.RLock()
	action := engine.actions[name]
	engine.mutex.RUnlock()

	if action == nil {
		return nil, errActionNotRegistered
	}
	actionPointer := reflect.New(reflect.TypeOf(action))
	if err := json.Unmarshal(b, actionPointer.Interface()); err != nil {
		return nil, err
	}
	return actionPointer.Elem().Interface().(Action), nil
}

repository: lovego/tcc

repo_name: lovego/tcc


text:
package group

import (
	"mongo-admin-backend/api/presenter"
)

//Reader interface
type Reader interface {
	Get(publicKey, privateKey string) ([]presenter.MongoGroups, error)
}

//UseCase interface
type UseCase interface {
	Reader
}

repository: PeerIslands/api-mobile-console

repo_name: PeerIslands/api-mobile-console


text:
package fpmoney

import (
	"fmt"
	"testing"
)

const numCurrencies = 181

func TestCurrency(t *testing.T) {
	if len(currencies) != numCurrencies {
		t.Errorf("wrong number of currencies(%d) exp(%d)", len(currencies), numCurrencies)
	}
	if len(fromAlpha) != numCurrencies {
		t.Errorf("wrong number of currencies(%d) exp(%d)", len(fromAlpha), numCurrencies)
	}
}

func TestCurrencyBasic(t *testing.T) {
	c := SGD
	if c.String() != "SGD" {
		t.Error("wrong stringer")
	}
}

func TestCurrencyTextEncoding(t *testing.T) {
	tests := []struct {
		c Currency
		s []byte
	}{
		{
			SGD,
			[]byte("SGD"),
		},
	}
	for _, tc := range tests {
		t.Run(fmt.Sprintf("%#v <-> %s", tc.c, tc.s), func(t *testing.T) {
			var v Currency
			if err := v.UnmarshalText(tc.s); err != nil {
				t.Error(err)
			}
			if v != tc.c {
				t.Error("wrong decode")
			}
			b, err := tc.c.MarshalText()
			if err != nil {
				t.Error(err)
			}
			if string(tc.s) != string(b) {
				t.Error(b, "!=", tc.s)
			}
		})
	}
}

func TestCurrencyTextEncoding_Error(t *testing.T) {
	tests := []struct {
		s []byte
	}{
		{s: []byte("asdf")},
		{s: []byte("sgd")},
		{s: []byte(" SGD")},
		{s: []byte("SGD ")},
		{s: []byte("")},
		{s: []byte("\n")},
		{s: nil},
	}
	for _, tc := range tests {
		t.Run(fmt.Sprintf("%+v", tc.s), func(t *testing.T) {
			var v Currency
			err := v.UnmarshalText(tc.s)
			if err == nil {
				t.Error("expected error")
			}
			if (v != Currency{}) {
				t.Error("wrong zero currency")
			}
		})
	}
}

repository: nikolaydubina/fpmoney

repo_name: nikolaydubina/fpmoney

gha_license_id: MIT


text:
SUMMARY = "Kernel evdev device emulation"
DESCRIPTION = "The evemu library and tools are used to describe devices, record data, create devices and replay data from kernel evdev devices. "
HOMEPAGE = "http://bitmath.org/code/evemu/"

LICENSE = "GPL-3.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=f27defe1e96c2e1ecd4e0c9be8967949"

inherit autotools

SRC_URI = "git://bitmath.org/git/evemu.git;protocol=http;branch=master \
           file://0001-Fix-build-on-32bit-arches-with-64bit-time_t.patch \
           "
SRCREV = "9752b50e922572e4cd214ac45ed95e4ee410fe24"

PV = "1.0.6+git${SRCPV}"

S = "${WORKDIR}/git"

PARALLEL_MAKE = ""

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_language: BitBake

extension: bb


text:
@InProceedings{liang15,
  title = {Landmarking Manifolds with Gaussian Processes},
  author = {Dawen Liang and John Paisley},
  pages = {466-474},
  abstract = {We present an algorithm for finding landmarks along a manifold. These landmarks provide a small set of locations spaced out along the manifold such that they capture the low-dimensional non-linear structure of the data embedded in the high-dimensional space. The approach does not select points directly from the dataset, but instead we optimize each landmark by moving along the continuous manifold space (as approximated by the data) according to the gradient of an objective function. We borrow ideas from active learning with Gaussian processes to define the objective, which has the property that a new landmark is "repelled" by those currently selected, allowing for exploration of the manifold. We derive a stochastic algorithm for learning with large datasets and show results on several datasets, including the Million Song Dataset and articles from the New York Times.},
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_language: TeX


text:
package http

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"testing"

	"github.com/pladdy/cabby"
	"github.com/pladdy/cabby/tester"
)

func TestStatusHandlerDelete(t *testing.T) {
	h := StatusHandler{StatusService: mockStatusService()}
	status, _ := handlerTest(h.Delete, http.MethodDelete, testStatusURL, nil)

	if status != http.StatusMethodNotAllowed {
		t.Error("Got:", status, "Expected:", http.StatusMethodNotAllowed)
	}
}

func TestStatusHandlerGet(t *testing.T) {
	h := StatusHandler{StatusService: mockStatusService()}
	status, body := handlerTest(h.Get, http.MethodGet, testStatusURL, nil)

	if status != http.StatusOK {
		t.Error("Got:", status, "Expected:", http.StatusOK)
	}

	var result cabby.Status
	err := json.Unmarshal([]byte(body), &result)
	if err != nil {
		t.Fatal(err)
	}
	expected := tester.Status

	passed := tester.CompareStatus(result, expected)
	if !passed {
		t.Error("Comparison failed")
	}
}

func TestStatusHandlerGetInternalServerError(t *testing.T) {
	expected := cabby.Error{
		Title: "Internal Server Error", Description: "Status failure", HTTPStatus: http.StatusInternalServerError}

	ms := mockStatusService()
	ms.StatusFn = func(ctx context.Context, statusID string) (cabby.Status, error) {
		return cabby.Status{}, errors.New(expected.Description)
	}

	h := StatusHandler{StatusService: &ms}
	status, body := handlerTest(h.Get, http.MethodGet, testStatusURL, nil)

	if status != expected.HTTPStatus {
		t.Error("Got:", status, "Expected:", expected.HTTPStatus)
	}

	var result cabby.Error
	err := json.Unmarshal([]byte(body), &result)
	if err != nil {
		t.Fatal(err)
	}

	passed := tester.CompareError(result, expected)
	if !passed {
		t.Error("Comparison failed")
	}
}

func TestStatusHandlerGetNoStatus(t *testing.T) {
	ms := mockStatusService()
	ms.StatusFn = func(ctx context.Context, statusID string) (cabby.Status, error) {
		return cabby.Status{}, nil
	}

	h := StatusHandler{StatusService: &ms}
	status, body := handlerTest(h.Get, http.MethodGet, testStatusURL, nil)

	if status != http.StatusNotFound {
		t.Error("Got:", status, "Expected:", http.StatusNotFound)
	}

	var result cabby.Error
	err := json.Unmarshal([]byte(body), &result)
	if err != nil {
		t.Fatal(err)
	}

	expected := tester.ErrorResourceNotFound
	expected.Description = "No status available for this id"

	passed := tester.CompareError(result, expected)
	if !passed {
		t.Error("Comparison failed")
	}
}

func TestStatusHandlePost(t *testing.T) {
	h := StatusHandler{StatusService: mockStatusService()}
	status, _ := handlerTest(h.Post, http.MethodPost, testStatusURL, nil)

	if status != http.StatusMethodNotAllowed {
		t.Error("Got:", status, "Expected:", http.StatusMethodNotAllowed)
	}
}

repository: pladdy/cabby

repo_name: pladdy/cabby


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/facebookgo/gangliamr"
	"github.com/facebookgo/inject"
	"github.com/facebookgo/startstop"
	"github.com/facebookgo/stats"
	"github.com/shutej/dvara"
)

func main() {
	if err := Main(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func Main() error {
	addrs := flag.String("addrs", "localhost:27017", "comma separated list of mongo addresses")
	certFile := flag.String("cert_file", "", "path to the certificate file")
	clientIdleTimeout := flag.Duration("client_idle_timeout", 60*time.Minute, "idle timeout for client connections")
	getLastErrorTimeout := flag.Duration("get_last_error_timeout", time.Minute, "timeout for getLastError pinning")
	keyFile := flag.String("key_file", "", "path to the key file")
	maxConnections := flag.Uint("max_connections", 100, "maximum number of connections per mongo")
	maxPerClientConnections := flag.Uint("max_per_client_connections", 1, "maximum number of connections from a single client")
	messageTimeout := flag.Duration("message_timeout", 2*time.Minute, "timeout for one message to be proxied")
	password := flag.String("password", "", "")
	portEnd := flag.Int("port_end", 6010, "end of port range")
	portStart := flag.Int("port_start", 6000, "start of port range")
	serverClosePoolSize := flag.Uint("server_close_pool_size", 1, "number of goroutines that will handle closing server connections.")
	serverIdleTimeout := flag.Duration("server_idle_timeout", 60*time.Minute, "duration after which a server connection will be considered idle")
	username := flag.String("username", "", "")

	flag.Parse()

	replicaSet := dvara.ReplicaSet{
		Addrs:                   *addrs,
		CertFile:                *certFile,
		ClientIdleTimeout:       *clientIdleTimeout,
		GetLastErrorTimeout:     *getLastErrorTimeout,
		KeyFile:                 *keyFile,
		MaxConnections:          *maxConnections,
		MaxPerClientConnections: *maxPerClientConnections,
		MessageTimeout:          *messageTimeout,
		Password:                *password,
		PortEnd:                 *portEnd,
		PortStart:               *portStart,
		ServerClosePoolSize:     *serverClosePoolSize,
		ServerIdleTimeout:       *serverIdleTimeout,
		Username:                *username,
	}

	var log stdLogger
	var graph inject.Graph
	err := graph.Provide(
		&inject.Object{Value: &log},
		&inject.Object{Value: &replicaSet},
		&inject.Object{Value: &stats.HookClient{}},
	)
	if err != nil {
		return err
	}
	if err := graph.Populate(); err != nil {
		return err
	}
	objects := graph.Objects()

	// Temporarily setup the metrics against a test registry.
	gregistry := gangliamr.NewTestRegistry()
	for _, o := range objects {
		if rmO, ok := o.Value.(registerMetrics); ok {
			rmO.RegisterMetrics(gregistry)
		}
	}
	if err := startstop.Start(objects, &log); err != nil {
		return err
	}
	defer startstop.Stop(objects, &log)

	ch := make(chan os.Signal, 2)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT)
	<-ch
	signal.Stop(ch)
	return nil
}

type registerMetrics interface {
	RegisterMetrics(r *gangliamr.Registry)
}

repository: shutej/dvara

repo_name: shutej/dvara


text:
// Copyright (c) 2018 Danilo Bürger <info@danilobuerger.de>

package null

import (
	"database/sql"
	"database/sql/driver"
	"encoding"
	"encoding/json"
	"encoding/xml"
	"strconv"
)

var (
	_ sql.Scanner              = (*Float64)(nil)
	_ driver.Valuer            = (*Float64)(nil)
	_ json.Marshaler           = (*Float64)(nil)
	_ json.Unmarshaler         = (*Float64)(nil)
	_ encoding.TextMarshaler   = (*Float64)(nil)
	_ encoding.TextUnmarshaler = (*Float64)(nil)
	_ xml.Marshaler            = (*Float64)(nil)
	_ xml.Unmarshaler          = (*Float64)(nil)
)

// Float64 represents a float64 that may be null.
type Float64 struct {
	sql.NullFloat64
}

// NewFloat64 creates a new Float64.
func NewFloat64(f float64) Float64 {
	return Float64{sql.NullFloat64{Float64: f, Valid: true}}
}

// NewFloat64Ptr creates a new Float64 pointer.
func NewFloat64Ptr(f float64) *Float64 {
	v := NewFloat64(f)
	return &v
}

// MarshalJSON implements the json.Marshaler interface.
func (f Float64) MarshalJSON() ([]byte, error) {
	if !f.Valid {
		return []byte(jsonNull), nil
	}
	return json.Marshal(f.Float64)
}

// UnmarshalJSON implements the json.Unmarshaler interface.
func (f *Float64) UnmarshalJSON(data []byte) error {
	if len(data) == 0 || string(data) == jsonNull {
		f.Float64, f.Valid = 0, false
		return nil
	}
	f.Valid = true
	return json.Unmarshal(data, &f.Float64)
}

// MarshalText implements the encoding.TextMarshaler interface.
func (f Float64) MarshalText() ([]byte, error) {
	if !f.Valid {
		return []byte{}, nil
	}
	return []byte(strconv.FormatFloat(f.Float64, 'f', -1, 64)), nil
}

// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (f *Float64) UnmarshalText(data []byte) (err error) {
	if len(data) == 0 {
		f.Float64, f.Valid = 0, false
		return nil
	}
	f.Valid = true
	f.Float64, err = strconv.ParseFloat(string(data), 64)
	return
}

// MarshalXML implements the xml.Marshaler interface.
func (f Float64) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	if !f.Valid {
		start.Attr = []xml.Attr{xsiNilAttr}
		if err := e.EncodeToken(start); err != nil {
			return err
		}
		return e.EncodeToken(start.End())
	}
	return e.EncodeElement(f.Float64, start)
}

// UnmarshalXML implements the xml.Unmarshaler interface.
func (f *Float64) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	for _, attr := range start.Attr {
		if isXsiNilAttr(attr) {
			f.Float64, f.Valid = 0, false
			return d.Skip()
		}
	}
	f.Valid = true
	return d.DecodeElement(&f.Float64, &start)
}

repository: danilobuerger/null

repo_name: danilobuerger/null


text:
package testing

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/openstack/identity/v3/endpoints"
	"github.com/gophercloud/gophercloud/pagination"
	th "github.com/gophercloud/gophercloud/testhelper"
	"github.com/gophercloud/gophercloud/testhelper/client"
)

func TestCreateSuccessful(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/endpoints", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "POST")
		th.TestHeader(t, r, "X-Auth-Token", client.TokenID)
		th.TestJSONRequest(t, r, `
      {
        "endpoint": {
          "interface": "public",
          "name": "the-endiest-of-points",
          "region": "underground",
          "url": "https://1.2.3.4:9000/",
          "service_id": "asdfasdfasdfasdf"
        }
      }
    `)

		w.WriteHeader(http.StatusCreated)
		fmt.Fprintf(w, `
      {
        "endpoint": {
          "id": "12",
          "interface": "public",
		  "enabled": true,
		  "links": {
            "self": "https://localhost:5000/v3/endpoints/12"
          },
          "name": "the-endiest-of-points",
          "region": "underground",
          "service_id": "asdfasdfasdfasdf",
          "url": "https://1.2.3.4:9000/"
        }
      }
    `)
	})

	actual, err := endpoints.Create(client.ServiceClient(), endpoints.CreateOpts{
		Availability: gophercloud.AvailabilityPublic,
		Name:         "the-endiest-of-points",
		Region:       "underground",
		URL:          "https://1.2.3.4:9000/",
		ServiceID:    "asdfasdfasdfasdf",
	}).Extract()
	th.AssertNoErr(t, err)

	expected := &endpoints.Endpoint{
		ID:           "12",
		Availability: gophercloud.AvailabilityPublic,
		Enabled:      true,
		Name:         "the-endiest-of-points",
		Region:       "underground",
		ServiceID:    "asdfasdfasdfasdf",
		URL:          "https://1.2.3.4:9000/",
	}

	th.AssertDeepEquals(t, expected, actual)
}

func TestListEndpoints(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/endpoints", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "GET")
		th.TestHeader(t, r, "X-Auth-Token", client.TokenID)

		w.Header().Add("Content-Type", "application/json")
		fmt.Fprintf(w, `
			{
				"endpoints": [
					{
						"id": "12",
						"interface": "public",
						"enabled": true,
						"links": {
							"self": "https://localhost:5000/v3/endpoints/12"
						},
						"name": "the-endiest-of-points",
						"region": "underground",
						"service_id": "asdfasdfasdfasdf",
						"url": "https://1.2.3.4:9000/"
					},
					{
						"id": "13",
						"interface": "internal",
						"enabled": false,
						"links": {
							"self": "https://localhost:5000/v3/endpoints/13"
						},
						"name": "shhhh",
						"region": "underground",
						"service_id": "asdfasdfasdfasdf",
						"url": "https://1.2.3.4:9001/"
					}
				],
				"links": {
					"next": null,
					"previous": null
				}
			}
		`)
	})

	count := 0
	endpoints.List(client.ServiceClient(), endpoints.ListOpts{}).EachPage(func(page pagination.Page) (bool, error) {
		count++
		actual, err := endpoints.ExtractEndpoints(page)
		if err != nil {
			t.Errorf("Failed to extract endpoints: %v", err)
			return false, err
		}

		expected := []endpoints.Endpoint{
			{
				ID:           "12",
				Availability: gophercloud.AvailabilityPublic,
				Enabled:      true,
				Name:         "the-endiest-of-points",
				Region:       "underground",
				ServiceID:    "asdfasdfasdfasdf",
				URL:          "https://1.2.3.4:9000/",
			},
			{
				ID:           "13",
				Availability: gophercloud.AvailabilityInternal,
				Enabled:      false,
				Name:         "shhhh",
				Region:       "underground",
				ServiceID:    "asdfasdfasdfasdf",
				URL:          "https://1.2.3.4:9001/",
			},
		}
		th.AssertDeepEquals(t, expected, actual)
		return true, nil
	})
	th.AssertEquals(t, 1, count)
}

func TestUpdateEndpoint(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/endpoints/12", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "PATCH")
		th.TestHeader(t, r, "X-Auth-Token", client.TokenID)
		th.TestJSONRequest(t, r, `
		{
	    "endpoint": {
	      "name": "renamed",
				"region": "somewhere-else"
	    }
		}
	`)

		fmt.Fprintf(w, `
		{
			"endpoint": {
				"id": "12",
				"interface": "public",
				"enabled": true,
				"links": {
					"self": "https://localhost:5000/v3/endpoints/12"
				},
				"name": "renamed",
				"region": "somewhere-else",
				"service_id": "asdfasdfasdfasdf",
				"url": "https://1.2.3.4:9000/"
			}
		}
	`)
	})

	actual, err := endpoints.Update(client.ServiceClient(), "12", endpoints.UpdateOpts{
		Name:   "renamed",
		Region: "somewhere-else",
	}).Extract()
	if err != nil {
		t.Fatalf("Unexpected error from Update: %v", err)
	}

	expected := &endpoints.Endpoint{
		ID:           "12",
		Availability: gophercloud.AvailabilityPublic,
		Enabled:      true,
		Name:         "renamed",
		Region:       "somewhere-else",
		ServiceID:    "asdfasdfasdfasdf",
		URL:          "https://1.2.3.4:9000/",
	}
	th.AssertDeepEquals(t, expected, actual)
}

func TestDeleteEndpoint(t *testing.T) {
	th.SetupHTTP()
	defer th.TeardownHTTP()

	th.Mux.HandleFunc("/endpoints/34", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "DELETE")
		th.TestHeader(t, r, "X-Auth-Token", client.TokenID)

		w.WriteHeader(http.StatusNoContent)
	})

	res := endpoints.Delete(client.ServiceClient(), "34")
	th.AssertNoErr(t, res.Err)
}

repository: gophercloud/gophercloud

repo_name: gophercloud/gophercloud

gha_license_id: NOASSERTION


text:
#include "../include/cIGZApp.h"
#include "../include/cIGZFrameWork.h"
#include "../include/cIGZMessage2.h"
#include "../include/cIGZMessageServer2.h"
#include "../include/cIGZMessageTarget2.h"
#include "../include/cISC4App.h"
#include "../include/cISC4RenderProperties.h"
#include "../include/cRZCOMDllDirector.h"
#include "../include/GZServPtrs.h"

static const uint32_t kExtraCheatsPluginCOMDirectorID = 0x8bbd9623;
static const uint32_t kGZIID_cISC4App = 0x26ce01c0;

class cSC4ExtraCheatsPluginCOMDirector : public cRZCOMDllDirector
{
	public:
		/* Failing to explicitly delegate these methods results in some
		   ambiguity when resolving which virtual methods to use: those
		   from cIGZMessageTarget (which are pure abstract) or those from
		   cRZCOMDllDirector, and the compiler will complain. */
		bool QueryInterface(uint32_t riid, void** ppvObj) {
			return cRZCOMDllDirector::QueryInterface(riid, ppvObj);
		}

		uint32_t AddRef(void) {
			return cRZCOMDllDirector::AddRef();
		}

		uint32_t Release(void) {
			return cRZCOMDllDirector::Release();
		}

		uint32_t GetDirectorID() const {
			return kExtraCheatsPluginCOMDirectorID;
		}

		bool PreAppInit() {
			cIGZFrameWork* const pFramework = RZGetFrameWork();
			if (pFramework) {
				cIGZApp* const pApp = pFramework->Application();
				if (pApp) {
					cISC4App* pISC4App;
					if (pApp->QueryInterface(kGZIID_cISC4App, (void**)&pISC4App)) {
						pISC4App->SetDebugFunctionalityEnabled(true);
					}
				}
			}

			return true;
		}

		bool PostAppInit() {
			return true;
		}

		bool OnStart(cIGZCOM* pCOM) {
			cIGZFrameWork* const pFramework = RZGetFrameWork();
			if (pFramework) {
				if (pFramework->GetState() < cIGZFrameWork::kStatePreAppInit) {
					pFramework->AddHook(this);
				}
				else {
					PreAppInit();
				}
			}
			return true;
		}
};

repository: caspervg/gzcom-dll

repo_name: caspervg/gzcom-dll

extension: cpp


text:
using System;

using P3D.Legacy.Launcher.Data;

using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

namespace P3D.Legacy.Launcher.YamlConverters
{
    internal class ProfileTypeConverter : IYamlTypeConverter
    {
        public bool Accepts(Type type) => type == typeof(ProfileType);

        public object ReadYaml(IParser parser, Type type)
        {
            var value = ((Scalar) parser.Current).Value;
            parser.MoveNext();
            return ProfileType.GetProfileType(value);
        }

        public void WriteYaml(IEmitter emitter, object value, Type type)
        {
            var profileType = (ProfileType) value;
            emitter.Emit(new Scalar(null, null, profileType.Name, ScalarStyle.Plain, true, false));
        }
    }
}

gha_language: C#

extension: cs


text:
@article{https://doi.org/10.1002/clt2.12019,
author = {Hurault, Guillem and Delorieux, Valentin and Kim, Young-Min and Ahn, Kangmo and Williams, Hywel C. and Tanaka, Reiko J.},
title = {Impact of environmental factors in predicting daily severity scores of atopic dermatitis},
journal = {Clinical and Translational Allergy},
volume = {11},
number = {2},
pages = {e12019},
keywords = {atopic dermatitis, environmental factors, longitudinal data, prediction, statistical machine learning},
doi = {https://doi.org/10.1002/clt2.12019},
url = {https://onlinelibrary.wiley.com/doi/abs/10.1002/clt2.12019},
eprint = {https://onlinelibrary.wiley.com/doi/pdf/10.1002/clt2.12019},
abstract = {Abstract Background Atopic dermatitis (AD) is a chronic inflammatory skin disease that affects 20\% of children worldwide. Environmental factors including weather and air pollutants have been shown to be associated with AD symptoms. However, the time-dependent nature of such a relationship has not been adequately investigated. This paper aims to assess whether real-time data on weather and air pollutants can make short-term prediction of AD severity scores. Methods Using longitudinal data from a published panel study of 177 paediatric patients followed up daily for 17 months, we developed a statistical machine learning model to predict daily AD severity scores for individual study participants. Exposures consisted of daily meteorological variables and concentrations of air pollutants, and outcomes were daily recordings of scores for six AD signs. We developed a mixed-effect autoregressive ordinal logistic regression model, validated it in a forward-chaining setting and evaluated the effects of the environmental factors on the predictive performance. Results Our model successfully made daily prediction of the AD severity scores, and the predictive performance was not improved by the addition of measured environmental factors. Potential short-term influence of environmental exposures on daily AD severity scores was outweighed by the underlying persistence of preceding scores. Conclusions Our data does not offer enough evidence to support a claim that weather or air pollutants can make short-term prediction of AD signs. Inferences about the magnitude of the effect of environmental factors on AD severity scores require consideration of their time-dependent dynamic nature.},
year = {2021}
}

repository: ghurault/personal-website

repo_name: ghurault/personal-website


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

// These tests should run without any network interface (except loopback).

#include <arpa/inet.h>

#include "gtest/gtest.h"

namespace {

TEST(NoNetworkTest, NonBlockingConnectHostV4) {
  int connfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  ASSERT_GE(connfd, 0) << "socket failed: " << strerror(errno);

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  inet_pton(AF_INET, "192.168.0.1", &addr.sin_addr);
  addr.sin_port = htons(10000);

  int ret = connect(connfd, (const struct sockaddr*)&addr, sizeof(addr));
  ASSERT_EQ(-1, ret);
  ASSERT_EQ(EHOSTUNREACH, errno) << "connect failed: " << strerror(errno);

  ASSERT_EQ(0, close(connfd)) << "close failed: " << strerror(errno);
}

TEST(NoNetworkTest, NonBlockingConnectHostV6) {
  int connfd = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, 0);
  ASSERT_GE(connfd, 0) << "socket failed: " << strerror(errno);

  struct sockaddr_in6 addr;
  addr.sin6_family = AF_INET6;
  inet_pton(AF_INET6, "fc00::1", &addr.sin6_addr);
  addr.sin6_port = htons(10000);

  int ret = connect(connfd, (const struct sockaddr*)&addr, sizeof(addr));
  ASSERT_EQ(-1, ret);
  ASSERT_EQ(EHOSTUNREACH, errno) << "connect failed: " << strerror(errno);

  ASSERT_EQ(0, close(connfd)) << "close failed: " << strerror(errno);
}

TEST(NoNetworkTest, NonBlockingConnectNetV4) {
  int connfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  ASSERT_GE(connfd, 0) << "socket failed: " << strerror(errno);

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  inet_pton(AF_INET, "224.0.0.0", &addr.sin_addr);  // multicast address
  addr.sin_port = htons(10000);

  int ret = connect(connfd, (const struct sockaddr*)&addr, sizeof(addr));
  ASSERT_EQ(-1, ret);
  ASSERT_EQ(ENETUNREACH, errno) << "connect failed: " << strerror(errno);

  ASSERT_EQ(0, close(connfd)) << "close failed: " << strerror(errno);
}

TEST(NoNetworkTest, NonBlockingConnectNetV6) {
  int connfd = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, 0);
  ASSERT_GE(connfd, 0) << "socket failed: " << strerror(errno);

  struct sockaddr_in6 addr;
  addr.sin6_family = AF_INET6;
  inet_pton(AF_INET6, "fe80::1", &addr.sin6_addr);  // linklocal address
  addr.sin6_port = htons(10000);

  int ret = connect(connfd, (const struct sockaddr*)&addr, sizeof(addr));
  ASSERT_EQ(-1, ret);
  ASSERT_EQ(ENETUNREACH, errno) << "connect failed: " << strerror(errno);

  ASSERT_EQ(0, close(connfd)) << "close failed: " << strerror(errno);
}

}  // namespace

extension: cc


text:
# Released under the MIT license (see COPYING.MIT for the terms)

# Applications using this library needs to add link against libbreakpad_client.a.

SUMMARY = "An open-source multi-platform crash reporting system"
DESCRIPTION = "Breakpad is a library and tool suite that allows you to distribute an application to users with compiler-provided debugging information removed, record crashes in compact \"minidump\" files, send them back to your server, and produce C and C++ stack traces from these minidumps. "
HOMEPAGE = "https://code.google.com/p/google-breakpad/"
LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://LICENSE;md5=07aeb530115539d62cacf9942fa60cac"
SECTION = "libs"

inherit autotools

DEPENDS += "zlib"
DEPENDS:append:libc-musl = " libucontext"

BBCLASSEXTEND = "native"

PE = "2"

PV = "1.0"

SRCREV_FORMAT = "breakpad_gtest_protobuf_lss_gyp"

SRCREV_breakpad = "7a1a190f4f68e8a3e06788498f50a4d5520a69f3"
#v1.10.0
SRCREV_gtest = "e2239ee6043f73722e7aa812a459f54a28552929"
SRCREV_protobuf = "cb6dd4ef5f82e41e06179dcd57d3b1d9246ad6ac"
SRCREV_lss = "9719c1e1e676814c456b55f5f070eabad6709d31"
SRCREV_gyp = "324dd166b7c0b39d513026fa52d6280ac6d56770"

SRC_URI = "git://github.com/google/breakpad;name=breakpad;branch=main;protocol=https \
           git://github.com/google/googletest.git;destsuffix=git/src/testing/gtest;name=gtest;branch=main;protocol=https \
           git://github.com/protocolbuffers/protobuf.git;destsuffix=git/src/third_party/protobuf/protobuf;name=protobuf;branch=master;protocol=https \
           git://chromium.googlesource.com/linux-syscall-support;protocol=https;branch=main;destsuffix=git/src/third_party/lss;name=lss \
           git://chromium.googlesource.com/external/gyp;protocol=https;destsuffix=git/src/tools/gyp;name=gyp;branch=master \
           file://0001-include-sys-reg.h-to-get-__WORDSIZE-on-musl-libc.patch \
           file://0003-Fix-conflict-between-musl-libc-dirent.h-and-lss.patch \
           file://0001-Turn-off-sign-compare-for-musl-libc.patch \
           file://0003-Dont-include-stab.h.patch \
           file://0004-elf_reader.cc-include-sys-reg.h-to-get-__WORDSIZE-on.patch \
           file://mcontext.patch \
           file://0001-Remove-HAVE_GETCONTEXT-check-to-add-local-implementa.patch \
           file://0001-lss-Match-syscalls-to-match-musl.patch;patchdir=src/third_party/lss \
           file://mips_asm_sgidefs.patch;patchdir=src/third_party/lss \
"
S = "${WORKDIR}/git"

CXXFLAGS += "-D_GNU_SOURCE"
LDFLAGS:append:libc-musl = " -lucontext"

COMPATIBLE_HOST:powerpc = "null"
COMPATIBLE_HOST:powerpc64 = "null"
COMPATIBLE_HOST:powerpc64le = "null"
COMPATIBLE_HOST:riscv64 = "null"
COMPATIBLE_HOST:riscv32 = "null"

do_install:append() {
        install -d ${D}${includedir}
        install -d ${D}${includedir}/breakpad

        install -d ${D}${includedir}/breakpad/client/linux/crash_generation
        install -m 0644 ${S}/src/client/linux/crash_generation/crash_generation_client.h  ${D}${includedir}/breakpad/client/linux/crash_generation/crash_generation_client.h

        install -d ${D}${includedir}/breakpad/client/linux/handler/
        install -m 0644 ${S}/src/client/linux/handler/exception_handler.h ${D}${includedir}/breakpad/client/linux/handler/exception_handler.h
        install -m 0644 ${S}/src/client/linux/handler/minidump_descriptor.h ${D}${includedir}/breakpad/client/linux/handler/minidump_descriptor.h

        install -d ${D}${includedir}/breakpad/client/linux/dump_writer_common
        install -m 0644 ${S}/src/client/linux/dump_writer_common/mapping_info.h ${D}${includedir}/breakpad/client/linux/dump_writer_common/mapping_info.h
        install -m 0644 ${S}/src/client/linux/dump_writer_common/thread_info.h ${D}${includedir}/breakpad/client/linux/dump_writer_common/thread_info.h
        install -m 0644 ${S}/src/client/linux/dump_writer_common/raw_context_cpu.h ${D}${includedir}/breakpad/client/linux/dump_writer_common/raw_context_cpu.h

        install -d ${D}${includedir}/breakpad/client/linux/minidump_writer
        install -m 0644 ${S}/src/client/linux/minidump_writer/linux_dumper.h ${D}${includedir}/breakpad/client/linux/minidump_writer/linux_dumper.h
        install -m 0644 ${S}/src/client/linux/minidump_writer/minidump_writer.h ${D}${includedir}/breakpad/client/linux/minidump_writer/minidump_writer.h

        install -d ${D}${includedir}/breakpad/common
        install -m 0644 ${S}/src/common/memory_allocator.h ${D}${includedir}/breakpad/common/memory_allocator.h
        install -m 0644 ${S}/src/common/scoped_ptr.h ${D}${includedir}/breakpad/common/scoped_ptr.h
        install -m 0644 ${S}/src/common/using_std_string.h ${D}${includedir}/breakpad/common/using_std_string.h

        install -d ${D}${includedir}/breakpad/google_breakpad/common
        install -m 0644 ${S}/src/google_breakpad/common/breakpad_types.h ${D}${includedir}/breakpad/google_breakpad/common/breakpad_types.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_format.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_format.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_cpu_amd64.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_cpu_amd64.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_cpu_arm.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_cpu_arm.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_cpu_arm64.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_cpu_arm64.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_cpu_mips.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_cpu_mips.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_cpu_ppc64.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_cpu_ppc64.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_cpu_ppc.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_cpu_ppc.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_cpu_sparc.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_cpu_sparc.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_cpu_x86.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_cpu_x86.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_exception_linux.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_exception_linux.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_exception_mac.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_exception_mac.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_exception_ps3.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_exception_ps3.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_exception_solaris.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_exception_solaris.h
        install -m 0644 ${S}/src/google_breakpad/common/minidump_exception_win32.h ${D}${includedir}/breakpad/google_breakpad/common/minidump_exception_win32.h

        install -d ${D}${includedir}/breakpad/third_party/lss
        install -m 0644 ${S}/src/third_party/lss/linux_syscall_support.h ${D}${includedir}/breakpad/third_party/lss/linux_syscall_support.h
}

PACKAGES =+ "${PN}-minidump-upload ${PN}-sym-upload"

FILES:${PN}-minidump-upload = "${bindir}/minidump_upload"
FILES:${PN}-sym-upload = "${bindir}/sym_upload"

SYSROOT_PREPROCESS_FUNCS += "breakpad_populate_sysroot"
breakpad_populate_sysroot() {
        sysroot_stage_dir ${D}/usr/include ${SYSROOT_DESTDIR}/usr/include
        sysroot_stage_dir ${D}/usr/lib ${SYSROOT_DESTDIR}/usr/lib
        sysroot_stage_dir ${D}/usr/lib ${SYSROOT_DESTDIR}/usr/lib
}

# Fails to build with thumb-1 (qemuarm)
#| {standard input}: Assembler messages:
#| {standard input}:2178: Error: selected processor does not support Thumb mode `it ne'
#| {standard input}:2179: Error: Thumb does not support conditional execution
#| {standard input}:2180: Error: selected processor does not support Thumb mode `it eq'
#| {standard input}:2181: Error: Thumb does not support conditional execution
#| {standard input}:2183: Error: lo register required -- `str ip,[r1,#-4]!'
#| {standard input}:2184: Error: Thumb does not support this addressing mode -- `str r6,[r1,#-4]!'
#| {standard input}:2191: Error: lo register required -- `ldr pc,[sp]'
#| make: *** [src/client/linux/handler/exception_handler.o] Error 1
ARM_INSTRUCTION_SET:armv5 = "arm"
ARM_INSTRUCTION_SET:armv4 = "arm"

TOOLCHAIN = "gcc"


text:
DESCRIPTION = "Handle & repair many DVB radio & television stream types."
MAINTAINER = "Andreas Frisch <andreas.frisch@multimedia-labs.de>"
LICENSE="GPL-2"
SECTION = "optional"
DEPENDS = ""
RDEPENDS_${PN} = ""
PN = "projectx"
PV = "0.90.4.00.b32"
PR = "r0"
SRCDATE = "20090824"

#SRC_URI = "cvs://anonymous@project-x.cvs.sourceforge.net/cvsroot/project-x;module=Project-X;method=pserver\
SRC_URI = "http://opengit.homelinux.com/pub/OpenPLi/src/Project-X_project-x.cvs.sourceforge.net__${SRCDATE}.tar.gz\
           file://dreambox-headless.patch \
           file://Makefile"

PRECOMPILED_N = "${PN}-mipsel-bin-20100218-${PV}-1.6.0-${TARGET_FPU}.tar.bz2"
PRECOMPILED_URI = "http://dreamboxupdate.com/download/opendreambox/${PRECOMPILED_N}"

do_unpack_extra() {
	mv ${WORKDIR}/Project-X ${S}
	mv ${WORKDIR}/Makefile ${S}/src
}
addtask unpack_extra after do_unpack before do_patch

do_compile_prepend() {
	export CROSS_LIBDIR="${CROSS_DIR}/${TARGET_SYS}/lib"
	export GCJ_ARCH=""
	for gcjarchives in libgcj.a libgij.a; do
		if test -e ${CROSS_LIBDIR}/$gcjarchives; then
			export GCJ_ARCHIVES="${GCJ_ARCHIVES} ${CROSS_LIBDIR}/$gcjarchives"
		fi
	done
	if [ "${GCJ_ARCHIVES}" = "" ]; then
		echo gcj not found, downloading statically linked binary
		exit
	else
		echo ${GCJ_ARCHIVES} found, compiling...
	fi
}

do_compile() {
	export JFLAGS="-g0 -O2 -march=mips32 -encoding \"ISO-8859-1\""
	export CROSS_COMPILE=${TARGET_PREFIX}
	cd ${S}/src
	make projectx-static
}

do_download_precompiled_binary() {
	if ! test -e ${S}/src/projectx; then
		cd ${S}/src
		wget ${PRECOMPILED_URI}
		tar -xjf ${PRECOMPILED_N}
	fi
}
addtask download_precompiled_binary after do_compile before do_install

do_install() {
	install -d ${D}/${bindir}
	install -m 755 ${S}/src/projectx ${D}/${bindir}/
}

gha_language: C


text:
#DEFAULT_PREFERENCE = "-1"

require cacao-native.inc

PR = "r0"

S = "${WORKDIR}/cacao"

CXXFLAGS += "-O1"

REV = "8948a434c10d"
SRC_URI = "hg://mips.complang.tuwien.ac.at/hg/;module=cacao;rev=${REV}"

repository: trini/openembedded

repo_name: trini/openembedded


text:
package s2s

import (
	"context"
	"fmt"
	"sync"
	"sync/atomic"
	"time"

	streamerror "github.com/dantin/cubit/errors"
	"github.com/dantin/cubit/log"
	"github.com/dantin/cubit/router/host"
	"github.com/dantin/cubit/session"
	"github.com/dantin/cubit/transport"
	"github.com/dantin/cubit/util/runqueue"
	"github.com/dantin/cubit/xmpp"
	"github.com/dantin/cubit/xmpp/jid"
)

const (
	outConnecting uint32 = iota
	outConnected
	outSecuring
	outAuthenticating
	outValidatingDialbackKey
	outAuthorizingDialbackKey
	outVerified
	outDisconnected
)

type outStream struct {
	id            string
	cfg           *outConfig
	runQueue      *runqueue.RunQueue
	hosts         *host.Hosts
	dialer        Dialer
	state         uint32
	tr            transport.Transport
	mu            sync.RWMutex
	sess          *session.Session
	readTimeoutTm *time.Timer
	secured       uint32
	authenticated uint32
	pendingSendQ  []xmpp.XElement
	dbVerify      xmpp.XElement
	verifyCh      chan bool
	discCh        chan *streamerror.Error
}

func newOutStream(cfg *outConfig, hosts *host.Hosts, dialer Dialer) *outStream {
	id := nextOutID()
	return &outStream{
		id:       id,
		cfg:      cfg,
		hosts:    hosts,
		dialer:   dialer,
		state:    outDisconnected,
		discCh:   make(chan *streamerror.Error),
		runQueue: runqueue.New(id),
	}
}

func (s *outStream) ID() string {
	return s.cfg.localDomain + ":" + s.cfg.remoteDomain
}

func (s *outStream) SendElement(ctx context.Context, elem xmpp.XElement) {
	s.runQueue.Run(func() {
		s.sendElement(ctx, elem)
	})
}

func (s *outStream) Disconnect(ctx context.Context, err error) {
	waitCh := make(chan struct{})
	s.runQueue.Stop(func() {
		defer close(waitCh)
		if s.getState() == outDisconnected {
			return
		}
		s.disconnect(ctx, err)
	})
	<-waitCh
}

func (s *outStream) sendElement(ctx context.Context, elem xmpp.XElement) {
	switch s.getState() {
	case outVerified:
		s.writeElement(ctx, elem)
	case outDisconnected:
		if err := s.start(ctx); err != nil {
			log.Error(err)
			return
		}
		fallthrough
	default:
		// send element after verification has been completed
		s.pendingSendQ = append(s.pendingSendQ, elem)
		return
	}
}

func (s *outStream) verify(ctx context.Context, streamID, from, to, key string) <-chan bool {
	verifyCh := make(chan bool, 1)
	s.runQueue.Run(func() {
		dbVerify := xmpp.NewElementName("db:verify")
		dbVerify.SetID(streamID)
		dbVerify.SetFrom(from)
		dbVerify.SetTo(to)
		dbVerify.SetText(key)

		s.dbVerify = dbVerify
		s.verifyCh = verifyCh

		if err := s.start(ctx); err != nil {
			log.Error(err)
			return
		}
	})
	return verifyCh
}

func (s *outStream) done() <-chan *streamerror.Error { return s.discCh }

// runs on its own goroutine
func (s *outStream) doRead() {
	s.scheduleReadTimeout()
	elem, sErr := s.sess.Receive()
	s.cancelReadTimeout()

	//ctx, _ := context.WithTimeout(context.Background(), s.cfg.timeout)
	ctx := context.TODO()
	if sErr == nil {
		s.runQueue.Run(func() { s.readElement(ctx, elem) })
	} else {
		s.runQueue.Run(func() {
			if s.getState() == outDisconnected {
				return // already disconnected...
			}
			log.Infof("s2s out stream disconnected... (domainpair: %s)", s.ID())

			s.handleSessionError(ctx, sErr)
		})
	}
}

func (s *outStream) dial(ctx context.Context) error {
	conn, err := s.dialer.Dial(ctx, s.cfg.remoteDomain)
	if err != nil {
		return err
	}
	s.tr = transport.NewSocketTransport(conn)
	return nil
}

func (s *outStream) start(ctx context.Context) error {
	if err := s.dial(ctx); err != nil {
		return err
	}
	s.restartSession()

	_ = s.sess.Open(ctx, nil)

	go s.doRead() // start reading transport...

	return nil
}

func (s *outStream) handleElement(ctx context.Context, elem xmpp.XElement) {
	switch s.getState() {
	case outConnecting:
		s.handleConnecting()
	case outConnected:
		s.handleConnected(ctx, elem)
	case outSecuring:
		s.handleSecuring(ctx, elem)
	case outAuthenticating:
		s.handleAuthenticating(ctx, elem)
	case outValidatingDialbackKey:
		s.handleValidatingDialbackKey(ctx, elem)
	case outAuthorizingDialbackKey:
		s.handleAuthorizingDialbackKey(ctx, elem)
	}
}

func (s *outStream) handleConnecting() {
	s.setState(outConnected)
}

func (s *outStream) handleConnected(ctx context.Context, elem xmpp.XElement) {
	if elem.Name() != "stream:features" {
		s.disconnectWithStreamError(ctx, streamerror.ErrUnsupportedStanzaType)
		return
	}
	if !s.isSecured() {
		if elem.Elements().ChildrenNamespace("starttls", tlsNamespace) == nil {
			// unsecured channels not supported
			s.disconnectWithStreamError(ctx, streamerror.ErrPolicyViolation)
			return
		}
		s.setState(outSecuring)
		s.writeElement(ctx, xmpp.NewElementNamespace("starttls", tlsNamespace))
	} else {
		// authorize dialback key
		if s.dbVerify != nil {
			s.setState(outAuthorizingDialbackKey)
			s.writeElement(ctx, s.dbVerify)
			return
		}
		if !s.isAuthenticated() {
			var hasExternalAuth bool
			if mechanisms := elem.Elements().ChildNamespace("mechanisms", saslNamespace); mechanisms != nil {
				for _, m := range mechanisms.Elements().All() {
					if m.Name() == "mechanism" && m.Text() == "EXTERNAL" {
						hasExternalAuth = true
						break
					}
				}
			}
			if hasExternalAuth {
				s.setState(outAuthenticating)
				auth := xmpp.NewElementNamespace("auth", saslNamespace)
				auth.SetAttribute("mechanism", "EXTERNAL")
				auth.SetText("=")
				s.writeElement(ctx, auth)
			} else if elem.Elements().ChildrenNamespace("dialback", dialbackNamespace) != nil {
				s.setState(outValidatingDialbackKey)
				db := xmpp.NewElementName("db:result")
				db.SetFrom(s.cfg.localDomain)
				db.SetTo(s.cfg.remoteDomain)
				db.SetText(s.cfg.keyGen.generate(s.cfg.remoteDomain, s.cfg.localDomain, s.sess.StreamID()))
				s.writeElement(ctx, db)
			} else {
				// no verification mechanism found... do not allow remote connection
				s.disconnectWithStreamError(ctx, streamerror.ErrRemoteConnectionFailed)
			}
		} else {
			s.finishVerification(ctx)
		}
	}
}

func (s *outStream) handleSecuring(ctx context.Context, elem xmpp.XElement) {
	if elem.Name() != "proceed" {
		s.disconnectWithStreamError(ctx, streamerror.ErrUnsupportedStanzaType)
		return
	} else if elem.Namespace() != tlsNamespace {
		s.disconnectWithStreamError(ctx, streamerror.ErrInvalidNamespace)
		return
	}
	s.tr.StartTLS(s.cfg.tls, true)

	atomic.StoreUint32(&s.secured, 1)
	s.restartSession()

	_ = s.sess.Open(ctx, nil)
}

func (s *outStream) handleAuthenticating(ctx context.Context, elem xmpp.XElement) {
	if elem.Namespace() != saslNamespace {
		s.disconnectWithStreamError(ctx, streamerror.ErrInvalidNamespace)
		return
	}
	switch elem.Name() {
	case "success":
		atomic.StoreUint32(&s.authenticated, 1)
		s.restartSession()
		_ = s.sess.Open(ctx, nil)

	case "failure":
		s.disconnectWithStreamError(ctx, streamerror.ErrRemoteConnectionFailed)

	default:
		s.disconnectWithStreamError(ctx, streamerror.ErrUnsupportedStanzaType)
	}
}

func (s *outStream) handleValidatingDialbackKey(ctx context.Context, elem xmpp.XElement) {
	switch elem.Name() {
	case "db:result":
		if elem.From() != s.cfg.remoteDomain {
			s.disconnectWithStreamError(ctx, streamerror.ErrInvalidFrom)
			return
		}
		switch elem.Type() {
		case "valid":
			log.Infof("s2s out stream successfully validated... (domainpair: %s)", s.ID())
			s.finishVerification(ctx)

		default:
			log.Infof("failed s2s out stream validation... (domainpair: %s)", s.ID())
			s.disconnectWithStreamError(ctx, streamerror.ErrRemoteConnectionFailed)
		}
	}
}

func (s *outStream) handleAuthorizingDialbackKey(ctx context.Context, elem xmpp.XElement) {
	switch elem.Name() {
	case "db:verify":
		s.verifyCh <- elem.Type() == "valid"

	default:
		s.disconnectWithStreamError(ctx, streamerror.ErrUnsupportedStanzaType)
	}
}

func (s *outStream) finishVerification(ctx context.Context) {
	s.setState(outVerified)

	// send pending elements...
	for _, el := range s.pendingSendQ {
		s.writeElement(ctx, el)
	}
	s.pendingSendQ = nil
}

func (s *outStream) writeStanzaErrorResponse(ctx context.Context, elem xmpp.XElement, stanzaErr *xmpp.StanzaError) {
	resp := xmpp.NewElementFromElement(elem)
	resp.SetType(xmpp.ErrorType)
	resp.SetFrom(elem.To())
	resp.SetTo(elem.From())
	resp.AppendElement(stanzaErr.Element())
	s.writeElement(ctx, resp)
}

func (s *outStream) writeElement(ctx context.Context, elem xmpp.XElement) {
	if err := s.sess.Send(ctx, elem); err != nil {
		log.Error(err)
	}
}

func (s *outStream) readElement(ctx context.Context, elem xmpp.XElement) {
	if elem != nil {
		s.handleElement(ctx, elem)
	}
	if s.getState() != outDisconnected {
		go s.doRead()
	}
}

func (s *outStream) handleSessionError(ctx context.Context, sErr *session.Error) {
	switch err := sErr.UnderlyingErr.(type) {
	case nil:
		s.disconnect(ctx, nil)
	case *streamerror.Error:
		s.disconnectWithStreamError(ctx, err)
	case *xmpp.StanzaError:
		s.writeStanzaErrorResponse(ctx, sErr.Element, err)
	default:
		log.Error(err)
		s.disconnectWithStreamError(ctx, streamerror.ErrUndefinedCondition)
	}
}

func (s *outStream) disconnect(ctx context.Context, err error) {
	switch err {
	case nil:
		s.disconnectClosingSession(ctx, false)
	default:
		if stmErr, ok := err.(*streamerror.Error); ok {
			s.disconnectWithStreamError(ctx, stmErr)
		} else {
			log.Error(err)
			s.disconnectClosingSession(ctx, false)
		}
	}
}

func (s *outStream) disconnectWithStreamError(ctx context.Context, err *streamerror.Error) {
	// notify disconnection
	select {
	case s.discCh <- err:
		break
	default:
		break
	}
	s.writeElement(ctx, err.Element())
	s.disconnectClosingSession(ctx, true)
}

func (s *outStream) disconnectClosingSession(ctx context.Context, closeSession bool) {
	if closeSession {
		_ = s.sess.Close(ctx)
	}
	atomic.StoreUint32(&s.secured, 0)
	atomic.StoreUint32(&s.authenticated, 0)

	s.setState(outDisconnected)
	_ = s.tr.Close()
}

func (s *outStream) restartSession() {
	j, _ := jid.New("", s.cfg.localDomain, "", true)
	s.sess = session.New(s.id, &session.Config{
		JID:           j,
		MaxStanzaSize: s.cfg.maxStanzaSize,
		RemoteDomain:  s.cfg.remoteDomain,
		IsServer:      true,
		IsInitiating:  true,
	}, s.tr, s.hosts)
	s.setState(outConnecting)
}

func (s *outStream) scheduleReadTimeout() {
	s.mu.Lock()
	s.readTimeoutTm = time.AfterFunc(s.cfg.keepAlive, s.readTimeout)
	s.mu.Unlock()
}

func (s *outStream) cancelReadTimeout() {
	s.mu.Lock()
	s.readTimeoutTm.Stop()
	s.mu.Unlock()
}

func (s *outStream) readTimeout() {
	s.runQueue.Run(func() {
		//ctx, _ := context.WithTimeout(context.Background(), s.cfg.timeout)
		ctx := context.TODO()
		s.disconnect(ctx, streamerror.ErrConnectionTimeout)
	})
}

func (s *outStream) isSecured() bool {
	return atomic.LoadUint32(&s.secured) == 1
}

func (s *outStream) isAuthenticated() bool {
	return atomic.LoadUint32(&s.authenticated) == 1
}

func (s *outStream) setState(state uint32) {
	atomic.StoreUint32(&s.state, state)
}

func (s *outStream) getState() uint32 {
	return atomic.LoadUint32(&s.state)
}

var outStreamCounter uint64

func nextOutID() string {
	return fmt.Sprintf("s2s:out:%d", atomic.AddUint64(&outStreamCounter, 1))
}

repository: dantin/cubit

repo_name: dantin/cubit


text:
// Copyright (c) 2017-2020 The Elastos Foundation
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
//

package manager

import (
	"bytes"
	"errors"

	"github.com/elastos/Elastos.ELA/blockchain"
	"github.com/elastos/Elastos.ELA/common"
	"github.com/elastos/Elastos.ELA/common/config"
	"github.com/elastos/Elastos.ELA/core/contract"
	"github.com/elastos/Elastos.ELA/core/contract/program"
	"github.com/elastos/Elastos.ELA/core/types"
	"github.com/elastos/Elastos.ELA/core/types/payload"
	"github.com/elastos/Elastos.ELA/crypto"
	"github.com/elastos/Elastos.ELA/dpos/account"
	"github.com/elastos/Elastos.ELA/dpos/dtime"
	"github.com/elastos/Elastos.ELA/dpos/log"
	dmsg "github.com/elastos/Elastos.ELA/dpos/p2p/msg"
	"github.com/elastos/Elastos.ELA/dpos/p2p/peer"
	"github.com/elastos/Elastos.ELA/dpos/state"
)

type ProposalDispatcherConfig struct {
	EventAnalyzerConfig
	EventMonitor *log.EventMonitor
	Consensus    *Consensus
	Network      DPOSNetwork
	Manager      *DPOSManager
	Account      account.Account
	ChainParams  *config.Params
	TimeSource   dtime.MedianTimeSource
}

type ProposalDispatcher struct {
	cfg ProposalDispatcherConfig

	finishedHeight      uint32
	finishedBlockHash   common.Uint256
	processingBlock     *types.Block
	processingProposal  *payload.DPOSProposal
	acceptVotes         map[common.Uint256]*payload.DPOSProposalVote
	rejectedVotes       map[common.Uint256]*payload.DPOSProposalVote
	pendingProposals    map[common.Uint256]*payload.DPOSProposal
	precociousProposals map[common.Uint256]*payload.DPOSProposal
	pendingVotes        map[common.Uint256]*payload.DPOSProposalVote

	proposalProcessFinished bool
	crcBadNetwork           bool
	firstBadNetworkRecover  bool

	inactiveCountDown           ViewChangesCountDown
	currentInactiveArbitratorTx *types.Transaction
	signedTxs                   map[common.Uint256]interface{}

	eventAnalyzer  *eventAnalyzer
	illegalMonitor *IllegalBehaviorMonitor
}

func (p *ProposalDispatcher) RequestAbnormalRecovering() {
	height := blockchain.DefaultLedger.Blockchain.GetHeight()
	msgItem := &dmsg.RequestConsensus{Height: height}
	log.Info("[RequestAbnormalRecovering] broadcast message to peers")
	p.cfg.Network.BroadcastMessage(msgItem)
}

func (p *ProposalDispatcher) GetProcessingBlock() *types.Block {
	return p.processingBlock
}

func (p *ProposalDispatcher) GetFinishedHeight() uint32 {
	return p.finishedHeight
}

func (p *ProposalDispatcher) GetProcessingProposal() *payload.DPOSProposal {
	return p.processingProposal
}

func (p *ProposalDispatcher) GetFinishedBlockHash() common.Uint256 {
	return p.finishedBlockHash
}

func (p *ProposalDispatcher) ProcessVote(v *payload.DPOSProposalVote,
	accept bool) (succeed bool, finished bool) {
	log.Info("[ProcessVote] start")
	defer log.Info("[ProcessVote] end")

	if err := blockchain.VoteCheck(v); err != nil {
		log.Warn("Invalid vote: ", err.Error())
		return false, false
	}

	if p.alreadyExistVote(v) {
		log.Info("Already has vote")
		return false, false
	}

	if anotherVote, legal := p.illegalMonitor.IsLegalVote(v); !legal {
		p.illegalMonitor.ProcessIllegalVote(v, anotherVote)
		return
	}

	if accept {
		return p.countAcceptedVote(v)
	} else {
		return p.countRejectedVote(v)
	}
}

func (p *ProposalDispatcher) AddPendingVote(v *payload.DPOSProposalVote) {
	p.pendingVotes[v.Hash()] = v
}

func (p *ProposalDispatcher) StartProposal(b *types.Block) {
	log.Info("[StartProposal] start")
	defer log.Info("[StartProposal] end")

	if p.processingBlock != nil {
		log.Info("[StartProposal] start proposal failed")
		return
	}
	p.processingBlock = b

	//p.cfg.Network.BroadcastMessage(dmsg.NewInventory(b.Hash()))
	proposal := &payload.DPOSProposal{Sponsor: p.cfg.Manager.GetPublicKey(),
		BlockHash: b.Hash(), ViewOffset: p.cfg.Consensus.GetViewOffset()}
	var err error
	proposal.Sign, err = p.cfg.Account.SignProposal(proposal)
	if err != nil {
		log.Error("[StartProposal] start proposal failed:", err.Error())
		return
	}

	log.Info("[StartProposal] sponsor:", p.cfg.Manager.GetPublicKey())

	m := &dmsg.Proposal{
		Proposal: *proposal,
	}

	log.Info("[StartProposal] send proposal message finished, Proposal Hash: ", dmsg.GetMessageHash(m))
	p.cfg.Network.BroadcastMessage(m)

	proposalEvent := log.ProposalEvent{
		Sponsor:      common.BytesToHexString(proposal.Sponsor),
		BlockHash:    proposal.BlockHash,
		ReceivedTime: p.cfg.TimeSource.AdjustedTime(),
		ProposalHash: proposal.Hash(),
		RawData:      proposal,
		Result:       false,
	}
	p.cfg.EventMonitor.OnProposalArrived(&proposalEvent)
	p.acceptProposal(proposal)
}

func (p *ProposalDispatcher) TryStartSpeculatingProposal(b *types.Block) {
	log.Info("[TryStartSpeculatingProposal] start")
	defer log.Info("[TryStartSpeculatingProposal] end")

	if p.processingBlock != nil {
		log.Warn("[TryStartSpeculatingProposal] processingBlock is not nil")
		return
	}
	p.processingBlock = b
}

func (p *ProposalDispatcher) FinishProposal() bool {
	log.Info("[FinishProposal] start")
	defer log.Info("[FinishProposal] end")

	if p.processingBlock == nil {
		log.Warn("[FinishProposal] nil processing block")
		return false
	}

	proposal, blockHash := p.processingProposal.Sponsor, p.processingBlock.Hash()

	p.AppendConfirm()

	proposalEvent := log.ProposalEvent{
		Sponsor:   common.BytesToHexString(proposal),
		BlockHash: blockHash,
		EndTime:   p.cfg.TimeSource.AdjustedTime(),
		Result:    true,
	}
	p.cfg.EventMonitor.OnProposalFinished(&proposalEvent)
	p.FinishConsensus(p.processingBlock.Height, p.processingBlock.Hash())

	return true
}

func (p *ProposalDispatcher) CleanProposals(changeView bool) {
	log.Info("Clean proposals")

	p.illegalMonitor.Reset(changeView)

	p.processingBlock = nil
	p.processingProposal = nil
	p.acceptVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	p.rejectedVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	p.pendingVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	p.proposalProcessFinished = false
	if !changeView {
		p.inactiveCountDown.Reset(0)
		p.currentInactiveArbitratorTx = nil
		p.signedTxs = map[common.Uint256]interface{}{}
		p.pendingProposals = make(map[common.Uint256]*payload.DPOSProposal)
		p.precociousProposals = make(map[common.Uint256]*payload.DPOSProposal)

		p.eventAnalyzer.Clear()
	} else {
		// clear pending proposals less than current view offset
		currentOffset := p.cfg.Consensus.GetViewOffset()
		for k, v := range p.pendingProposals {
			if v.ViewOffset < currentOffset {
				delete(p.pendingProposals, k)
			}
		}
		for k, v := range p.precociousProposals {
			if v.ViewOffset < currentOffset {
				delete(p.precociousProposals, k)
			}
		}
	}
}

func (p *ProposalDispatcher) ResetByCurrentView() {
	p.illegalMonitor.Reset(false)

	p.processingBlock = nil
	p.processingProposal = nil
	p.acceptVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	p.rejectedVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	p.pendingVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	p.proposalProcessFinished = false

	p.inactiveCountDown.Reset(p.cfg.Consensus.GetViewOffset() + 1)
	p.currentInactiveArbitratorTx = nil
	p.signedTxs = map[common.Uint256]interface{}{}
	p.pendingProposals = make(map[common.Uint256]*payload.DPOSProposal)
	p.precociousProposals = make(map[common.Uint256]*payload.DPOSProposal)

	p.eventAnalyzer.Clear()

}

func (p *ProposalDispatcher) ProcessProposal(id peer.PID, d *payload.DPOSProposal,
	force bool) (needRecord bool, handled bool) {
	log.Info("[ProcessProposal] start")
	defer log.Info("[ProcessProposal] end")

	self := bytes.Equal(id[:], d.Sponsor)
	if err := blockchain.ProposalCheck(d); err != nil {
		log.Warn("invalid proposal: ", err.Error())
		return false, true
	}

	if p.IsViewChangedTimeOut() {
		log.Info("enter emergency state, proposal will be discard")
		return true, !self
	}

	if p.processingProposal != nil && d.Hash().IsEqual(
		p.processingProposal.Hash()) {
		log.Info("already processing proposal")
		return true, true
	}

	if _, err := blockchain.DefaultLedger.Blockchain.GetBlockByHash(d.BlockHash); err == nil {
		log.Info("already exist block in block chain")
		return true, true
	}

	if d.BlockHash.IsEqual(p.finishedBlockHash) {
		log.Info("already processed block")
		return true, true
	}

	if d.ViewOffset != p.cfg.Consensus.GetViewOffset() {
		log.Info("have different view offset")
		if d.ViewOffset > p.cfg.Consensus.GetViewOffset() {
			p.precociousProposals[d.Hash()] = d
		}
		return true, !self
	}

	if !force {
		if _, ok := p.pendingProposals[d.Hash()]; ok {
			log.Info("already have proposal, wait for processing")
			return true, true
		}
	}

	if anotherProposal, ok := p.illegalMonitor.IsLegalProposal(d); !ok {
		p.illegalMonitor.ProcessIllegalProposal(d, anotherProposal)
		return true, true
	}

	if !p.cfg.Consensus.IsArbitratorOnDuty(d.Sponsor) {
		currentArbiter := p.cfg.Manager.GetArbitrators().GetNextOnDutyArbitrator(p.cfg.Consensus.GetViewOffset())
		log.Info("viewOffset:", p.cfg.Consensus.GetViewOffset(), "current arbiter:",
			common.BytesToHexString(currentArbiter), "sponsor:", d.Sponsor)
		p.rejectProposal(d)
		log.Warn("reject: current arbiter is not sponsor")
		return true, !self
	}

	currentBlock, ok := p.cfg.Manager.GetBlockCache().TryGetValue(d.BlockHash)
	if !ok || !p.cfg.Consensus.IsRunning() {
		p.pendingProposals[d.Hash()] = d
		p.cfg.Manager.OnInv(id, d.BlockHash)
		log.Info("received pending proposal")
		return true, true
	} else {
		p.TryStartSpeculatingProposal(currentBlock)
	}

	if currentBlock.Height != p.processingBlock.Height {
		log.Warn("[ProcessProposal] Invalid block height")
		return true, !self
	}

	if !d.BlockHash.IsEqual(p.processingBlock.Hash()) {
		log.Warn("[ProcessProposal] Invalid block hash")
		return true, !self
	}

	if !p.proposalProcessFinished {
		p.acceptProposal(d)
	}

	return true, true
}

func (p *ProposalDispatcher) AppendConfirm() {
	currentVoteSlot := &payload.Confirm{
		Proposal: *p.processingProposal,
		Votes:    make([]payload.DPOSProposalVote, 0),
	}
	for _, v := range p.acceptVotes {
		currentVoteSlot.Votes = append(currentVoteSlot.Votes, *v)
	}

	log.Info("[AppendConfirm] append confirm.")
	go func() {
		if _, _, err := p.cfg.Manager.AppendConfirm(
			currentVoteSlot); err != nil {
			log.Warn("[AppendConfirm] append failed: ", err)
		}
	}()
}

func (p *ProposalDispatcher) OnBlockAdded(b *types.Block) {
	for k, v := range p.pendingProposals {
		if p.cfg.Consensus.IsRunning() && v.BlockHash.IsEqual(b.Hash()) {
			// block is already exist, will not use PID, given PID{} is ok
			if needRecord, _ := p.ProcessProposal(
				peer.PID{}, v, true); needRecord {
				p.illegalMonitor.AddProposal(v)
			}
			delete(p.pendingProposals, k)
		}
	}
}

func (p *ProposalDispatcher) UpdatePrecociousProposals() {
	for k, v := range p.precociousProposals {
		if p.cfg.Consensus.IsRunning() &&
			v.ViewOffset == p.cfg.Consensus.GetViewOffset() {
			if needRecord, _ := p.ProcessProposal(
				peer.PID{}, v, true); needRecord {
				p.illegalMonitor.AddProposal(v)
			}
			delete(p.precociousProposals, k)
		}
	}
}

func (p *ProposalDispatcher) FinishConsensus(height uint32, blockHash common.Uint256) {
	if p.cfg.Consensus.IsRunning() {
		log.Info("[FinishConsensus] start")
		defer log.Info("[FinishConsensus] end")

		p.finishedHeight = height
		p.finishedBlockHash = blockHash
		p.cfg.Manager.changeOnDuty()
		c := log.ConsensusEvent{EndTime: p.cfg.TimeSource.AdjustedTime(), Height: height}
		p.cfg.EventMonitor.OnConsensusFinished(&c)
		p.cfg.Consensus.SetReady()
		p.CleanProposals(false)
	}
}

func (p *ProposalDispatcher) CollectConsensusStatus(status *dmsg.ConsensusStatus) error {
	status.AcceptVotes = make([]payload.DPOSProposalVote, 0, len(p.acceptVotes))
	for _, v := range p.acceptVotes {
		status.AcceptVotes = append(status.AcceptVotes, *v)
	}

	status.RejectedVotes = make([]payload.DPOSProposalVote, 0, len(p.rejectedVotes))
	for _, v := range p.rejectedVotes {
		status.RejectedVotes = append(status.RejectedVotes, *v)
	}

	status.PendingProposals = make([]payload.DPOSProposal, 0, len(p.pendingProposals))
	for _, v := range p.pendingProposals {
		status.PendingProposals = append(status.PendingProposals, *v)
	}

	status.PendingVotes = make([]payload.DPOSProposalVote, 0, len(p.pendingVotes))
	for _, v := range p.pendingVotes {
		status.PendingVotes = append(status.PendingVotes, *v)
	}

	return nil
}

func (p *ProposalDispatcher) RecoverFromConsensusStatus(status *dmsg.ConsensusStatus) error {
	p.acceptVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	for _, v := range status.AcceptVotes {
		vote := v
		p.acceptVotes[v.Hash()] = &vote
	}

	p.rejectedVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	for _, v := range status.RejectedVotes {
		vote := v
		p.rejectedVotes[v.Hash()] = &vote
	}

	p.pendingProposals = make(map[common.Uint256]*payload.DPOSProposal)
	for _, v := range status.PendingProposals {
		vote := v
		p.pendingProposals[v.Hash()] = &vote
	}

	p.pendingVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	for _, v := range status.PendingVotes {
		vote := v
		p.pendingVotes[v.Hash()] = &vote
	}

	if status.ConsensusStatus == consensusReady {
		p.processingBlock = nil
	}
	return nil
}

func (p *ProposalDispatcher) IsCRCBadNetWork() bool {
	peers := p.cfg.Network.GetActivePeers()
	var count int
	for _, v := range peers {
		pid := v.PID()
		if p.cfg.Arbitrators.IsCRCArbitrator(pid[:]) {
			count++
		}
	}
	return count <= p.cfg.Arbitrators.GetCRCArbitersCount()*2/3
}

func (p *ProposalDispatcher) IsViewChangedTimeOut() bool {
	return false
	if p.crcBadNetwork {
		if !p.IsCRCBadNetWork() {
			p.crcBadNetwork = false
			if p.firstBadNetworkRecover {
				p.firstBadNetworkRecover = false
				return false
			}
			p.ResetByCurrentView()
		}
		return false
	}

	if p.IsCRCBadNetWork() {
		p.crcBadNetwork = true
		return false
	}

	return p.inactiveCountDown.IsTimeOut()
}

func (p *ProposalDispatcher) OnIllegalBlocksTxReceived(i *payload.DPOSIllegalBlocks) {
	p.inactiveCountDown.SetEliminated(i.Hash())
}

func (p *ProposalDispatcher) OnInactiveArbitratorsReceived(id peer.PID,
	tx *types.Transaction) {
	if _, ok := p.signedTxs[tx.Hash()]; ok {
		log.Warn("[OnInactiveArbitratorsReceived] already processed")
		return
	}

	log.Info("[OnInactiveArbitratorsReceived] received inactive tx")

	if !p.IsViewChangedTimeOut() {
		log.Warn("[OnInactiveArbitratorsReceived] received inactive" +
			" arbitrators transaction when normal view changing")
		return
	}

	inactivePayload := tx.Payload.(*payload.InactiveArbitrators)
	if len(inactivePayload.Arbitrators) == 0 {
		log.Warn("[OnInactiveArbitratorsReceived] received empty payload")
		return
	}
	if err := p.checkInactivePayloadContent(inactivePayload); err != nil {
		log.Warn("[OnInactiveArbitratorsReceived] error: ", err)
		return
	}

	p.signedTxs[tx.Hash()] = nil

	response := &dmsg.ResponseInactiveArbitrators{
		TxHash: tx.Hash(),
		Signer: p.cfg.Manager.GetPublicKey(),
	}
	var err error
	if response.Sign, err = p.cfg.Account.SignTx(tx); err != nil {
		log.Warn("[OnInactiveArbitratorsReceived] sign response message"+
			" error, details: ", err.Error())
	}
	go func() {
		if err := p.cfg.Network.SendMessageToPeer(id, response); err != nil {
			log.Warn("[OnInactiveArbitratorsReceived] send msg error: ", err)
		}
	}()

	log.Info("[OnInactiveArbitratorsReceived] response inactive tx sign")
}

func (p *ProposalDispatcher) checkInactivePayloadContent(
	inactivePayload *payload.InactiveArbitrators) error {
	// todo pass this check for now
	return nil

	inactiveArbitratorsMap := make(map[string]interface{})
	for _, v := range p.eventAnalyzer.ParseInactiveArbitrators() {
		inactiveArbitratorsMap[v] = nil
	}
	if len(inactivePayload.Arbitrators) != len(inactiveArbitratorsMap) {
		return errors.New("received inactive arbitrators transaction " +
			"with wrong arbitrators count")
	}
	for _, v := range inactivePayload.Arbitrators {
		if _, exist := inactiveArbitratorsMap[common.BytesToHexString(
			v)]; !exist {
			return errors.New("disagree with inactive arbitrators")
		}
	}
	return nil
}

func (p *ProposalDispatcher) OnResponseInactiveArbitratorsReceived(
	txHash *common.Uint256, signer []byte, sign []byte) {
	log.Info("[OnResponseInactiveArbitratorsReceived] collect transaction" +
		" signs")

	if p.currentInactiveArbitratorTx == nil ||
		!p.currentInactiveArbitratorTx.Hash().IsEqual(*txHash) {
		log.Warn("[OnResponseInactiveArbitratorsReceived] unknown " +
			"inactive arbitrators transaction")
		return
	}

	data := new(bytes.Buffer)
	if err := p.currentInactiveArbitratorTx.SerializeUnsigned(
		data); err != nil {
		log.Warn("[OnResponseInactiveArbitratorsReceived] transaction "+
			"serialize error, details: ", err)
		return
	}

	pk, err := crypto.DecodePoint(signer)
	if err != nil {
		log.Warn("[OnResponseInactiveArbitratorsReceived] decode signer "+
			"error, details: ", err)
		return
	}

	if err := crypto.Verify(*pk, data.Bytes(), sign); err != nil {
		log.Warn("[OnResponseInactiveArbitratorsReceived] sign verify "+
			"error, details: ", err)
		return
	}

	pro := p.currentInactiveArbitratorTx.Programs[0]
	buf := new(bytes.Buffer)
	buf.Write(pro.Parameter)
	buf.WriteByte(byte(len(sign)))
	buf.Write(sign)
	pro.Parameter = buf.Bytes()

	p.tryEnterEmergencyState(len(pro.Parameter) / crypto.SignatureScriptLength)
}

func (p *ProposalDispatcher) tryEnterEmergencyState(signCount int) bool {
	log.Info("[tryEnterEmergencyState] current sign count: ", signCount)

	minSignCount := int(float64(len(p.cfg.Arbitrators.GetCRCArbiters()))*
		state.MajoritySignRatioNumerator/state.MajoritySignRatioDenominator) + 1
	if signCount >= minSignCount {
		payload := p.currentInactiveArbitratorTx.Payload.(*payload.InactiveArbitrators)
		p.illegalMonitor.AddEvidence(payload)
		p.cfg.Manager.AppendToTxnPool(p.currentInactiveArbitratorTx)

		if err := p.cfg.Arbitrators.ProcessSpecialTxPayload(
			p.currentInactiveArbitratorTx.Payload,
			blockchain.DefaultLedger.Blockchain.GetHeight()); err != nil {
			log.Error("[tryEnterEmergencyState] force change arbitrators"+
				" error: ", err.Error())
			return false
		}
		p.cfg.Manager.clearInactiveData(payload)

		log.Info("[tryEnterEmergencyState] successfully entered emergency"+
			" state ", payload.Hash())
		return true
	}

	return false
}

func (p *ProposalDispatcher) alreadyExistVote(v *payload.DPOSProposalVote) bool {
	_, ok := p.acceptVotes[v.Hash()]
	if ok {
		log.Info("[alreadyExistVote]: ", v.Signer, "already in the AcceptVotes!")
		return true
	}

	_, ok = p.rejectedVotes[v.Hash()]
	if ok {
		log.Info("[alreadyExistVote]: ", v.Signer, "already in the RejectedVotes!")
		return true
	}

	return false
}

func (p *ProposalDispatcher) countAcceptedVote(v *payload.DPOSProposalVote) (
	succeed bool, finished bool) {
	log.Info("[countAcceptedVote] start")
	defer log.Info("[countAcceptedVote] end")

	if v.Accept {
		log.Info("[countAcceptedVote] Received needed sign, collect it into AcceptVotes!")
		p.acceptVotes[v.Hash()] = v

		if p.cfg.Manager.GetArbitrators().HasArbitersMajorityCount(len(p.acceptVotes)) {
			log.Info("Collect majority signs, finish proposal.")
			return true, p.FinishProposal()
		}
		return true, false
	}

	return false, false
}

func (p *ProposalDispatcher) countRejectedVote(v *payload.DPOSProposalVote) (
	succeed bool, finished bool) {
	log.Info("[countRejectedVote] start")
	defer log.Info("[countRejectedVote] end")

	if !v.Accept {
		log.Info("[countRejectedVote] Received invalid sign, collect it into RejectedVotes!")
		p.rejectedVotes[v.Hash()] = v

		if p.cfg.Manager.GetArbitrators().HasArbitersMinorityCount(len(p.rejectedVotes)) {
			p.CleanProposals(true)
			p.cfg.Consensus.ChangeView()
			return true, true
		}
		return true, false
	}

	return false, false
}

func (p *ProposalDispatcher) acceptProposal(d *payload.DPOSProposal) {
	log.Info("[acceptProposal] start")
	defer log.Info("[acceptProposal] end")

	if p.setProcessingProposal(d) {
		return
	}
	if !p.cfg.Manager.isCurrentArbiter() {
		return
	}

	vote := &payload.DPOSProposalVote{ProposalHash: d.Hash(),
		Signer: p.cfg.Manager.GetPublicKey(), Accept: true}
	var err error
	vote.Sign, err = p.cfg.Account.SignVote(vote)
	if err != nil {
		log.Error("[acceptProposal] sign failed")
		return
	}
	voteMsg := &dmsg.Vote{Command: dmsg.CmdAcceptVote, Vote: *vote}
	p.ProcessVote(vote, true)

	p.proposalProcessFinished = true
	p.cfg.Network.BroadcastMessage(voteMsg)
	log.Info("[acceptProposal] send acc_vote msg:", dmsg.GetMessageHash(voteMsg).String())

	voteEvent := log.VoteEvent{Signer: common.BytesToHexString(vote.Signer),
		ReceivedTime: p.cfg.TimeSource.AdjustedTime(), Result: true, RawData: vote}
	p.cfg.EventMonitor.OnVoteArrived(&voteEvent)
	p.eventAnalyzer.AppendConsensusVote(vote)
}

func (p *ProposalDispatcher) rejectProposal(d *payload.DPOSProposal) {
	if p.setProcessingProposal(d) {
		return
	}
	vote := &payload.DPOSProposalVote{ProposalHash: d.Hash(),
		Signer: p.cfg.Manager.GetPublicKey(), Accept: false}
	var err error
	vote.Sign, err = p.cfg.Account.SignVote(vote)
	if err != nil {
		log.Error("[rejectProposal] sign failed")
		return
	}
	msg := &dmsg.Vote{Command: dmsg.CmdRejectVote, Vote: *vote}
	log.Info("[rejectProposal] send rej_vote msg:", dmsg.GetMessageHash(msg))

	_, ok := p.cfg.Manager.GetBlockCache().TryGetValue(d.BlockHash)
	if !ok {
		log.Error("[rejectProposal] can't find block")
		return
	}
	p.ProcessVote(vote, false)
	p.cfg.Network.BroadcastMessage(msg)

	voteEvent := log.VoteEvent{Signer: common.BytesToHexString(vote.Signer),
		ReceivedTime: p.cfg.TimeSource.AdjustedTime(), Result: false, RawData: vote}
	p.cfg.EventMonitor.OnVoteArrived(&voteEvent)
	p.eventAnalyzer.AppendConsensusVote(vote)
}

func (p *ProposalDispatcher) setProcessingProposal(d *payload.DPOSProposal) (finished bool) {
	p.processingProposal = d

	for _, v := range p.pendingVotes {
		if v.ProposalHash.IsEqual(d.Hash()) {
			_, finished = p.ProcessVote(v, v.Accept)
			if finished {
				return
			}
		}
	}
	p.pendingVotes = make(map[common.Uint256]*payload.DPOSProposalVote)
	return false
}

func (p *ProposalDispatcher) CreateInactiveArbitrators() (
	*types.Transaction, error) {
	var err error

	inactivePayload := &payload.InactiveArbitrators{
		Sponsor:     p.cfg.Manager.GetPublicKey(),
		Arbitrators: [][]byte{},
		BlockHeight: blockchain.DefaultLedger.Blockchain.GetHeight() + 1,
	}
	inactiveArbitrators := p.eventAnalyzer.ParseInactiveArbitrators()
	for _, v := range inactiveArbitrators {
		var pk []byte
		pk, err = common.HexStringToBytes(v)
		if err != nil {
			return nil, err
		}
		inactivePayload.Arbitrators = append(inactivePayload.Arbitrators, pk)
	}
	if len(inactivePayload.Arbitrators) == 0 {
		return nil, errors.New("found no inactive arbiters")
	}

	con := contract.Contract{Prefix: contract.PrefixMultiSig}
	if con.Code, err = p.createArbitratorsRedeemScript(); err != nil {
		return nil, err
	}

	programHash := con.ToProgramHash()
	tx := &types.Transaction{
		Version:        types.TxVersion09,
		TxType:         types.InactiveArbitrators,
		PayloadVersion: payload.InactiveArbitratorsVersion,
		Payload:        inactivePayload,
		Attributes: []*types.Attribute{{
			Usage: types.Script,
			Data:  programHash.Bytes(),
		}},
		LockTime: 0,
		Outputs:  []*types.Output{},
		Inputs:   []*types.Input{},
		Fee:      0,
	}

	var sign []byte
	if sign, err = p.cfg.Account.SignTx(tx); err != nil {
		return nil, err
	}
	parameter := append([]byte{byte(len(sign))}, sign...)
	tx.Programs = []*program.Program{
		{
			Code:      con.Code,
			Parameter: parameter,
		},
	}

	p.currentInactiveArbitratorTx = tx
	return tx, nil
}

func (p *ProposalDispatcher) createArbitratorsRedeemScript() ([]byte, error) {
	var pks []*crypto.PublicKey
	for _, v := range p.cfg.Arbitrators.GetCRCArbiters() {
		pk, err := crypto.DecodePoint(v)
		if err != nil {
			return nil, err
		}
		pks = append(pks, pk)
	}

	arbitratorsCount := p.cfg.Arbitrators.GetCRCArbitersCount()
	minSignCount := int(float64(arbitratorsCount)*
		state.MajoritySignRatioNumerator/state.MajoritySignRatioDenominator) + 1
	return contract.CreateMultiSigRedeemScript(minSignCount, pks)
}

func NewDispatcherAndIllegalMonitor(cfg ProposalDispatcherConfig) (
	*ProposalDispatcher, *IllegalBehaviorMonitor) {
	p := &ProposalDispatcher{
		cfg:                    cfg,
		processingBlock:        nil,
		processingProposal:     nil,
		acceptVotes:            make(map[common.Uint256]*payload.DPOSProposalVote),
		rejectedVotes:          make(map[common.Uint256]*payload.DPOSProposalVote),
		pendingProposals:       make(map[common.Uint256]*payload.DPOSProposal),
		precociousProposals:    make(map[common.Uint256]*payload.DPOSProposal),
		pendingVotes:           make(map[common.Uint256]*payload.DPOSProposalVote),
		signedTxs:              make(map[common.Uint256]interface{}),
		firstBadNetworkRecover: true,
		eventAnalyzer: newEventStoreAnalyzer(EventAnalyzerConfig{
			Arbitrators: cfg.Arbitrators,
		}),
	}
	p.inactiveCountDown = ViewChangesCountDown{
		dispatcher:      p,
		consensus:       cfg.Consensus,
		arbitrators:     cfg.Arbitrators,
		timeoutRefactor: 0,
	}
	p.inactiveCountDown.Reset(0)

	i := &IllegalBehaviorMonitor{
		dispatcher:      p,
		cachedProposals: make(map[common.Uint256]*payload.DPOSProposal),
		evidenceCache: evidenceCache{
			make(map[common.Uint256]payload.DPOSIllegalData)},
		manager: cfg.Manager,
	}
	p.illegalMonitor = i
	return p, i
}

repository: elastos/Elastos

detected_licenses: MIT BSD-3-Clause ISC

repo_name: elastos/Elastos


text:
/*
 * Copyright (C) 2013, The Android Open Source Project
 *
 * 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.
 */

#ifndef LATINIME_PATRICIA_TRIE_POLICY_H
#define LATINIME_PATRICIA_TRIE_POLICY_H

#include <stdint.h>

#include "defines.h"
#include "suggest/core/policy/dictionary_structure_with_buffer_policy.h"
#include "suggest/policyimpl/dictionary/bigram/bigram_list_policy.h"
#include "suggest/policyimpl/dictionary/header/header_policy.h"
#include "suggest/policyimpl/dictionary/shortcut/shortcut_list_policy.h"
#include "suggest/policyimpl/dictionary/utils/mmapped_buffer.h"

namespace latinime {

class DicNode;
class DicNodeVector;

class PatriciaTriePolicy : public DictionaryStructureWithBufferPolicy {
 public:
    PatriciaTriePolicy(const MmappedBuffer *const buffer)
            : mBuffer(buffer), mHeaderPolicy(mBuffer->getBuffer(), buffer->getBufferSize()),
              mDictRoot(mBuffer->getBuffer() + mHeaderPolicy.getSize()),
              mDictBufferSize(mBuffer->getBufferSize() - mHeaderPolicy.getSize()),
              mBigramListPolicy(mDictRoot), mShortcutListPolicy(mDictRoot) {}

    ~PatriciaTriePolicy() {
        delete mBuffer;
    }

    AK_FORCE_INLINE int getRootPosition() const {
        return 0;
    }

    void createAndGetAllChildNodes(const DicNode *const dicNode,
            DicNodeVector *const childDicNodes) const;

    int getCodePointsAndProbabilityAndReturnCodePointCount(
            const int terminalNodePos, const int maxCodePointCount, int *const outCodePoints,
            int *const outUnigramProbability) const;

    int getTerminalNodePositionOfWord(const int *const inWord,
            const int length, const bool forceLowerCaseSearch) const;

    int getProbability(const int unigramProbability, const int bigramProbability) const;

    int getUnigramProbabilityOfPtNode(const int ptNodePos) const;

    int getShortcutPositionOfPtNode(const int ptNodePos) const;

    int getBigramsPositionOfPtNode(const int ptNodePos) const;

    const DictionaryHeaderStructurePolicy *getHeaderStructurePolicy() const {
        return &mHeaderPolicy;
    }

    const DictionaryBigramsStructurePolicy *getBigramsStructurePolicy() const {
        return &mBigramListPolicy;
    }

    const DictionaryShortcutsStructurePolicy *getShortcutsStructurePolicy() const {
        return &mShortcutListPolicy;
    }

    bool addUnigramWord(const int *const word, const int length, const int probability) {
        // This method should not be called for non-updatable dictionary.
        AKLOGI("Warning: addUnigramWord() is called for non-updatable dictionary.");
        return false;
    }

    bool addBigramWords(const int *const word0, const int length0, const int *const word1,
            const int length1, const int probability) {
        // This method should not be called for non-updatable dictionary.
        AKLOGI("Warning: addBigramWords() is called for non-updatable dictionary.");
        return false;
    }

    bool removeBigramWords(const int *const word0, const int length0, const int *const word1,
            const int length1) {
        // This method should not be called for non-updatable dictionary.
        AKLOGI("Warning: removeBigramWords() is called for non-updatable dictionary.");
        return false;
    }

    void flush(const char *const filePath) {
        // This method should not be called for non-updatable dictionary.
        AKLOGI("Warning: flush() is called for non-updatable dictionary.");
    }

    void flushWithGC(const char *const filePath) {
        // This method should not be called for non-updatable dictionary.
        AKLOGI("Warning: flushWithGC() is called for non-updatable dictionary.");
    }

    bool needsToRunGC(const bool mindsBlockByGC) const {
        // This method should not be called for non-updatable dictionary.
        AKLOGI("Warning: needsToRunGC() is called for non-updatable dictionary.");
        return false;
    }

    void getProperty(const char *const query, char *const outResult,
            const int maxResultLength) {
        // getProperty is not supported for this class.
        if (maxResultLength > 0) {
            outResult[0] = '\0';
        }
    }

 private:
    DISALLOW_IMPLICIT_CONSTRUCTORS(PatriciaTriePolicy);

    const MmappedBuffer *const mBuffer;
    const HeaderPolicy mHeaderPolicy;
    const uint8_t *const mDictRoot;
    const int mDictBufferSize;
    const BigramListPolicy mBigramListPolicy;
    const ShortcutListPolicy mShortcutListPolicy;

    int createAndGetLeavingChildNode(const DicNode *const dicNode, const int ptNodePos,
            DicNodeVector *const childDicNodes) const;
};
} // namespace latinime
#endif // LATINIME_PATRICIA_TRIE_POLICY_H

extension: h


text:
/*

Print the numbers from 1 to 1000 without using any loop or conditional statements.

Don’t just write the printf() or cout statement 1000 times.

Be creative and try to find the most efficient way!

*/

#include <cstdio>

template <int N>
void gen()
{
	if (N < 1)
		return;
	gen<N-1>();
	printf("%d\n", N);
}

template <>
void gen<0>()
{
}

int main()
{
	gen<1000>();
	return 0;
}

repository: qeedquan/challenges

repo_name: qeedquan/challenges


text:
#
# This file is the benchmarks-mani recipe.
#

SUMMARY = "Copy all benchmarks from manifold"
SECTION = "PETALINUX/apps"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

SRC_URI = "file://benchmarks-mani \
	   file://benchmarks \
	"

S = "${WORKDIR}"

do_install() {
	     install -d ${D}/${bindir}
	     install -m 0755 ${S}/benchmarks-mani ${D}/${bindir}
	     install -d ${D}/data/benchmarks
	     cp      -r ${WORKDIR}/benchmarks   ${D}/data
}

RDEPENDS_${PN} = " \
	bash \
"

FILES_${PN} = " \
  /data/benchmarks \
  /data/benchmarks/* \
  /usr/bin/benchmarks-mani \
"


text:
require cog.inc

SRC_URI = "https://github.com/Igalia/${PN}/archive/v${PV}.tar.gz"

SRC_URI[md5sum] = "141b94b4cac9b70a9de3e1a2efc21019"
SRC_URI[sha256sum] = "7cefb6e045eaeb02ddb152cf283c1f35221110d0370a0fba7b76d4e96391279c"

repository: kristoiv/meta-webkit

repo_name: kristoiv/meta-webkit


text:
@INPROCEEDINGS{Yamaguchi2003,
  author = {Yumi Yamaguchi and Takayuki Itoh},
  title = {Visualization of Distributed Processes Using {Data Jewelry Box} Algorithm},
  pages = {162--169},
  abstract = {Visualization of distributed processes is useful for the management of large-scale distributed computing systems. Reactivity and scalability are especially important requirements for such visualization of distributed processes. We have proposed the visualization technique "Data Jewelry Box" algorithm, which satisfies both of the above requirements. The technique can be applied for the visualization of distributed processes, however, the algorithm has a problem that may yield much different data layouts even among very similar datasets. This is a serious issue for the seamless visualization of time-varying data. To solve the problem, we propose the extension of "Data Jewelry Box" algorithm. The extension places data elements referring positions of the previous data layout, so that the extension can yield similar layouts among similar datasets. We introduce the extended algorithm, and propose the visualization system for distributed computing systems using the extended algorithm.},
  doi = {10.1109/CGI.2003.1214461},
  year = {2003},
  booktitle = PROC # {Computer Graphics International 2003},
  publisher = {IEEE Computer Society},
  isbn = {0769519466}
}

repository: vis-au/treevisnet

repo_name: vis-au/treevisnet