text:
package cfn

import (
	"context"
	"net/http"
	"testing"

	"github.com/aws/aws-lambda-go/cfn"
	"github.com/google/go-cmp/cmp"
	"github.com/shogo82148/cfn-mackerel-macro/mackerel"
)

func TestCreateService(t *testing.T) {
	s := &service{
		Function: &Function{
			org: &mackerel.Org{
				Name: "test-org",
			},
			client: &fakeMackerelClient{
				createService: func(ctx context.Context, param *mackerel.CreateServiceParam) (*mackerel.Service, error) {
					if param.Name != "awesome-service" {
						t.Errorf("unexpected name, want %s, got %s", "awesome-service", param.Name)
					}
					return &mackerel.Service{
						Name:  param.Name,
						Memo:  "",
						Roles: []string{},
					}, nil
				},
				putServiceMetaData: func(ctx context.Context, serviceName, namespace string, v interface{}) error {
					if namespace != "cloudformation" {
						t.Errorf("unexpected namespace: want cloudformation, got %s", namespace)
					}
					if serviceName != "awesome-service" {
						t.Errorf("unexpected host id, want %sn got %s", "awesome-service", serviceName)
					}
					meta := v.(metadata)
					want := metadata{
						StackName: "foobar",
						StackID:   "arn:aws:cloudformation:ap-northeast-1:1234567890:stack/foobar/12345678-1234-1234-1234-123456789abc",
						LogicalID: "Service",
					}
					if diff := cmp.Diff(meta, want); diff != "" {
						t.Errorf("metadata differs: (-got +want)\n%s", diff)
					}
					return nil
				},
			},
		},
		Event: cfn.Event{
			RequestType:       cfn.RequestCreate,
			RequestID:         "",
			ResponseURL:       "https://cloudformation-custom-resource-response-apnortheast1.s3-ap-northeast-1.amazonaws.com/xxxxx",
			ResourceType:      "Custom:Service",
			LogicalResourceID: "Service",
			StackID:           "arn:aws:cloudformation:ap-northeast-1:1234567890:stack/foobar/12345678-1234-1234-1234-123456789abc",
			ResourceProperties: map[string]interface{}{
				"Name": "awesome-service",
			},
		},
	}
	id, param, err := s.create(context.Background())
	if err != nil {
		t.Error(err)
	}
	if id != "mkr:test-org:service:awesome-service" {
		t.Errorf("unexpected host id: want %s, got %s", "mkr:test-org:service:awesome-service", id)
	}
	if param["Name"].(string) != "awesome-service" {
		t.Errorf("unexpected name, want %s, got %s", "awesome-service", param["Name"].(string))
	}
}

func TestCreateService_AlreadyExists(t *testing.T) {
	s := &service{
		Function: &Function{
			org: &mackerel.Org{
				Name: "test-org",
			},
			client: &fakeMackerelClient{
				createService: func(ctx context.Context, param *mackerel.CreateServiceParam) (*mackerel.Service, error) {
					return nil, mkrError{
						statusCode: http.StatusBadRequest,
					}
				},
				putServiceMetaData: func(ctx context.Context, serviceName, namespace string, v interface{}) error {
					if namespace != "cloudformation" {
						t.Errorf("unexpected namespace: want cloudformation, got %s", namespace)
					}
					if serviceName != "awesome-service" {
						t.Errorf("unexpected host id, want %sn got %s", "awesome-service", serviceName)
					}
					meta := v.(metadata)
					want := metadata{
						StackName: "foobar",
						StackID:   "arn:aws:cloudformation:ap-northeast-1:1234567890:stack/foobar/12345678-1234-1234-1234-123456789abc",
						LogicalID: "Service",
					}
					if diff := cmp.Diff(meta, want); diff != "" {
						t.Errorf("metadata differs: (-got +want)\n%s", diff)
					}
					return nil
				},
			},
		},
		Event: cfn.Event{
			RequestType:       cfn.RequestCreate,
			RequestID:         "",
			ResponseURL:       "https://cloudformation-custom-resource-response-apnortheast1.s3-ap-northeast-1.amazonaws.com/xxxxx",
			ResourceType:      "Custom:Service",
			LogicalResourceID: "Service",
			StackID:           "arn:aws:cloudformation:ap-northeast-1:1234567890:stack/foobar/12345678-1234-1234-1234-123456789abc",
			ResourceProperties: map[string]interface{}{
				"Name": "awesome-service",
			},
		},
	}
	id, param, err := s.create(context.Background())
	if err != nil {
		t.Error(err)
	}
	if id != "mkr:test-org:service:awesome-service" {
		t.Errorf("unexpected host id: want %s, got %s", "mkr:test-org:service:awesome-service", id)
	}
	if param["Name"].(string) != "awesome-service" {
		t.Errorf("unexpected name, want %s, got %s", "awesome-service", param["Name"].(string))
	}
}

func TestDeleteService(t *testing.T) {
	var deleted bool
	s := &service{
		Function: &Function{
			org: &mackerel.Org{
				Name: "test-org",
			},
			client: &fakeMackerelClient{
				deleteService: func(ctx context.Context, serviceName string) (*mackerel.Service, error) {
					deleted = true
					if serviceName != "awesome-service" {
						t.Errorf("unexpected service name, want awesome-service, got %s", serviceName)
					}
					return &mackerel.Service{
						Name: serviceName,
					}, nil
				},
			},
		},
		Event: cfn.Event{
			RequestType:       cfn.RequestDelete,
			RequestID:         "",
			ResponseURL:       "https://cloudformation-custom-resource-response-apnortheast1.s3-ap-northeast-1.amazonaws.com/xxxxx",
			ResourceType:      "Custom:Service",
			LogicalResourceID: "Service",
			StackID:           "arn:aws:cloudformation:ap-northeast-1:1234567890:stack/foobar/12345678-1234-1234-1234-123456789abc",
			ResourceProperties: map[string]interface{}{
				"Name": "awesome-service",
			},
			PhysicalResourceID: "mkr:test-org:service:awesome-service",
		},
	}
	_, _, err := s.delete(context.Background())
	if err != nil {
		t.Error(err)
	}
	if !deleted {
		t.Error("the service is not deleted")
	}
}

func TestDeleteService_serviceNotFound(t *testing.T) {
	var deleted bool
	s := &service{
		Function: &Function{
			org: &mackerel.Org{
				Name: "test-org",
			},
			client: &fakeMackerelClient{
				deleteService: func(ctx context.Context, serviceName string) (*mackerel.Service, error) {
					deleted = true
					if serviceName != "awesome-service" {
						t.Errorf("unexpected service name, want awesome-service, got %s", serviceName)
					}
					return nil, mkrError{
						statusCode: http.StatusNotFound,
					}
				},
			},
		},
		Event: cfn.Event{
			RequestType:       cfn.RequestDelete,
			RequestID:         "",
			ResponseURL:       "https://cloudformation-custom-resource-response-apnortheast1.s3-ap-northeast-1.amazonaws.com/xxxxx",
			ResourceType:      "Custom:Service",
			LogicalResourceID: "Service",
			StackID:           "arn:aws:cloudformation:ap-northeast-1:1234567890:stack/foobar/12345678-1234-1234-1234-123456789abc",
			ResourceProperties: map[string]interface{}{
				"Name": "awesome-service",
			},
			PhysicalResourceID: "mkr:test-org:service:awesome-service",
		},
	}
	_, _, err := s.delete(context.Background())
	if err != nil {
		t.Error(err)
	}
	if !deleted {
		t.Error("the service is not deleted")
	}
}

branch_name: refs/heads/main


text:
package v1

import (
	sloCrds "sloc.github.io/sloc/apis/slo/v1"
)

const (
	// SloComplianceDefaultTolerance is the default tolerance for SloCompliance.
	SloComplianceDefaultTolerance int32 = 10

	// SloComplianceDefaultSloTargetCompliance is the default value for SloCompliance.SloTargetCompliance
	SloComplianceDefaultSloTargetCompliance int32 = 100
)

// SloCompliance contains the information needed for elasticity strategies that require only a single
// parameter, i.e., the current SLO compliance value.
//
// Embed this struct in the CRDs that should work with single parameter elasticity strategies.
type SloCompliance struct {
	// Specifies how much the current state of the system complies with the SLO.
	//
	// This value must be specified as an integer, e.g., `50` meaning 50%,
	// `100` meaning 100%, `200` meaning 200%.
	//
	// If this value is `100`, the SLO is met exactly and no scaling action is required.
	//
	// If this value is greater than `100`, the SLO is violated
	// and scaling out/up is required.
	//
	// If this value is less than `100`, the system is performing
	// better than the SLO demands and scaling in/down will be performed.
	//
	CurrSloCompliancePercentage int32 `json:"currSloCompliancePercentage,omitempty"`

	// Specifies the tolerance around 100%, within which no scaling will be performed.
	//
	// For example, if tolerance is `10`, no scaling will be performed as long as `currSloCompliancePercentage`
	// is between `90` and `110`.
	Tolerance *int32 `json:"tolerance,omitempty"`
}

// SloComplianceElasticityStrategyData describes the input data for any SloCompliance-based elasticity strategy.
type SloComplianceElasticityStrategyData struct {

	// Specifies the target on which to execute the elasticity strategy.
	sloCrds.SloTarget `json:",inline"`

	// Specifies how much the current state of the system complies with the SLO.
	SloCompliance `json:",inline"`
}

repository: SLOCloud/SLOC

license_type: permissive

repo_name: SLOCloud/SLOC

branch_name: refs/heads/master

gha_language: TypeScript

extension: go


text:
DESCRIPTION = "Scapy is a powerful interactive packet manipulation tool, \
packet generator, network scanner, network discovery, packet sniffer, etc. \
It can for the moment replace hping, 85% of nmap, arpspoof, arp-sk, arping, \
tcpdump, tethereal, p0f, ...."
SECTION = "devel/python"
HOMEPAGE = "http://www.secdev.org/projects/scapy/"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://bin/scapy;beginline=3;endline=18;md5=a5be896f88f8396346f67f7a8878ee09"
PRIORITY = "optional"
SRCNAME = "scapy"
PR = "ml2"

SRC_URI = "https://pypi.python.org/packages/36/0a/d6f4f3c621a1d5e063ccae5e91816f565d92ecf0a372193f141b15859539/scapy-python3-0.20.tar.gz"
SRC_URI[md5sum] = "708456a38987bb76b35d6594875a5b2b"

S = "${WORKDIR}/scapy-python3-0.20"

inherit setuptools3

RDEPENDS_${PN} = "\
  ${PYTHON_PN}-netclient \
  ${PYTHON_PN}-netserver \
  ${PYTHON_PN}-pydoc \
  ${PYTHON_PN}-pkgutil \
"

repository: jsdanielh/libreswitch

repo_name: jsdanielh/libreswitch

extension: bb


text:
@article{melymcb-0152,
 author = {Scalise, O.H.},
 document_type = {Article},
 doi = {10.1080/00319109808030608},
 journal = {Physics and Chemistry of Liquids},
 note = {cited By 5},
 number = {3},
 pages = {179-185},
 source = {Scopus},
 title = {Vapour-liquid coexistence in a quasi two-dimensional hard dipolar fluid},
 url = {https://www.scopus.com/inward/record.uri?eid=2-s2.0-0032423973&doi=10.1080%2f00319109808030608&partnerID=40&md5=2aae4613b25e2449be5751285fe5cd5d},
 volume = {36},
 year = {1998}
}

license: MIT

extension: bib


text:
package manifest

type Release struct {
	Name    string `yaml:"name"`
	Version string `yaml:"version"`

	CommitHash         string `yaml:"commit_hash"`
	UncommittedChanges bool   `yaml:"uncommitted_changes"`

	Jobs     []Job     `yaml:"jobs"`
	Packages []Package `yaml:"packages"`
}

repository: drnic/bosh-init

repo_name: drnic/bosh-init


text:
package kinitx

import "github.com/go-kata/kinit"

// Apply calls kinit.Apply passing a processor based on the given entity.
//
// See the documentation for the NewProcessor to find out possible values of the argument x.
//
// Deprecated: since 0.4.0, use Attach instead.
func Apply(x interface{}) error {
	proc, err := NewProcessor(x)
	if err != nil {
		return err
	}
	return kinit.Apply(proc)
}

// MustApply is a variant of the Apply that panics on error.
//
// Deprecated: since 0.4.0, use MustAttach instead.
func MustApply(x interface{}) {
	if err := Apply(x); err != nil {
		panic(err)
	}
}

repository: go-kata/kinitx

repo_name: go-kata/kinitx


text:
@article{gomory1997characterization,
  title={Characterization of high-temperature superconductors by AC susceptibility measurements},
  author={G{\"o}m{\"o}ry, Fedor},
  journal={Superconductor Science and Technology},
  volume={10},
  number={8},
  pages={523},
  year={1997},
  publisher={IOP Publishing}
}

@book{francavilla2013magnetic,
  title={Magnetic susceptibility of superconductors and other spin systems},
  author={Francavilla, Thomas L and Hein, Robert A and Liebenberg, Donald H},
  year={2013},
  publisher={Springer Science \& Business Media}
}

@incollection{goldfarb1991alternating,
  title={Alternating-field susceptometry and magnetic susceptibility of superconductors},
  author={Goldfarb, Ronald B and Lelental, M and Thompson, CA},
  booktitle={Magnetic susceptibility of superconductors and other spin systems},
  pages={49--80},
  year={1991},
  publisher={Springer}
  }

@article{bean1964magnetization,
  title={Magnetization of high-field superconductors},
  author={Bean, Charles P},
  journal={Reviews of modern physics},
  volume={36},
  number={1},
  pages={31},
  year={1964},
  publisher={APS}
}

@article{ji1989critical,
  title={Critical-state model for harmonic generation in high-temperature superconductors},
  author={Ji, L and Sohn, RH and Spalding, GC and Lobb, CJ and Tinkham, M},
  journal={Physical Review B},
  volume={40},
  number={16},
  pages={10936},
  year={1989},
  publisher={APS}
}

@article{matsushita1989ac,
  title={Ac Permeability Measurement for Inter-and Intragrain Critical Current Densities in Oxide Superconductors},
  author={Matsushita, Teruo and Ni, Baorong},
  journal={Japanese Journal of Applied Physics},
  volume={28},
  number={3A},
  pages={L419},
  year={1989},
  publisher={IOP Publishing}
}

repository: fedowser/acs

repo_name: fedowser/acs


text:
package evm

import (
	"github.com/entropyio/go-entropy/blockchain/state"
	"github.com/entropyio/go-entropy/common"
	"github.com/entropyio/go-entropy/config"
	"github.com/entropyio/go-entropy/database/rawdb"
	"math"
	"math/big"
	"testing"
	"time"
)

var loopInterruptTests = []string{
	// infinite loop using JUMP: push(2) jumpdest dup1 jump
	"60025b8056",
	// infinite loop using JUMPI: push(1) push(4) jumpdest dup2 dup2 jumpi
	"600160045b818157",
}

func TestLoopInterrupt(t *testing.T) {
	address := common.BytesToAddress([]byte("contract"))
	vmctx := BlockContext{
		Transfer: func(StateDB, common.Address, common.Address, *big.Int) {},
	}

	for i, tt := range loopInterruptTests {
		statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
		statedb.CreateAccount(address)
		statedb.SetCode(address, common.Hex2Bytes(tt))
		statedb.Finalise(true)

		evm := NewEVM(vmctx, TxContext{}, statedb, config.TestChainConfig, Config{})

		errChannel := make(chan error)
		timeout := make(chan bool)

		go func(evm *EVM) {
			_, _, err := evm.Call(AccountRef(common.Address{}), address, nil, math.MaxUint64, new(big.Int))
			errChannel <- err
		}(evm)

		go func() {
			<-time.After(time.Second)
			timeout <- true
		}()

		evm.Cancel()

		select {
		case <-timeout:
			t.Errorf("test %d timed out", i)
		case err := <-errChannel:
			if err != nil {
				t.Errorf("test %d failure: %v", i, err)
			}
		}
	}

}

repository: entropyio/go-entropy

repo_name: entropyio/go-entropy

gha_language: Go


text:
package orr

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

// 每个结构必须有key键值，字段名必须为Id，必须为正整数
//
// tags:
//   orr
//     index: 该字段名与结构名(结构名_字段名)，作为辅助hashmap，hashmap的field为该字段值，hashmap的值位obj.Id
//     list: 该字段名与结构名(结构名_字段名)，作为辅助list
//  example: `orr:"index"`

// map,list数据过大的解决方法：
//  当map,list数据较少时(1000个以内)，可以将map,list数据保存为json格式; 当map,list数据超过一定规模时，
//  应使用redis的hashmap或list数据结构
//  可以通过设置用户的relations来决定该数据是否以json格式保存

// Insert用于初次数据到redis中，检查struct的tags，并根据tags的定义，
// 来设置redis的辅助字段
// 返回Id
func Insert(obj interface{}, index bool) (int64, error) {
	if reflect.TypeOf(obj).Kind() != reflect.Ptr {
		return -1, fmt.Errorf("param obj MUST be type Ptr.")
	}
	rvobj := reflect.ValueOf(obj).Elem()
	rtobj := reflect.TypeOf(rvobj.Interface())

	if rtobj.Kind() != reflect.Struct {
		return -1, fmt.Errorf("Param obj must be struct type.")
	}

	objName := getTypeName(rtobj)

	// 查看结构体是否有辅助字段
	var (
		idxkeys   []string = make([]string, 0)
		idxfields []string = make([]string, 0)
		vid       reflect.Value
	)
	for i := 0; i < rtobj.NumField(); i++ {
		structfield := rtobj.Field(i)
		if structfield.Anonymous {
			continue
		}

		fieldName := structfield.Name
		tag := structfield.Tag
		if tag == "" || tag == "-" {
			continue
		}

		if tag.Get("orr") == "index" {
			fieldValue := rvobj.Field(i)
			if fieldValue.Kind() != reflect.String {
				return -1, fmt.Errorf("index field must be string type!")
			}
			fv := fieldValue.Interface().(string)
			if fv == "" {
				if index {
					return -1, fmt.Errorf("field %s should be index, but is empty.", fieldName)
				} else {
					continue
				}
			}

			if unique(objName+"_"+fieldName, fv) != true {
				return -1, fmt.Errorf("field %s has exist value %s.", fieldName, fieldValue)
			}
			idxkeys = append(idxkeys, objName+"_"+strings.Replace(strings.ToLower(fieldName), "_", "", -1))
			idxfields = append(idxfields, fv)
		}
	}

	id := NewId(objName)
	sid := strconv.FormatInt(id, 10)

	bsid := []byte(sid)
	for i := 0; i < len(idxkeys); i++ {
		hsetToRedis(idxkeys[i], idxfields[i], bsid, "map")
	}

	vid = rvobj.FieldByName("Id")
	vid.SetInt(id)
	buf, err := json.Marshal(obj)
	if err != nil {
		ReturnId(objName, id)
		return -1, err
	}

	err = hsetToRedis(objName, sid, buf, "map")
	if err != nil {
		for i := 0; i < len(idxkeys); i++ {
			hdelFromRedis(idxkeys[i], idxfields[i], "map")
		}

		ReturnId(objName, id)
		return -1, err
	}

	return id, nil
}

// 将结构体的field插入到数据库中
// typ should be "key" or "hash"
func InsertKeyField(typ, name string, fn string, id int64, value interface{}) error {
	buf, err := json.Marshal(&value)
	if err != nil {
		return err
	}
	conn := rpool.Get()
	defer conn.Close()
	sid := strconv.FormatInt(id, 10)
	switch typ {
	case "key":
		_, err := conn.Do("SET", name+"_"+fn+"_"+sid, buf)
		return err

	case "hash":
		_, err := conn.Do("HSET", name+"_"+fn, sid, buf)
		return err

	default:
		return fmt.Errorf("param typ invalid, must be key or hash or list.")
	}

	return nil
}

func BuildRelation() {

}

// 仅更新主hashmap
func Update(obj interface{}, objName string, objId int64) error {
	buf, err := json.Marshal(obj)
	if err != nil {
		return err
	}

	err = hsetToRedis(objName, strconv.FormatInt(objId, 10), buf, "map")
	return err
}

func Delete(obj interface{}) error {
	var (
		rvobj reflect.Value
		rtobj reflect.Type
	)

	if reflect.TypeOf(obj).Kind() == reflect.Ptr {
		rvobj = reflect.ValueOf(obj).Elem()
		rtobj = reflect.TypeOf(rvobj.Interface())
	} else {
		rvobj = reflect.ValueOf(obj)
		rtobj = reflect.TypeOf(obj)
	}

	if rtobj.Kind() != reflect.Struct {
		return fmt.Errorf("Param obj must be struct type.")
	}

	var (
		idxfields []string
		idxvalue  []string
	)
	objName := getTypeName(rtobj)

	for i := 0; i < rtobj.NumField(); i++ {
		structfield := rtobj.Field(i)
		if structfield.Anonymous {
			continue
		}

		fieldName := structfield.Name
		tag := structfield.Tag
		if tag == "" || tag == "-" {
			continue
		}

		if tag.Get("orr") == "index" {
			if rvobj.Field(i).String() != "" {
				idxfields = append(idxfields, objName+"_"+strings.ToLower(fieldName))
				idxvalue = append(idxvalue, rvobj.Field(i).String())
			}
		}
	}
	conn := rpool.Get()
	defer conn.Close()
	id := rvobj.FieldByName("Id").Int()
	sid := strconv.FormatInt(id, 10)
	for i, field := range idxfields {
		conn.Send("HDEL", field, idxvalue[i])
	}
	conn.Send("HDEL", objName, sid)
	conn.Flush()
	/*
		for i := 0; i <= len(idxfields); i++ {
			fmt.Println("conn receive ", i)
			r, err := conn.Receive()
			if err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println(r)
			}
		}
	*/
	return nil
}

func DeleteKeyField(typ string, name string, fn string, id int64) {
	conn := rpool.Get()
	defer conn.Close()
	switch typ {
	case "key":
		conn.Do("DEL", name+"_"+fn+"_"+strconv.FormatInt(id, 10))
		return

	case "hash":
		conn.Do("HDEL", name+"_"+fn, strconv.FormatInt(id, 10))
		return

	default:
		panic("param typ invalid, must be key or hash or list.")
	}
}

// 从redis中还原数据
func Select(Id int64, name string, res interface{}) error {
	if reflect.TypeOf(res).Kind() != reflect.Ptr {
		return fmt.Errorf("param res must be Ptr type.")
	}
	conn := rpool.Get()
	defer conn.Close()
	reply, err := conn.Do("HGET", name, strconv.FormatInt(Id, 10))
	if err != nil {
		return err
	}

	err = json.Unmarshal(reply.([]byte), res)
	return err
}

func SelectIndex(name, fn, value string) (int64, error) {
	conn := rpool.Get()
	defer conn.Close()
	reply, err := conn.Do("HGET", name+"_"+fn, value)
	if err != nil || reply == nil {
		return -1, err
	}
	id, err := strconv.ParseInt(string(reply.([]byte)), 10, 64)
	if err != nil {
		return -1, err
	}
	return id, nil
}

func SelectKeyField(keyTyp string, name string,
	fn string, id int64, res interface{}) (err error) {
	if reflect.TypeOf(res).Kind() != reflect.Ptr {
		return fmt.Errorf("param res must be Ptr type.")
	}
	var reply interface{}

	sid := strconv.FormatInt(id, 10)
	conn := rpool.Get()
	defer conn.Close()
	switch keyTyp {
	case "key":
		reply, err = conn.Do("GET", name+"_"+fn+"_"+sid)
	case "hash":
		reply, err = conn.Do("HGET", name+"_"+fn, sid)
	default:
		return fmt.Errorf("Not support this keytype: %s", keyTyp)
	}
	if err != nil {
		return err
	}
	if reply == nil {
		res = reflect.New(reflect.TypeOf(res)).Elem()
		return
	}

	err = json.Unmarshal(reply.([]byte), res)
	return err
}

func getLatestId(name string) (string, error) {
	conn := rpool.Get()
	defer conn.Close()
	reply, err := conn.Do("INCR", name)
	if err != nil {
		return "", err
	}

	return reply.(string), nil
}

func parseTag(str string) (typ string, addational_typ string) {
	if str == "-" {
		typ = str
	} else if str != "" {
		tags := strings.Split(str, ";")
		m := make(map[string]string)
		for _, value := range tags {
			v := strings.Split(value, ":")
			k := strings.TrimSpace(strings.ToUpper(v[0]))
			if len(v) == 2 {
				m[k] = v[1]
			} else {
				m[k] = k
			}
		}

		addational_typ = m["NOT NULL"] + " " + m["UNIQUE"]
	}
	return
}

func unique(name string, value string) bool {
	conn := rpool.Get()
	defer conn.Close()
	reply, _ := conn.Do("HGET", name, value)
	if reply != nil {
		return false
	}

	return true
}

repository: guotie/orr

repo_name: guotie/orr


text:
// Copyright 2018 Istio 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 ctrlz implements Istio's introspection facility. When components
// integrate with ControlZ, they automatically gain an IP port which allows operators
// to visualize and control a number of aspects of each process, including controlling
// logging scopes, viewing command-line options, memory use, etc. Additionally,
// the port implements a REST API allowing access and control over the same state.
//
// ControlZ is designed around the idea of "topics". A topic corresponds to the different
// parts of the UI. There are a set of built-in topics representing the core introspection
// functionality, and each component that uses ControlZ can add new topics specialized
// for their purpose.
package ctrlz

import (
	"fmt"
	"html/template"
	"net"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/gorilla/mux"

	"istio.io/pkg/ctrlz/assets"
	"istio.io/pkg/ctrlz/fw"
	"istio.io/pkg/ctrlz/topics"
	"istio.io/pkg/log"
)

var coreTopics = []fw.Topic{
	topics.ScopeTopic(),
	topics.MemTopic(),
	topics.EnvTopic(),
	topics.ProcTopic(),
	topics.ArgsTopic(),
	topics.VersionTopic(),
	topics.MetricsTopic(),
	topics.SignalsTopic(),
}

var (
	allTopics          []fw.Topic
	topicMutex         sync.Mutex
	listeningTestProbe func()
)

// Server represents a running ControlZ instance.
type Server struct {
	listener   net.Listener
	shutdown   sync.WaitGroup
	httpServer http.Server
}

func augmentLayout(layout *template.Template, page string) *template.Template {
	return assets.ParseTemplate(layout, page)
}

func registerTopic(router *mux.Router, layout *template.Template, t fw.Topic) {
	htmlRouter := router.NewRoute().PathPrefix("/" + t.Prefix() + "z").Subrouter()
	jsonRouter := router.NewRoute().PathPrefix("/" + t.Prefix() + "j").Subrouter()

	tmpl := template.Must(template.Must(layout.Clone()).Parse("{{ define \"title\" }}" + t.Title() + "{{ end }}"))
	t.Activate(fw.NewContext(htmlRouter, jsonRouter, tmpl))
}

// getLocalIP returns a non loopback local IP of the host
func getLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}

	for _, address := range addrs {
		// check the address type and if it is not a loopback then return it
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

type topic struct {
	Name string
	URL  string
}

func getTopics() []topic {
	topicMutex.Lock()
	defer topicMutex.Unlock()

	topics := make([]topic, 0, len(allTopics))
	for _, t := range allTopics {
		topics = append(topics, topic{Name: t.Title(), URL: "/" + t.Prefix() + "z/"})
	}

	return topics
}

func normalize(input string) string {
	return strings.Replace(input, "/", "-", -1)
}

// RegisterTopic registers a new Control-Z topic for the current process.
func RegisterTopic(t fw.Topic) {
	topicMutex.Lock()
	defer topicMutex.Unlock()

	allTopics = append(allTopics, t)
}

// Run starts up the ControlZ listeners.
//
// ControlZ uses the set of standard core topics, the
// supplied custom topics, as well as any topics registered
// via the RegisterTopic function.
func Run(o *Options, customTopics []fw.Topic) (*Server, error) {
	topicMutex.Lock()
	allTopics = append(allTopics, coreTopics...)
	allTopics = append(allTopics, customTopics...)
	topicMutex.Unlock()

	exec, _ := os.Executable()
	instance := exec + " - " + getLocalIP()

	funcs := template.FuncMap{
		"getTopics": getTopics,
		"normalize": normalize,
	}

	baseLayout := assets.ParseTemplate(template.New("base"), "templates/layouts/base.html")
	baseLayout = baseLayout.Funcs(funcs)
	baseLayout = template.Must(baseLayout.Parse("{{ define \"instance\" }}" + instance + "{{ end }}"))
	_ = augmentLayout(baseLayout, "templates/modules/header.html")
	_ = augmentLayout(baseLayout, "templates/modules/sidebar.html")
	_ = augmentLayout(baseLayout, "templates/modules/last-refresh.html")
	mainLayout := augmentLayout(template.Must(baseLayout.Clone()), "templates/layouts/main.html")

	router := mux.NewRouter()
	for _, t := range allTopics {
		registerTopic(router, mainLayout, t)
	}

	registerHome(router, mainLayout)

	addr := o.Address
	if addr == "*" {
		addr = ""
	}

	// Canonicalize the address and resolve a dynamic port if necessary
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, o.Port))
	if err != nil {
		log.Errorf("Unable to start ControlZ: %v", err)
		return nil, err
	}

	s := &Server{
		listener: listener,
		httpServer: http.Server{
			Addr:           listener.Addr().(*net.TCPAddr).String(),
			ReadTimeout:    10 * time.Second,
			WriteTimeout:   10 * time.Second,
			MaxHeaderBytes: 1 << 20,
			Handler:        router,
		},
	}

	s.shutdown.Add(1)
	go s.listen()

	return s, nil
}

func (s *Server) listen() {
	log.Infof("ControlZ available at %s", s.httpServer.Addr)
	if listeningTestProbe != nil {
		go listeningTestProbe()
	}
	err := s.httpServer.Serve(s.listener)
	log.Infof("ControlZ terminated: %v", err)
	s.shutdown.Done()
}

// Close terminates ControlZ.
//
// Close is not normally used by programs that expose ControlZ, it is primarily intended to be
// used by tests.
func (s *Server) Close() {
	log.Info("Closing ControlZ")

	if s.listener != nil {
		if err := s.listener.Close(); err != nil {
			log.Warnf("Error closing ControlZ: %v", err)
		}
		s.shutdown.Wait()
	}
}

func (s *Server) Address() string {
	return s.httpServer.Addr
}

repository: istio/pkg

repo_name: istio/pkg


text:
package main

import (
	"fmt"

	"github.com/anuvu/stacker"
	"github.com/urfave/cli"
)

var buildCmd = cli.Command{
	Name:   "build",
	Usage:  "builds a new OCI image from a stacker yaml file",
	Action: doBuild,
	Flags: []cli.Flag{
		cli.BoolFlag{
			Name:  "leave-unladen",
			Usage: "leave the built rootfs mount after image building",
		},
		cli.StringFlag{
			Name:  "stacker-file, f",
			Usage: "the input stackerfile",
			Value: "stacker.yaml",
		},
		cli.BoolFlag{
			Name:  "no-cache",
			Usage: "don't use the previous build cache",
		},
		cli.StringSliceFlag{
			Name:  "substitute",
			Usage: "variable substitution in stackerfiles, FOO=bar format",
		},
		cli.StringFlag{
			Name:  "on-run-failure",
			Usage: "command to run inside container if run fails (useful for inspection)",
		},
		cli.BoolFlag{
			Name:  "shell-fail",
			Usage: "exec /bin/sh inside the container if run fails (alias for --on-run-failure=/bin/sh)",
		},
		cli.BoolFlag{
			Name:  "apply-consider-timestamps",
			Usage: "for apply layer merging, fail if timestamps on files don't match",
		},
		cli.StringFlag{
			Name:  "layer-type",
			Usage: "set the output layer type (supported values: tar, squashfs)",
			Value: "tar",
		},
		cli.BoolFlag{
			Name:  "order-only",
			Usage: "show the build order without running the actual build",
		},
	},
	Before: beforeBuild,
}

func beforeBuild(ctx *cli.Context) error {
	if ctx.Bool("shell-fail") {
		askedFor := ctx.String("on-run-failure")
		if askedFor != "" && askedFor != "/bin/sh" {
			return fmt.Errorf("--shell-fail is incompatible with --on-run-failure=%s", askedFor)
		}
		err := ctx.Set("on-run-failure", "/bin/sh")
		if err != nil {
			return err
		}
	}

	switch ctx.String("layer-type") {
	case "tar":
		break
	case "squashfs":
		fmt.Println("squashfs support is experimental")
		break
	default:
		return fmt.Errorf("unknown layer type: %s", ctx.String("layer-type"))
	}

	return nil
}

func doBuild(ctx *cli.Context) error {
	args := stacker.BuildArgs{
		Config:                  config,
		LeaveUnladen:            ctx.Bool("leave-unladen"),
		NoCache:                 ctx.Bool("no-cache"),
		Substitute:              ctx.StringSlice("substitute"),
		OnRunFailure:            ctx.String("on-run-failure"),
		ApplyConsiderTimestamps: ctx.Bool("apply-consider-timestamps"),
		LayerType:               ctx.String("layer-type"),
		OrderOnly:               ctx.Bool("order-only"),
		Debug:                   debug,
	}

	builder := stacker.NewBuilder(&args)
	return builder.BuildMultiple([]string{ctx.String("stacker-file")})
}

repository: smoser/stacker

repo_name: smoser/stacker


text:
package cache

import (
	"errors"
	"fmt"
	"strconv"
)

/*Cache is the thing the server knows
how to ask about the existance of a
particular entry.  Various implementations
can be built that correspond to this interface*/
type Cache interface {
	KeyPresent(key string) bool
	GetValue(key string) (Entry, error)
	SetValue(key string, value Entry) error
}

/*NoOp is a dummy implementation.  No keys are ever present,
so it never has to replace anything.  Naive baseline.*/
type NoOp struct{}

/*KeyPresent will always be false for the no-op cache*/
func (cno *NoOp) KeyPresent(k string) bool { return false }

/*GetValue will always return an error for the no-op cache*/
func (cno *NoOp) GetValue(k string) (Entry, error) {
	return Entry{}, errors.New("Key not present")
}

/*SetValue does nothing in the no-op cache*/
func (cno *NoOp) SetValue(k string, v Entry) error { return nil }

/*useful for easily tracking the "oldest" added node in the
cache*/
type fifoNode struct {
	key   string
	entry Entry
	prev  *fifoNode
	next  *fifoNode
}

/*FiFo is a First-in-fist-out cache implementation.
When full, it will always decide to evict the oldest key added.*/
type FiFo struct {
	maxSize int
	length  int
	head    *fifoNode
	tail    *fifoNode
	lookup  map[string]*fifoNode
}

/*KeyPresent is true if the key is in the cache right now*/
func (ff *FiFo) KeyPresent(k string) bool {
	_, ok := ff.lookup[k]
	return ok
}

/*GetValue will return the entry if present in the lookup*/
func (ff *FiFo) GetValue(k string) (Entry, error) {
	node, ok := ff.lookup[k]
	if !ok {
		return Entry{}, errors.New("Key not present in lookup hash")
	}
	return node.entry, nil
}

/*SetValue inserts a new cache entry, evicting one if necessary*/
func (ff *FiFo) SetValue(k string, v Entry) error {
	if ff.length == 0 {
		// create list head/tail
		node := &fifoNode{entry: v, key: k}
		ff.head = node
		ff.tail = node
		ff.lookup[k] = node
		ff.length = 1
		return nil
	} else if ff.length == ff.maxSize {
		// evict one entry
		newNode := &fifoNode{entry: v, key: k}
		prevHead := ff.head
		delete(ff.lookup, prevHead.key)
		newHead := prevHead.next
		newHead.prev = nil
		ff.head = newHead
		prevTail := ff.tail
		prevTail.next = newNode
		newNode.prev = prevTail
		ff.tail = newNode
		ff.lookup[k] = newNode
		// length does not change
		return nil
	}
	// just grow the list
	newNode := &fifoNode{entry: v, key: k}
	prevTail := ff.tail
	prevTail.next = newNode
	newNode.prev = prevTail
	ff.tail = newNode
	ff.lookup[k] = newNode
	ff.length = ff.length + 1
	return nil
}

func newFifo(size int) *FiFo {
	lk := make(map[string]*fifoNode)
	return &FiFo{maxSize: size, length: 0, head: nil, tail: nil, lookup: lk}
}

/*useful for easily tracking the "least recently accessed" added node in the
cache*/
type lruNode struct {
	key   string
	entry Entry
	prev  *lruNode
	next  *lruNode
}

/*Lru is a cache implementation adapting to access time.
When full, it will always decide to evict the key touched the longest ago.*/
type Lru struct {
	maxSize int
	length  int
	head    *lruNode
	tail    *lruNode
	lookup  map[string]*lruNode
}

/*KeyPresent is true if the key is in the cache right now*/
func (l *Lru) KeyPresent(k string) bool {
	_, ok := l.lookup[k]
	return ok
}

/*GetValue will return the entry if present in the lookup*/
func (l *Lru) GetValue(k string) (Entry, error) {
	node, ok := l.lookup[k]
	if !ok {
		return Entry{}, errors.New("Key not present in lookup hash")
	}
	// promote entry to most recently accessed
	if node == l.tail {
		// do nothing, it's already most recently accessed
	} else if node == l.head {
		// just move head to tail
		newHead := node.next
		newHead.prev = nil
		l.head = newHead
		prevTail := l.tail
		node.prev = prevTail
		prevTail.next = node
		l.tail = node
		node.next = nil
	} else {
		// in the middle, stitch two nodes together and move to tail
		oldPrev := node.prev
		oldNext := node.next
		oldPrev.next = oldNext
		oldNext.prev = oldPrev
		prevTail := l.tail
		node.prev = prevTail
		node.next = nil
		prevTail.next = node
		l.tail = node
	}
	return node.entry, nil
}

/*SetValue inserts a new cache entry, evicting one if necessary*/
func (l *Lru) SetValue(k string, v Entry) error {
	if l.length == 0 {
		// create list head/tail
		node := &lruNode{entry: v, key: k}
		l.head = node
		l.tail = node
		l.lookup[k] = node
		l.length = 1
		return nil
	} else if l.length == l.maxSize {
		// evict one entry
		newNode := &lruNode{entry: v, key: k}
		prevHead := l.head
		delete(l.lookup, prevHead.key)
		newHead := prevHead.next
		newHead.prev = nil
		l.head = newHead
		prevTail := l.tail
		prevTail.next = newNode
		newNode.prev = prevTail
		l.tail = newNode
		l.lookup[k] = newNode
		// length does not change
		return nil
	}
	// just grow the list
	newNode := &lruNode{entry: v, key: k}
	prevTail := l.tail
	prevTail.next = newNode
	newNode.prev = prevTail
	l.tail = newNode
	l.lookup[k] = newNode
	l.length = l.length + 1
	return nil
}

func newLru(size int) *Lru {
	lk := make(map[string]*lruNode)
	return &Lru{maxSize: size, length: 0, head: nil, tail: nil, lookup: lk}
}

/*useful for easily tracking the "least frequently accessed" added node in the
cache*/
type lfuNode struct {
	key         string
	entry       Entry
	accessCount int
	prev        *lfuNode
	next        *lfuNode
}

/*Lfu is a cache implementation adapting to access frequency.
When full, it will always decide to evict the key touched the least number of times.*/
type Lfu struct {
	maxSize int
	length  int
	head    *lfuNode
	tail    *lfuNode
	lookup  map[string]*lfuNode
	debug   bool
}

/*KeyPresent is true if the key is in the cache right now*/
func (l *Lfu) KeyPresent(k string) bool {
	_, ok := l.lookup[k]
	return ok
}

func (l *Lfu) debugCache() {
	fmt.Println("CACHE STATE")
	dbg := ""
	node := l.head
	for {
		dbg = dbg + "->" + node.key + ":" + strconv.Itoa(node.accessCount)
		node = node.next
		if node == nil {
			break
		}
	}
	fmt.Println(dbg)
}

func (l *Lfu) reorderList(node *lfuNode) {
	for {
		if node.accessCount >= node.next.accessCount {
			// swap positions
			if node.prev == nil {
				// node is currently HEAD
				newHead := node.next
				rightHead := newHead.next
				newHead.prev = nil
				node.next = rightHead
				node.prev = newHead
				newHead.next = node
				l.head = newHead
				if rightHead == nil {
					// node is now tail
					l.tail = node
					return
				}
				rightHead.prev = node
			} else {
				// node in the middle of list
				leftTail := node.prev
				swapNode := node.next
				rightHead := swapNode.next
				leftTail.next = swapNode
				swapNode.prev = leftTail
				swapNode.next = node
				node.prev = swapNode
				node.next = rightHead
				if rightHead == nil {
					// node is now tail
					l.tail = node
					return
				}
				rightHead.prev = node
			}
		} else {
			return
		}
	}
}

/*GetValue will return the entry if present in the lookup*/
func (l *Lfu) GetValue(k string) (Entry, error) {
	node, ok := l.lookup[k]
	if !ok {
		return Entry{}, errors.New("Key not present in lookup hash")
	}
	node.accessCount++
	// move node to the right until it is accessed more
	// than prev and less than next, or until it is the tail
	if node == l.tail {
		// do nothing, it's already the most frequently accessed
	} else {
		l.reorderList(node)
	}
	if l.debug {
		l.debugCache()
	}
	return node.entry, nil
}

/*SetValue inserts a new cache entry, evicting one if necessary*/
func (l *Lfu) SetValue(k string, v Entry) error {
	if l.length == 0 {
		// create list head/tail
		node := &lfuNode{entry: v, key: k, accessCount: 1}
		l.head = node
		l.tail = node
		l.lookup[k] = node
		l.length = 1
		if l.debug {
			l.debugCache()
		}
		return nil
	} else if l.length == l.maxSize {
		// evict one entry
		newNode := &lfuNode{entry: v, key: k, accessCount: 1}
		prevHead := l.head
		delete(l.lookup, prevHead.key)
		newHead := prevHead.next
		newHead.prev = nil
		l.head = newNode
		newNode.next = newHead
		newHead.prev = newNode
		l.lookup[k] = newNode
		l.reorderList(newNode)
		if l.debug {
			l.debugCache()
		}
		// length does not change
		return nil
	}
	// just grow the list
	newNode := &lfuNode{entry: v, key: k, accessCount: 1}
	oldHead := l.head
	newNode.next = oldHead
	oldHead.prev = newNode
	l.head = newNode
	l.lookup[k] = newNode
	l.reorderList(newNode)
	l.length++
	if l.debug {
		l.debugCache()
	}
	return nil
}

func newLfu(size int) *Lfu {
	lk := make(map[string]*lfuNode)
	return &Lfu{maxSize: size, length: 0, head: nil, tail: nil, lookup: lk, debug: false}
}

/*useful for easily tracking the "least costly to recompute" added node in the
cache*/
type lcrNode struct {
	key   string
	entry Entry
	prev  *lcrNode
	next  *lcrNode
}

/*Lcr is a cache implementation adapting to cost of recomputation.
When full, it will always decide to evict the key with the lowest cost to recompute.*/
type Lcr struct {
	maxSize int
	length  int
	head    *lcrNode
	tail    *lcrNode
	lookup  map[string]*lcrNode
	debug   bool
}

/*KeyPresent is true if the key is in the cache right now*/
func (l *Lcr) KeyPresent(k string) bool {
	_, ok := l.lookup[k]
	return ok
}

func (l *Lcr) debugCache() {
	fmt.Println("CACHE STATE")
	dbg := ""
	node := l.head
	for {
		dbg = dbg + "->" + node.key + ":" + strconv.Itoa(node.entry.cost)
		node = node.next
		if node == nil {
			break
		}
	}
	fmt.Println(dbg)
}

func (l *Lcr) reorderList(node *lcrNode) {
	for {
		if node.entry.cost >= node.next.entry.cost {
			// swap positions
			if node.prev == nil {
				// node is currently HEAD
				newHead := node.next
				rightHead := newHead.next
				newHead.prev = nil
				node.next = rightHead
				node.prev = newHead
				newHead.next = node
				l.head = newHead
				if rightHead == nil {
					// node is now tail
					l.tail = node
					return
				}
				rightHead.prev = node
			} else {
				// node in the middle of list
				leftTail := node.prev
				swapNode := node.next
				rightHead := swapNode.next
				leftTail.next = swapNode
				swapNode.prev = leftTail
				swapNode.next = node
				node.prev = swapNode
				node.next = rightHead
				if rightHead == nil {
					// node is now tail
					l.tail = node
					return
				}
				rightHead.prev = node
			}
		} else {
			return
		}
	}
}

/*GetValue will return the entry if present in the lookup*/
func (l *Lcr) GetValue(k string) (Entry, error) {
	node, ok := l.lookup[k]
	if !ok {
		return Entry{}, errors.New("Key not present in lookup hash")
	}
	if l.debug {
		l.debugCache()
	}
	return node.entry, nil
}

/*SetValue inserts a new cache entry, evicting one if necessary*/
func (l *Lcr) SetValue(k string, v Entry) error {
	if l.length == 0 {
		// create list head/tail
		node := &lcrNode{entry: v, key: k}
		l.head = node
		l.tail = node
		l.lookup[k] = node
		l.length = 1
		if l.debug {
			l.debugCache()
		}
		return nil
	} else if l.length == l.maxSize {
		// evict one entry
		newNode := &lcrNode{entry: v, key: k}
		prevHead := l.head
		delete(l.lookup, prevHead.key)
		newHead := prevHead.next
		newHead.prev = nil
		l.head = newNode
		newNode.next = newHead
		newHead.prev = newNode
		l.lookup[k] = newNode
		l.reorderList(newNode)
		if l.debug {
			l.debugCache()
		}
		// length does not change
		return nil
	}
	// just grow the list
	newNode := &lcrNode{entry: v, key: k}
	oldHead := l.head
	newNode.next = oldHead
	oldHead.prev = newNode
	l.head = newNode
	l.lookup[k] = newNode
	l.reorderList(newNode)
	l.length++
	if l.debug {
		l.debugCache()
	}
	return nil
}

func newLcr(size int) *Lcr {
	lk := make(map[string]*lcrNode)
	return &Lcr{maxSize: size, length: 0, head: nil, tail: nil, lookup: lk, debug: false}
}

/*NewCache is a factory for building a cache implementation
of the requested strategy*/
func NewCache(cacheType string, size int) (Cache, error) {
	if cacheType == "NONE" {
		return &NoOp{}, nil
	} else if cacheType == "FIFO" {
		return newFifo(size), nil
	} else if cacheType == "LRU" {
		return newLru(size), nil
	} else if cacheType == "LFU" {
		return newLfu(size), nil
	} else if cacheType == "LCR" {
		return newLcr(size), nil
	} else if cacheType == "LECAR" {
		return newLecar(size), nil
	} else if cacheType == "CALECAR" {
		return newCalecar(size), nil
	}
	return &NoOp{}, errors.New("No cache exists of type '" + cacheType + "'")
}

repository: evizitei/CaLeCaR

repo_name: evizitei/CaLeCaR


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

@book{davison1997bootstrap,
  title={Bootstrap methods and their application},
  author={Davison, Anthony Christopher and Hinkley, David Victor},
  volume={1},
  year={1997},
  publisher={Cambridge university press}
}

@Book{marie,
  title = {Simulation studies in statistics},
  author = {Marie Davidian},
  year = {2005},
  url = {http://www4.stat.ncsu.edu/~davidian/st810a/simulation_handout.pdf},
}

@article{hallgren2013conducting,
  title={Conducting simulation studies in the R programming environment},
  author={Hallgren, Kevin A},
  journal={Tutorials in quantitative methods for psychology},
  volume={9},
  number={2},
  pages={43},
  year = {2013},
  publisher={NIH Public Access}
}

   @Manual{joseph,
    title = {Principles of Inferential Statistics in Medicine},
    author = {Lawrence Joseph},
    year = {2010},
    note = {EPIB 607},
    url = {http://www.medicine.mcgill.ca/epidemiology/Joseph/courses/EPIB-607/notes.pdf}
  }

@misc{david,
author = {David A. Stephens},
title = {MATH 680 - Computation Intensive Statistics course notes},
type = {Notes},
institution = {McGill University},
date = {2015},
url = {http://www.math.mcgill.ca/dstephens/}
}

@article{d1998tutorial,
  title={Tutorial in biostatistics: propensity score methods for bias reduction in the comparison of a treatment to a non-randomized control group},
  author={dAgostino, Ralph B},
  journal={Stat Med},
  volume={17},
  number={19},
  pages={2265--2281},
  year={1998}
}

@article{rosenbaum1983central,
  title={The central role of the propensity score in observational studies for causal effects},
  author={Rosenbaum, Paul R and Rubin, Donald B},
  journal={Biometrika},
  volume={70},
  number={1},
  pages={41--55},
  year={1983},
  publisher={Biometrika Trust}
}

@article{austin2011introduction,
  title={An introduction to propensity score methods for reducing the effects of confounding in observational studies},
  author={Austin, Peter C},
  journal={Multivariate behavioral research},
  volume={46},
  number={3},
  pages={399--424},
  year={2011},
  publisher={Taylor \& Francis}
}

@book{esl,
  title={The Elements of Statistical Learning (2nd edition)},
  author={Hastie and Tibshirani and Friedman},
  volume={2},
  year={2009},
  pages={763},
  publisher={Cambridge university press},
  url = {http://statweb.stanford.edu/~tibs/ElemStatLearn/}
}

@article{wang2015perils,
  title={The perils of quasi-likelihood information criteria},
  author={Wang, Yishu and Murphy, Orla and Turgeon, Maxime and Wang, ZhuoYu and Bhatnagar, Sahir R and Schulz, Juliana and Moodie, Erica EM},
  journal={Stat},
  volume={4},
  number={1},
  pages={246--254},
  year={2015},
  publisher={Wiley Online Library}
}

@article{tibshirani1996regression,
  title={Regression shrinkage and selection via the lasso},
  author={Tibshirani, Robert},
  journal={Journal of the Royal Statistical Society. Series B (Methodological)},
  pages={267--288},
  year={1996},
  publisher={JSTOR}
}

@book{efron1994introduction,
  title={An introduction to the bootstrap},
  author={Efron, Bradley and Tibshirani, Robert J},
  year={1994},
  publisher={CRC press}
}


text:
package handler

import (
	"fmt"
	"strconv"

	"github.com/labstack/echo"
	"github.com/luiz-mai/go-api-boilerplate/server/viewmodel"
	"github.com/luiz-mai/go-api-boilerplate/service"
	"github.com/pkg/errors"
)

func HandleGetToDos(todoService service.ToDoService) func(ctx echo.Context) error {
	return func(ctx echo.Context) error {
		todos, err := todoService.GetAll()
		if err != nil {
			return errors.New("Error while getting list of ToDos")
		}

		vm := viewmodel.ParseGetToDosResponse(todos)

		return responseOK(ctx, vm)
	}
}

func HandleGetToDo(todoService service.ToDoService) func(ctx echo.Context) error {
	return func(ctx echo.Context) error {

		id, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
		if err != nil {
			fmt.Println(err)
			return errors.New("Invalid id")
		}

		todo, err := todoService.GetByID(id)
		if err != nil {
			return errors.New("Error while getting list of ToDos")
		}

		vm := viewmodel.ParseGetToDoResponse(todo)

		return responseOK(ctx, vm)
	}
}

func HandleCreateToDo(todoService service.ToDoService) func(ctx echo.Context) error {
	return func(ctx echo.Context) error {

		var vm viewmodel.CreateToDoRequest
		err := ctx.Bind(&vm)
		if err != nil {
			fmt.Println(err)
			return errors.New("Error parsing request body")
		}

		todo := vm.Parse()
		err = todoService.Create(todo)
		if err != nil {
			fmt.Println(err)
			return errors.New("Error creating a new ToDo")
		}

		return responseNoContent(ctx)
	}
}

func HandleUpdateToDo(todoService service.ToDoService) func(ctx echo.Context) error {
	return func(ctx echo.Context) error {

		id, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
		if err != nil {
			fmt.Println(err)
			return errors.New("Invalid id")
		}

		var vm viewmodel.UpdateToDoRequest
		err = ctx.Bind(&vm)
		if err != nil {
			fmt.Println(err)
			return errors.New("Error parsing request body")
		}

		todo := vm.Parse()
		todo.ID = id

		err = todoService.Update(todo)
		if err != nil {
			fmt.Println(err)
			return errors.New("Error creating a new ToDo")
		}

		return responseNoContent(ctx)
	}
}

func HandleDeleteToDo(todoService service.ToDoService) func(ctx echo.Context) error {
	return func(ctx echo.Context) error {

		id, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
		if err != nil {
			fmt.Println(err)
			return errors.New("Invalid id")
		}

		err = todoService.Delete(id)
		if err != nil {
			fmt.Println(err)
			return errors.New("Error creating a new ToDo")
		}

		return responseNoContent(ctx)
	}
}

repository: tvacare/go-api-boilerplate

repo_name: tvacare/go-api-boilerplate

gha_license_id: MIT


text:
package kocha

// Flash represents a container of flash messages.
// Flash is for the one-time messaging between requests. It useful for
// implementing the Post/Redirect/Get pattern.
type Flash map[string]FlashData

// Get gets a value associated with the given key.
// If there is the no value associated with the key, Get returns "".
func (f Flash) Get(key string) string {
	if f == nil {
		return ""
	}
	data, exists := f[key]
	if !exists {
		return ""
	}
	data.Loaded = true
	f[key] = data
	return data.Data
}

// Set sets the value associated with key.
// It replaces the existing value associated with key.
func (f Flash) Set(key, value string) {
	if f == nil {
		return
	}
	data := f[key]
	data.Loaded = false
	data.Data = value
	f[key] = data
}

// Len returns a length of the dataset.
func (f Flash) Len() int {
	return len(f)
}

// deleteLoaded delete the loaded data.
func (f Flash) deleteLoaded() {
	for k, v := range f {
		if v.Loaded {
			delete(f, k)
		}
	}
}

// FlashData represents a data of flash messages.
type FlashData struct {
	Data   string // flash message.
	Loaded bool   // whether the message was loaded.
}


text:
DESCRIPTION = "An Amazon S3 Transfer Manager"
AUTHOR = "Amazon Web Services"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=b1e01b26bacfc2232046c90a330332b3"

inherit setuptools

PR = "r0"

RDEPENDS_${PN} = "\
	${PYTHON_PN}-botocore \
	${PYTHON_PN}-futures \
	${PYTHON_PN}-math \
	${PYTHON_PN}-lang \
	${PYTHON_PN}-logging \
	${PYTHON_PN}-io \
	${PYTHON_PN}-threading \
	${PYTHON_PN}-stringold \
	${PYTHON_PN}-pkgutil \
"

SRC_NAME = "s3transfer"

SRC_URI = "git://github.com/boto/${SRC_NAME}.git"
SRCREV = "61dd450e43432b016e55506cec3cf31c3c807e9b"

S = "${WORKDIR}/git"

repository: adammendoza/meta-iot-cloud

repo_name: adammendoza/meta-iot-cloud


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

inherit setuptools3
require python-lz4.inc

SRC_URI[md5sum] = "2a7d1d8669046c380ad69dbd9db4db94"
SRC_URI[sha256sum] = "440bbb039e15c09b049c0a8c1294978341d3fac943b83e04ff3f9e3b7ec0058b"

repository: jianchangfeng/meta-ros

repo_name: jianchangfeng/meta-ros


text:
#
#   Copyright (C) 2015 Pelagicore AB
#
#   SPDX-License-Identifier: MIT
#
DESCRIPTION = "common-api-c++-native"
HOMEPAGE = "http://www.pelagicore.com"
LICENSE = "MPL-2.0"
LIC_FILES_CHKSUM = "file://LICENSE;md5=815ca599c9df247a0c7f619bab123dad"
PR = "r0"

DEPENDS = "common-api-cmdline-codegen"

inherit cmake maven-properties

GIT_REPO = "git://github.com/Pelagicore/common-api-tools.git;protocol=https"
S = "${WORKDIR}/git"

SRC_URI = "${GIT_REPO};branch=master"
SRCREV = "81fe6698a95ba048ed2dbf1b557c884a97f939d6"
PV = "0.1+git${SRCREV}"

FILES_${PN} += "${datadir}/*"
ALLOW_EMPTY_${PN} = "1"

BBCLASSEXTEND = "native nativesdk"

repository: sashko/meta-bistro

repo_name: sashko/meta-bistro


text:
// Code generated by the Pulumi SDK Generator DO NOT EDIT.
// *** WARNING: Do not edit by hand unless you're certain you know what you are doing! ***

package ec2

import (
	"context"
	"reflect"

	"github.com/pulumi/pulumi-aws-native/sdk/go/aws/internal"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

// Resource Type definition for AWS::EC2::Instance
//
// Deprecated: Instance is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible.
type Instance struct {
	pulumi.CustomResourceState

	AdditionalInfo                    pulumi.StringPtrOutput                         `pulumi:"additionalInfo"`
	Affinity                          pulumi.StringPtrOutput                         `pulumi:"affinity"`
	AvailabilityZone                  pulumi.StringPtrOutput                         `pulumi:"availabilityZone"`
	BlockDeviceMappings               InstanceBlockDeviceMappingArrayOutput          `pulumi:"blockDeviceMappings"`
	CpuOptions                        InstanceCpuOptionsPtrOutput                    `pulumi:"cpuOptions"`
	CreditSpecification               InstanceCreditSpecificationPtrOutput           `pulumi:"creditSpecification"`
	DisableApiTermination             pulumi.BoolPtrOutput                           `pulumi:"disableApiTermination"`
	EbsOptimized                      pulumi.BoolPtrOutput                           `pulumi:"ebsOptimized"`
	ElasticGpuSpecifications          InstanceElasticGpuSpecificationArrayOutput     `pulumi:"elasticGpuSpecifications"`
	ElasticInferenceAccelerators      InstanceElasticInferenceAcceleratorArrayOutput `pulumi:"elasticInferenceAccelerators"`
	EnclaveOptions                    InstanceEnclaveOptionsPtrOutput                `pulumi:"enclaveOptions"`
	HibernationOptions                InstanceHibernationOptionsPtrOutput            `pulumi:"hibernationOptions"`
	HostId                            pulumi.StringPtrOutput                         `pulumi:"hostId"`
	HostResourceGroupArn              pulumi.StringPtrOutput                         `pulumi:"hostResourceGroupArn"`
	IamInstanceProfile                pulumi.StringPtrOutput                         `pulumi:"iamInstanceProfile"`
	ImageId                           pulumi.StringPtrOutput                         `pulumi:"imageId"`
	InstanceInitiatedShutdownBehavior pulumi.StringPtrOutput                         `pulumi:"instanceInitiatedShutdownBehavior"`
	InstanceType                      pulumi.StringPtrOutput                         `pulumi:"instanceType"`
	Ipv6AddressCount                  pulumi.IntPtrOutput                            `pulumi:"ipv6AddressCount"`
	Ipv6Addresses                     InstanceIpv6AddressArrayOutput                 `pulumi:"ipv6Addresses"`
	KernelId                          pulumi.StringPtrOutput                         `pulumi:"kernelId"`
	KeyName                           pulumi.StringPtrOutput                         `pulumi:"keyName"`
	LaunchTemplate                    InstanceLaunchTemplateSpecificationPtrOutput   `pulumi:"launchTemplate"`
	LicenseSpecifications             InstanceLicenseSpecificationArrayOutput        `pulumi:"licenseSpecifications"`
	Monitoring                        pulumi.BoolPtrOutput                           `pulumi:"monitoring"`
	NetworkInterfaces                 InstanceNetworkInterfaceArrayOutput            `pulumi:"networkInterfaces"`
	PlacementGroupName                pulumi.StringPtrOutput                         `pulumi:"placementGroupName"`
	PrivateDnsName                    pulumi.StringOutput                            `pulumi:"privateDnsName"`
	PrivateDnsNameOptions             InstancePrivateDnsNameOptionsPtrOutput         `pulumi:"privateDnsNameOptions"`
	PrivateIp                         pulumi.StringOutput                            `pulumi:"privateIp"`
	PrivateIpAddress                  pulumi.StringPtrOutput                         `pulumi:"privateIpAddress"`
	PropagateTagsToVolumeOnCreation   pulumi.BoolPtrOutput                           `pulumi:"propagateTagsToVolumeOnCreation"`
	PublicDnsName                     pulumi.StringOutput                            `pulumi:"publicDnsName"`
	PublicIp                          pulumi.StringOutput                            `pulumi:"publicIp"`
	RamdiskId                         pulumi.StringPtrOutput                         `pulumi:"ramdiskId"`
	SecurityGroupIds                  pulumi.StringArrayOutput                       `pulumi:"securityGroupIds"`
	SecurityGroups                    pulumi.StringArrayOutput                       `pulumi:"securityGroups"`
	SourceDestCheck                   pulumi.BoolPtrOutput                           `pulumi:"sourceDestCheck"`
	SsmAssociations                   InstanceSsmAssociationArrayOutput              `pulumi:"ssmAssociations"`
	SubnetId                          pulumi.StringPtrOutput                         `pulumi:"subnetId"`
	Tags                              InstanceTagArrayOutput                         `pulumi:"tags"`
	Tenancy                           pulumi.StringPtrOutput                         `pulumi:"tenancy"`
	UserData                          pulumi.StringPtrOutput                         `pulumi:"userData"`
	Volumes                           InstanceVolumeArrayOutput                      `pulumi:"volumes"`
}

// NewInstance registers a new resource with the given unique name, arguments, and options.
func NewInstance(ctx *pulumi.Context,
	name string, args *InstanceArgs, opts ...pulumi.ResourceOption) (*Instance, error) {
	if args == nil {
		args = &InstanceArgs{}
	}

	opts = internal.PkgResourceDefaultOpts(opts)
	var resource Instance
	err := ctx.RegisterResource("aws-native:ec2:Instance", name, args, &resource, opts...)
	if err != nil {
		return nil, err
	}
	return &resource, nil
}

// GetInstance gets an existing Instance resource's state with the given name, ID, and optional
// state properties that are used to uniquely qualify the lookup (nil if not required).
func GetInstance(ctx *pulumi.Context,
	name string, id pulumi.IDInput, state *InstanceState, opts ...pulumi.ResourceOption) (*Instance, error) {
	var resource Instance
	err := ctx.ReadResource("aws-native:ec2:Instance", name, id, state, &resource, opts...)
	if err != nil {
		return nil, err
	}
	return &resource, nil
}

// Input properties used for looking up and filtering Instance resources.
type instanceState struct {
}

type InstanceState struct {
}

func (InstanceState) ElementType() reflect.Type {
	return reflect.TypeOf((*instanceState)(nil)).Elem()
}

type instanceArgs struct {
	AdditionalInfo                    *string                               `pulumi:"additionalInfo"`
	Affinity                          *string                               `pulumi:"affinity"`
	AvailabilityZone                  *string                               `pulumi:"availabilityZone"`
	BlockDeviceMappings               []InstanceBlockDeviceMapping          `pulumi:"blockDeviceMappings"`
	CpuOptions                        *InstanceCpuOptions                   `pulumi:"cpuOptions"`
	CreditSpecification               *InstanceCreditSpecification          `pulumi:"creditSpecification"`
	DisableApiTermination             *bool                                 `pulumi:"disableApiTermination"`
	EbsOptimized                      *bool                                 `pulumi:"ebsOptimized"`
	ElasticGpuSpecifications          []InstanceElasticGpuSpecification     `pulumi:"elasticGpuSpecifications"`
	ElasticInferenceAccelerators      []InstanceElasticInferenceAccelerator `pulumi:"elasticInferenceAccelerators"`
	EnclaveOptions                    *InstanceEnclaveOptions               `pulumi:"enclaveOptions"`
	HibernationOptions                *InstanceHibernationOptions           `pulumi:"hibernationOptions"`
	HostId                            *string                               `pulumi:"hostId"`
	HostResourceGroupArn              *string                               `pulumi:"hostResourceGroupArn"`
	IamInstanceProfile                *string                               `pulumi:"iamInstanceProfile"`
	ImageId                           *string                               `pulumi:"imageId"`
	InstanceInitiatedShutdownBehavior *string                               `pulumi:"instanceInitiatedShutdownBehavior"`
	InstanceType                      *string                               `pulumi:"instanceType"`
	Ipv6AddressCount                  *int                                  `pulumi:"ipv6AddressCount"`
	Ipv6Addresses                     []InstanceIpv6Address                 `pulumi:"ipv6Addresses"`
	KernelId                          *string                               `pulumi:"kernelId"`
	KeyName                           *string                               `pulumi:"keyName"`
	LaunchTemplate                    *InstanceLaunchTemplateSpecification  `pulumi:"launchTemplate"`
	LicenseSpecifications             []InstanceLicenseSpecification        `pulumi:"licenseSpecifications"`
	Monitoring                        *bool                                 `pulumi:"monitoring"`
	NetworkInterfaces                 []InstanceNetworkInterface            `pulumi:"networkInterfaces"`
	PlacementGroupName                *string                               `pulumi:"placementGroupName"`
	PrivateDnsNameOptions             *InstancePrivateDnsNameOptions        `pulumi:"privateDnsNameOptions"`
	PrivateIpAddress                  *string                               `pulumi:"privateIpAddress"`
	PropagateTagsToVolumeOnCreation   *bool                                 `pulumi:"propagateTagsToVolumeOnCreation"`
	RamdiskId                         *string                               `pulumi:"ramdiskId"`
	SecurityGroupIds                  []string                              `pulumi:"securityGroupIds"`
	SecurityGroups                    []string                              `pulumi:"securityGroups"`
	SourceDestCheck                   *bool                                 `pulumi:"sourceDestCheck"`
	SsmAssociations                   []InstanceSsmAssociation              `pulumi:"ssmAssociations"`
	SubnetId                          *string                               `pulumi:"subnetId"`
	Tags                              []InstanceTag                         `pulumi:"tags"`
	Tenancy                           *string                               `pulumi:"tenancy"`
	UserData                          *string                               `pulumi:"userData"`
	Volumes                           []InstanceVolume                      `pulumi:"volumes"`
}

// The set of arguments for constructing a Instance resource.
type InstanceArgs struct {
	AdditionalInfo                    pulumi.StringPtrInput
	Affinity                          pulumi.StringPtrInput
	AvailabilityZone                  pulumi.StringPtrInput
	BlockDeviceMappings               InstanceBlockDeviceMappingArrayInput
	CpuOptions                        InstanceCpuOptionsPtrInput
	CreditSpecification               InstanceCreditSpecificationPtrInput
	DisableApiTermination             pulumi.BoolPtrInput
	EbsOptimized                      pulumi.BoolPtrInput
	ElasticGpuSpecifications          InstanceElasticGpuSpecificationArrayInput
	ElasticInferenceAccelerators      InstanceElasticInferenceAcceleratorArrayInput
	EnclaveOptions                    InstanceEnclaveOptionsPtrInput
	HibernationOptions                InstanceHibernationOptionsPtrInput
	HostId                            pulumi.StringPtrInput
	HostResourceGroupArn              pulumi.StringPtrInput
	IamInstanceProfile                pulumi.StringPtrInput
	ImageId                           pulumi.StringPtrInput
	InstanceInitiatedShutdownBehavior pulumi.StringPtrInput
	InstanceType                      pulumi.StringPtrInput
	Ipv6AddressCount                  pulumi.IntPtrInput
	Ipv6Addresses                     InstanceIpv6AddressArrayInput
	KernelId                          pulumi.StringPtrInput
	KeyName                           pulumi.StringPtrInput
	LaunchTemplate                    InstanceLaunchTemplateSpecificationPtrInput
	LicenseSpecifications             InstanceLicenseSpecificationArrayInput
	Monitoring                        pulumi.BoolPtrInput
	NetworkInterfaces                 InstanceNetworkInterfaceArrayInput
	PlacementGroupName                pulumi.StringPtrInput
	PrivateDnsNameOptions             InstancePrivateDnsNameOptionsPtrInput
	PrivateIpAddress                  pulumi.StringPtrInput
	PropagateTagsToVolumeOnCreation   pulumi.BoolPtrInput
	RamdiskId                         pulumi.StringPtrInput
	SecurityGroupIds                  pulumi.StringArrayInput
	SecurityGroups                    pulumi.StringArrayInput
	SourceDestCheck                   pulumi.BoolPtrInput
	SsmAssociations                   InstanceSsmAssociationArrayInput
	SubnetId                          pulumi.StringPtrInput
	Tags                              InstanceTagArrayInput
	Tenancy                           pulumi.StringPtrInput
	UserData                          pulumi.StringPtrInput
	Volumes                           InstanceVolumeArrayInput
}

func (InstanceArgs) ElementType() reflect.Type {
	return reflect.TypeOf((*instanceArgs)(nil)).Elem()
}

type InstanceInput interface {
	pulumi.Input

	ToInstanceOutput() InstanceOutput
	ToInstanceOutputWithContext(ctx context.Context) InstanceOutput
}

func (*Instance) ElementType() reflect.Type {
	return reflect.TypeOf((**Instance)(nil)).Elem()
}

func (i *Instance) ToInstanceOutput() InstanceOutput {
	return i.ToInstanceOutputWithContext(context.Background())
}

func (i *Instance) ToInstanceOutputWithContext(ctx context.Context) InstanceOutput {
	return pulumi.ToOutputWithContext(ctx, i).(InstanceOutput)
}

type InstanceOutput struct{ *pulumi.OutputState }

func (InstanceOutput) ElementType() reflect.Type {
	return reflect.TypeOf((**Instance)(nil)).Elem()
}

func (o InstanceOutput) ToInstanceOutput() InstanceOutput {
	return o
}

func (o InstanceOutput) ToInstanceOutputWithContext(ctx context.Context) InstanceOutput {
	return o
}

func (o InstanceOutput) AdditionalInfo() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.AdditionalInfo }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) Affinity() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.Affinity }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) AvailabilityZone() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.AvailabilityZone }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) BlockDeviceMappings() InstanceBlockDeviceMappingArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceBlockDeviceMappingArrayOutput { return v.BlockDeviceMappings }).(InstanceBlockDeviceMappingArrayOutput)
}

func (o InstanceOutput) CpuOptions() InstanceCpuOptionsPtrOutput {
	return o.ApplyT(func(v *Instance) InstanceCpuOptionsPtrOutput { return v.CpuOptions }).(InstanceCpuOptionsPtrOutput)
}

func (o InstanceOutput) CreditSpecification() InstanceCreditSpecificationPtrOutput {
	return o.ApplyT(func(v *Instance) InstanceCreditSpecificationPtrOutput { return v.CreditSpecification }).(InstanceCreditSpecificationPtrOutput)
}

func (o InstanceOutput) DisableApiTermination() pulumi.BoolPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.BoolPtrOutput { return v.DisableApiTermination }).(pulumi.BoolPtrOutput)
}

func (o InstanceOutput) EbsOptimized() pulumi.BoolPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.BoolPtrOutput { return v.EbsOptimized }).(pulumi.BoolPtrOutput)
}

func (o InstanceOutput) ElasticGpuSpecifications() InstanceElasticGpuSpecificationArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceElasticGpuSpecificationArrayOutput { return v.ElasticGpuSpecifications }).(InstanceElasticGpuSpecificationArrayOutput)
}

func (o InstanceOutput) ElasticInferenceAccelerators() InstanceElasticInferenceAcceleratorArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceElasticInferenceAcceleratorArrayOutput {
		return v.ElasticInferenceAccelerators
	}).(InstanceElasticInferenceAcceleratorArrayOutput)
}

func (o InstanceOutput) EnclaveOptions() InstanceEnclaveOptionsPtrOutput {
	return o.ApplyT(func(v *Instance) InstanceEnclaveOptionsPtrOutput { return v.EnclaveOptions }).(InstanceEnclaveOptionsPtrOutput)
}

func (o InstanceOutput) HibernationOptions() InstanceHibernationOptionsPtrOutput {
	return o.ApplyT(func(v *Instance) InstanceHibernationOptionsPtrOutput { return v.HibernationOptions }).(InstanceHibernationOptionsPtrOutput)
}

func (o InstanceOutput) HostId() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.HostId }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) HostResourceGroupArn() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.HostResourceGroupArn }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) IamInstanceProfile() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.IamInstanceProfile }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) ImageId() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.ImageId }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) InstanceInitiatedShutdownBehavior() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.InstanceInitiatedShutdownBehavior }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) InstanceType() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.InstanceType }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) Ipv6AddressCount() pulumi.IntPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.IntPtrOutput { return v.Ipv6AddressCount }).(pulumi.IntPtrOutput)
}

func (o InstanceOutput) Ipv6Addresses() InstanceIpv6AddressArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceIpv6AddressArrayOutput { return v.Ipv6Addresses }).(InstanceIpv6AddressArrayOutput)
}

func (o InstanceOutput) KernelId() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.KernelId }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) KeyName() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.KeyName }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) LaunchTemplate() InstanceLaunchTemplateSpecificationPtrOutput {
	return o.ApplyT(func(v *Instance) InstanceLaunchTemplateSpecificationPtrOutput { return v.LaunchTemplate }).(InstanceLaunchTemplateSpecificationPtrOutput)
}

func (o InstanceOutput) LicenseSpecifications() InstanceLicenseSpecificationArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceLicenseSpecificationArrayOutput { return v.LicenseSpecifications }).(InstanceLicenseSpecificationArrayOutput)
}

func (o InstanceOutput) Monitoring() pulumi.BoolPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.BoolPtrOutput { return v.Monitoring }).(pulumi.BoolPtrOutput)
}

func (o InstanceOutput) NetworkInterfaces() InstanceNetworkInterfaceArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceNetworkInterfaceArrayOutput { return v.NetworkInterfaces }).(InstanceNetworkInterfaceArrayOutput)
}

func (o InstanceOutput) PlacementGroupName() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.PlacementGroupName }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) PrivateDnsName() pulumi.StringOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.PrivateDnsName }).(pulumi.StringOutput)
}

func (o InstanceOutput) PrivateDnsNameOptions() InstancePrivateDnsNameOptionsPtrOutput {
	return o.ApplyT(func(v *Instance) InstancePrivateDnsNameOptionsPtrOutput { return v.PrivateDnsNameOptions }).(InstancePrivateDnsNameOptionsPtrOutput)
}

func (o InstanceOutput) PrivateIp() pulumi.StringOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.PrivateIp }).(pulumi.StringOutput)
}

func (o InstanceOutput) PrivateIpAddress() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.PrivateIpAddress }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) PropagateTagsToVolumeOnCreation() pulumi.BoolPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.BoolPtrOutput { return v.PropagateTagsToVolumeOnCreation }).(pulumi.BoolPtrOutput)
}

func (o InstanceOutput) PublicDnsName() pulumi.StringOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.PublicDnsName }).(pulumi.StringOutput)
}

func (o InstanceOutput) PublicIp() pulumi.StringOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringOutput { return v.PublicIp }).(pulumi.StringOutput)
}

func (o InstanceOutput) RamdiskId() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.RamdiskId }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) SecurityGroupIds() pulumi.StringArrayOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringArrayOutput { return v.SecurityGroupIds }).(pulumi.StringArrayOutput)
}

func (o InstanceOutput) SecurityGroups() pulumi.StringArrayOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringArrayOutput { return v.SecurityGroups }).(pulumi.StringArrayOutput)
}

func (o InstanceOutput) SourceDestCheck() pulumi.BoolPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.BoolPtrOutput { return v.SourceDestCheck }).(pulumi.BoolPtrOutput)
}

func (o InstanceOutput) SsmAssociations() InstanceSsmAssociationArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceSsmAssociationArrayOutput { return v.SsmAssociations }).(InstanceSsmAssociationArrayOutput)
}

func (o InstanceOutput) SubnetId() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.SubnetId }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) Tags() InstanceTagArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceTagArrayOutput { return v.Tags }).(InstanceTagArrayOutput)
}

func (o InstanceOutput) Tenancy() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.Tenancy }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) UserData() pulumi.StringPtrOutput {
	return o.ApplyT(func(v *Instance) pulumi.StringPtrOutput { return v.UserData }).(pulumi.StringPtrOutput)
}

func (o InstanceOutput) Volumes() InstanceVolumeArrayOutput {
	return o.ApplyT(func(v *Instance) InstanceVolumeArrayOutput { return v.Volumes }).(InstanceVolumeArrayOutput)
}

func init() {
	pulumi.RegisterInputType(reflect.TypeOf((*InstanceInput)(nil)).Elem(), &Instance{})
	pulumi.RegisterOutputType(InstanceOutput{})
}

repository: pulumi/pulumi-aws-native

repo_name: pulumi/pulumi-aws-native


text:
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

func upload(c echo.Context) error {
	p, err := c.FormParams()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(p)
	file, err := c.FormFile("file")
	if err != nil {
		fmt.Println("Error receiving file")
		return err
	}

	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	// Destination
	dst, err := os.Create(file.Filename)
	if err != nil {
		return err
	}
	defer dst.Close()

	// Copy
	if _, err = io.Copy(dst, src); err != nil {
		return err
	}
	fmt.Println("File ", file.Filename, "saved")
	return c.HTML(http.StatusOK, fmt.Sprintf("<p>File %s uploaded successfully", file.Filename))
}

func main() {
	e := echo.New()

	e.Use(middleware.Logger())
	//e.Use(middleware.Recover())

	e.Static("/", "public")
	e.POST("/upload", upload)

	e.Logger.Fatal(e.Start(":8082"))
}

repository: WahomeKezia/dataview

repo_name: WahomeKezia/dataview


text:
package medium

// Given a linked list, rotate the list to the right by k places, where k is non-negative.
//
// Example 1:
// Input: 1->2->3->4->5->NULL, k = 2
// Output: 4->5->1->2->3->NULL
// Explanation:
// rotate 1 steps to the right: 5->1->2->3->4->NULL
// rotate 2 steps to the right: 4->5->1->2->3->NULL
//
// Example 2:
// Input: 0->1->2->NULL, k = 4
// Output: 2->0->1->NULL
// Explanation:
// rotate 1 steps to the right: 2->0->1->NULL
// rotate 2 steps to the right: 1->2->0->NULL
// rotate 3 steps to the right: 0->1->2->NULL
// rotate 4 steps to the right: 2->0->1->NULL

func rotateRight(head *ListNode, k int) *ListNode {
	length := listLen(head)
	if length <= 1 || k == 0 {
		return head
	}

	rotate := k % length
	if rotate == 0 {
		return head
	}

	skip := length - rotate
	prev := head
	for i := 0; i < skip-1; i++ {
		prev = prev.Next
	}
	newHead := prev.Next
	prev.Next = nil
	last := newHead
	for last.Next != nil {
		last = last.Next
	}
	last.Next = head
	return newHead
}

func listLen(head *ListNode) int {
	len := 0
	for head != nil {
		len++
		head = head.Next
	}

	return len
}


text:
@article{chojnacki_expression_2013,
 abstract = {Helicobacter pylori colonization of gastric mucosa causes pain of unknown etiology in about 15-20\% of infected subjects. The aim of the present work was to determine the level of expression of enzymes involved in the synthesis of melatonin in gastric mucosa of asymptomatic and symptomatic H. pylori infected patients. To diagnose H. pylori infection, histological analysis and the urea breath test (UBT C13) were performed. The levels of mRNA expression of arylalkylamine-N-acetyltransferase (AA-NAT) and acetylserotonin methyltransferase (ASMT) were estimated in gastric mucosa with RT-PCR. The level of AA-NAT expression and AMST was decreased in H. pylori infected patients and was increased after H. pylori eradication. We conclude that decreased expression of melatonin synthesizing enzymes, AA-NAT and ASMT, in patients with symptomatic H. pylori infection returns to normal level after H. pylori eradication.},
 author = {Chojnacki, Cezary and Poplawski, Tomasz and Blasiak, Janusz and Chojnacki, Jan and Reiter, Russel J. and Klupinska, Grazyna},
 doi = {10.1155/2013/845032},
 issn = {2314-6141},
 journal = {BioMed research international},
 month = {jul},
 note = {MEDLINE:23936850},
 pages = {845032},
 title = {Expression of melatonin synthesizing enzymes in {Helicobacter} pylori infected gastric mucosa.},
 volume = {2013},
 year = {2013}
}

repository: naraoia/cv

repo_name: naraoia/cv


text:
SUMMARY = "Entity Manager"
DESCRIPTION = "Entity Manager provides d-bus configuration data \
and configures system sensors"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://LICENCE;md5=a6a4edad4aed50f39a66d098d74b265b"
DEPENDS = "boost \
           dbus \
           nlohmann-json \
           sdbusplus \
           valijson \
           ${PYTHON_PN}-jsonschema-native \
"
SRCREV = "d0eb129180f8849026e2cd48ddf1152e51ef25b7"
PACKAGECONFIG ??= "ipmi-fru"
PACKAGECONFIG[ipmi-fru] = "-Dfru-device=true, -Dfru-device=false, i2c-tools,"
PV = "0.1+git${SRCPV}"

SRC_URI = "git://github.com/openbmc/entity-manager.git;branch=master;protocol=https \
           file://blocklist.json \
          "

S = "${WORKDIR}/git"
SYSTEMD_PACKAGES = "${PN} ${EXTRA_ENTITY_MANAGER_PACKAGES}"
SYSTEMD_SERVICE:${PN} = "xyz.openbmc_project.EntityManager.service"
SYSTEMD_SERVICE:fru-device = "xyz.openbmc_project.FruDevice.service"
SYSTEMD_AUTO_ENABLE:fru-device:ibm-power-cpu = "disable"

inherit pkgconfig meson systemd python3native

EXTRA_OEMESON = "-Dtests=disabled"
EXTRA_ENTITY_MANAGER_PACKAGES = " \
    ${@bb.utils.contains('PACKAGECONFIG', 'ipmi-fru', 'fru-device', '', d)} \
    "

do_install:append() {
    install -D ${WORKDIR}/blocklist.json ${D}${datadir}/${BPN}/blacklist.json
}

FILES:${PN} += " \
    ${datadir}/dbus-1/system-services/xyz.openbmc_project.EntityManager.service \
    "
FILES:fru-device = "${bindir}/fru-device ${datadir}/${BPN}/blacklist.json"

PACKAGE_BEFORE_PN = "${EXTRA_ENTITY_MANAGER_PACKAGES}"

repository: openbmc/openbmc

repo_name: openbmc/openbmc

gha_license_id: NOASSERTION

gha_language: Python


text:
/*
	Write an in-place function that squashes each run of adjacent Unicode spaces
	(see `unicode.IsSpace`) in a UTF-8-encoded `[]byte` slice into a single ASCII space.
*/

package main

import (
	"fmt"
	"unicode"
)

func main() {
	b := []byte("a  b      d\n\t   \ras\n\td   ")
	combineSpaces(&b)
	fmt.Printf("%s\n", b)
}

func combineSpaces(b *[]byte) {
	for i := 0; i < len(*b) - 1; {
		if unicode.IsSpace(rune((*b)[i])) {
			if unicode.IsSpace(rune((*b)[i+1])) {
				(*b)[i] = ' ' // rune(int32) automatically casted to byte(uint8)
				if i + 2 < len(*b) - 1 {
					*b = append((*b)[:i+1], (*b)[i+2:]...)
				} else {
					*b = (*b)[:i+1]
				}
			} else {
				i++
			}
		} else {
			i++
		}
	}
}

repository: zzossig/gopl

repo_name: zzossig/gopl


text:
@inproceedings{mukherjee2019fault,
 author = {Mukherjee, Sohom and Dutta, Arindam and Ghosh, Saradindu},
 booktitle = {TENCON 2019-2019 IEEE Region 10 Conference (TENCON)},
 organization = {IEEE},
 pages = {1547--1552},
 title = {Fault Classification in Three Phase Self-Excited Induction Generators using Deep Neural Networks},
 year = {2019}
}

repository: mukherjeesohom/academic-kickstart

repo_name: mukherjeesohom/academic-kickstart