text:
package main

import (
	"fmt"
	"io"
	"os"

	"net"
	"reflect"
	"strconv"
	"strings"
	"time"

	gopb "gameserver-997/pb/gopb"
	"gameserver-997/server/base/logger"
	"gameserver-997/unit_test/fnet"

	"github.com/golang/protobuf/proto"
	"github.com/gorilla/websocket"
)

//封装网络
type TcpClient struct {
	connection fnet.IConn
	addr       string
	stopChan   chan struct{}
}

func (this *TcpClient) Start() {

}

//封装hangler
type Handler struct {
	Apis     map[uint32]reflect.Value
	DataPack *fnet.PBDataPack
}

func (this *Handler) AddRouter(router interface{}) {
	value := reflect.ValueOf(router)
	tp := reflect.TypeOf(router)
	for i := 0; i < value.NumMethod(); i++ {
		name := tp.Method(i).Name
		if name[0:2] != "On" {
			continue
		}
		name = name[2:]
		k := strings.Split(name, "_")
		index, err := strconv.Atoi(k[1])
		if err != nil {
			panic("error api: " + name)
		}
		this.Apis[uint32(index)] = value.Method(i)
		fmt.Println("add router ", name)
	}
}

func (this *Handler) HandleClient(client *TcpClient) {
	for {
		headdata := make([]byte, this.DataPack.GetHeadLen())
		if _, err := io.ReadFull(client.connection, headdata); err != nil {
			fmt.Println("error:", err.Error())
			close(client.stopChan)
			return
		}
		pkgHead, err := this.DataPack.Unpack(headdata)
		fmt.Println("pkgHead: ", pkgHead)
		if err != nil {
			fmt.Println("error:", err.Error())
			close(client.stopChan)
			return
		}
		//data
		pkg := pkgHead.(*fnet.PkgData)
		if pkg.Len > 0 {
			pkg.Data = make([]byte, pkg.Len)
			if _, err := io.ReadFull(client.connection, pkg.Data); err != nil {
				fmt.Println("error:", err.Error())
				close(client.stopChan)
				return
			}
		}
		fmt.Println("pkg: ", pkg)
		if f, ok := this.Apis[pkg.MsgId]; ok {
			f.Call([]reflect.Value{reflect.ValueOf(pkg.Data)})
		} else {
			fmt.Println("received message no handler: ", pkg.MsgId)
		}
	}
}

type NewApi struct {
	reqId uint
}

func (this *NewApi) HandShake(connection fnet.IConn) {
	pkg := fnet.BuildPackage(fnet.PKG_HANDSHAKE, 0, nil)
	bytes := fnet.WritePackage(pkg)
	fmt.Println("before write write")
	connection.Write(bytes)
}

var heartTime int64 = 0

func (this *NewApi) HeartBeat(connection fnet.IConn) {
	ticker := time.NewTicker(time.Millisecond * 5000)
	go func() {
		for {
			select {
			case <-ticker.C:
				// if heartTime == 0 {
				// 	heartTime = time.Now().UnixNano() / 1000000
				// } else {
				// 	fmt.Printf("hearttime is not zero")
				// }
				pkg := fnet.BuildPackage(fnet.PKG_HEARTBEAT, 0, nil)
				bytes := fnet.WritePackage(pkg)
				connection.Write(bytes)
			}
		}
	}()
}

func (this *NewApi) GetNetAddr(connection fnet.IConn) {
	this.reqId++
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, "Net_Addr", nil)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
}

func (this *NewApi) OnVersion_Addr(data []byte) {
	msg := &gopb.ResVersionAddr{}
	if err := proto.Unmarshal(data, msg); err == nil {
		fmt.Println("Onnetaddr success\n", msg)
	} else {
		fmt.Printf("Onnetaddr %v\n fauled", data)
	}
}

// func (this *NewApi) Login(connection fnet.IConn, user string) {
// 	info := &gopb.ReqNetLogin{
// 		Uid:   user,
// 		Token: "pass0",
// 	}
// 	this.reqId++
// 	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, "Net_Login", info)
// 	msgData, _ := fnet.MsgEncode(msg)
// 	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
// 	bytes := fnet.WritePackage(pkg)
// 	connection.Write(bytes)
// 	fmt.Println("Login time: ", time.Now().UnixNano()/1000)
// }

func GetRouteName(obj interface{}) (string, string) {
	typeString := reflect.TypeOf(obj).String()
	typeString = typeString[5:]
	pfStart := -1
	serverNameStart := -1
	interNameStart := -1
	for i := 0; i < len(typeString); i++ {
		if typeString[i] >= 65 && typeString[i] <= 90 {
			//首字母大写
			if pfStart < 0 {
				pfStart = i
				continue
			}
			if serverNameStart < 0 {
				serverNameStart = i
				continue
			}

			if interNameStart < 0 {
				interNameStart = i
				break
			}
		}
	}

	pfStr := typeString[pfStart:serverNameStart]
	serverStr := typeString[serverNameStart:interNameStart]
	interStr := typeString[interNameStart:]
	routeName := serverStr + "_" + interStr
	fmt.Println("[GetRouteName]: ", routeName)

	return pfStr, routeName
}

func (this *NewApi) Net_Login(connection fnet.IConn, username string, pwd string) {
	logger.Fatal("start login test: ", time.Now().UnixNano()/1000)
	info := &gopb.ReqNetLogin{Username: username, Password: pwd}
	_, routeName := GetRouteName(info)
	this.reqId++
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, routeName, info)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
	logger.Fatal("login test: ", time.Now().UnixNano()/1000)
}

func (this *NewApi) Net_EnterMatchQueue(connection fnet.IConn) {
	logger.Info("Net_EnterMatchQueue: ", time.Now().UnixNano()/1000)
	info := &gopb.ReqNetEnterMatchQueue{Level: 1}
	_, routeName := GetRouteName(info)
	this.reqId++
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, routeName, info)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
	logger.Info("Net_EnterMatchQueue: ", time.Now().UnixNano()/1000)
}

func (this *NewApi) Net_CreateTimeRoom(connection fnet.IConn) {
	info := &gopb.ReqNetCreateRoom{PlayMod: "richMan", Mac: "18-93-7F-E1-8D-CD"}
	this.reqId++
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, "Net_CreateTimeRoom", info)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
	fmt.Println("CreateRoom time: ", time.Now().UnixNano()/1000)
}

func (this *NewApi) Net_EnterRoom(connection fnet.IConn, uid, roomId string) {
	info := &gopb.ReqNetEnterRoom{Token: uid, DeviceId: roomId}
	this.reqId++
	fmt.Println(this.reqId, "+++++++++++++++++++")
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, "EnterTimeRoom", info)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
}

func (this *NewApi) Game_RandomAward(connection fnet.IConn) {
	info := &gopb.ReqGamRandomAward{Start: 18, Steps: 1}
	this.reqId++
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, "Game_RandomAward", info)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
}

func (this *NewApi) Game_PlayerReady(connection fnet.IConn) {
	this.reqId++
	info := &gopb.ReqGameFPlayerReday{Select: []string{"2_0_1_2"}}
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, "Game_PlayerReady", info)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
}

func (this *NewApi) Game_SyncScore(connection fnet.IConn) {
	info := &gopb.ReqCommonArgs{Args: make([]*gopb.ReqCommonArg, 1)}
	info.Args[0] = &gopb.ReqCommonArg{
		StrVal1: "5f9bd3f7e8a5671dccc580b5",
		IntVal1: 210,
		IntVal2: 0,
		IntVal3: 0,
	}
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, "Game_SyncResult", info)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
}

func (this *NewApi) SendCommand(connection fnet.IConn, command string) {
	this.reqId++
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, command, nil)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
}

func (this *NewApi) SendFrame(connection fnet.IConn, i int32) {
	this.reqId++
	info := &gopb.ReqGameSyncFCommand{EpFrame: i, Uid: "11111", Ctype: 2, ParamList: []int32{1}}
	msg := fnet.BuildMsg(fnet.MSG_REQUEST, this.reqId, "Game_SyncFCommand", info)
	msgData, _ := fnet.MsgEncode(msg)
	pkg := fnet.BuildPackage(fnet.PKG_DATA, len(msgData), msgData)
	bytes := fnet.WritePackage(pkg)
	connection.Write(bytes)
}

var lastSererTime int64
var lastCliTime int64
var frameTime int64 = 0
var loginTime int64 = 0

func (this *NewApi) OnHandleData(route string, data []byte, connection fnet.IConn) {
	var msg proto.Message
	switch route {
	case "Net_Login":
		msg = &gopb.ResNetLogin{}
	case "Net_CreateRoom":
		msg = &gopb.ResNetCreateFRoom{}
	case "Net_CreateStateRoom":
		msg = &gopb.ResNetCreateSRoom{}
	case "Net_EnterStateRoom":
		msg = &gopb.ResNetEnterSRoom{}
	case "Net_CreateTimeRoom":
		msg = &gopb.ResNetCreateSRoom{}

	case "OnPlayerWaiting":
		msg = &gopb.PlayerInfo{}
	case "OnGameEnd":
		msg = &gopb.OnGameEnd{}
	case "OnPlayerEnter":
		msg = &gopb.OnPlayerEnterFRoom{}
	case "OnPlayerClientEnter":
		msg = &gopb.OnPlayerClientEnter{}
	case "OnPlayerReady":
		msg = &gopb.OnPlayerReady{}
	case "OnAllPlayerReady":
		// heartTime = time.Now().UnixNano() / 1000000
		// fmt.Println("send gameoktostart: ", time.Now().UnixNano()/1000000)
		this.SendCommand(connection, "Game_OkToStart")
		// loginTime = time.Now().Unix()
		// this.Game_SyncScore(connection)
		return
	case "OnFrame":
		if loginTime > 0 && time.Now().Unix()-loginTime > 30 {
			loginTime = 0
			this.Game_SyncScore(connection)
		}
		fmt.Printf("frameTime: %d\n", time.Now().UnixNano()/1000000-frameTime)
		frameTime = time.Now().UnixNano() / 1000000
		msg = &gopb.OnFrame{}
	case "HeartBeat":
		// fmt.Printf("heartBeat cost %d\n", time.Now().UnixNano()/1000000-heartTime)
		// heartTime = time.Now().UnixNano() / 1000000
		return
	case "Game_OkToStart":
		msg = &gopb.ResError{}
		fmt.Printf("heartBeat cost %d\n", time.Now().UnixNano()/1000000-heartTime)
		fallthrough
	case "Game_RandomAward":
		msg = &gopb.ResGamRandomAward{}
	default:
		msg = &gopb.ResError{}
	}
	if err := proto.Unmarshal(data, msg); err == nil {
		logger.Info("handledata", route, msg, time.Now().UnixNano()/1000000, data)
	} else {
		logger.Error("handledata error %s %v %+v\n", route, data, err)
	}
}

func main() {
	connection, err := dialWebSocket()
	if err != nil {
		os.Exit(1)
	}

	//---------------------pkg msg两层协议
	protocol := fnet.NewProtocol()
	api := &NewApi{}
	protocol.AddRouter(api)
	ackChan := make(chan struct{})
	go protocol.HandleConnection(connection, ackChan)
	api.HandShake(connection)
	api.HeartBeat(connection)
	if len(os.Args) < 2 {
		logger.Error("need args!!!")
		return
	}
	if os.Args[1] == "0" {
		api.Net_Login(connection, "luoyonglin2", "111222333")
		api.Net_EnterMatchQueue(connection)

	} else if os.Args[1] == "1" {
		api.Net_Login(connection, "luoyonglin3", "111222333")
		api.Net_EnterMatchQueue(connection)
	} else if os.Args[1] == "2" {
		api.Net_Login(connection, "luoyonglin3", "111222333")
		api.Net_EnterMatchQueue(connection)
	} else if os.Args[1] == "3" {

		//api.Net_EnterRoom(connection, "", "30-9C-23-50-CB-73")
	} else {
		runAis()
	}
	// api.Game_SyncState(connection)
	<-ackChan
}

var uids = []string{"5f44762df1f8ed333c281078", "5f448e9af1f8ed333c281079", "5f44d621f1f8ed4b5f0fb26e", "5f44d1aaf1f8ed4b5f0fb26c", "5f44d61ef1f8ed4b5f0fb26d"}

func runAis() {
	for i := 0; i < 7; i++ {
		go runAi(uids[i%5])
	}
	ch := make(chan struct{})
	<-ch
}

func runAi(uid string) {
	for {
		connection, err := dialWebSocket()
		if err != nil {
			return
		}
		protocol := fnet.NewProtocol()
		api := &NewApi{reqId: 100}
		protocol.AddRouter(api)
		ackChan := make(chan struct{})
		go protocol.HandleConnection(connection, ackChan)
		api.HandShake(connection)
		api.HeartBeat(connection)
		api.Net_EnterRoom(connection, uid, "30-9C-23-50-CB-73")
		fmt.Println(api.reqId, "+++++++++++")
		time.Sleep(time.Second * 150)
		connection.Close()
		time.Sleep(time.Second * 50)
	}
}

func dialTcp(addr string) (fnet.IConn, error) {
	servAddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		fmt.Println("resolve addr error ", servAddr, err.Error())
		return nil, err
	}
	connection, err := net.DialTCP("tcp", nil, servAddr)
	if err != nil {
		fmt.Println("dial tcp error: ", err.Error(), servAddr)
		return nil, err
	}
	return connection, nil
}

func dialWebSocket() (fnet.IConn, error) {
	var dialer *websocket.Dialer
	conn, _, err := dialer.Dial("ws://127.0.0.1:8080/ws", nil)
	if err != nil {
		fmt.Printf("dial websocket err %+v", err)
		return nil, err
	}
	wsConn := fnet.NewWsConn(conn)
	return wsConn, nil
}

repository: lwcbest/gogame

repo_name: lwcbest/gogame


text:
@article{MacDonald-2018-Water,
    title = "Water and energy fluxes over northern prairies as affected by chinook winds and winter precipitation",
    author = "MacDonald, Matthew K.  and
      Pomeroy, John W.  and
      Essery, Richard L.H.",
    journal = "Agricultural and Forest Meteorology, Volume 248",
    volume = "248",
    year = "2018",
    publisher = "Elsevier BV",
    url = "https://aclanthology.org/G18-76001",
    doi = "10.1016/j.agrformet.2017.10.025",
    pages = "372--385",
    abstract = "Abstract Chinooks are the North American variety of foehn: strong, warm and dry winds that descend lee mountain slopes. The strong wind speeds, high temperatures and substantial humidity deficits have been hypothesized to remove important prairie near-surface water storage from agricultural fields via evaporation, sublimation and blowing snow, as well as change the phase of near surface water via snowmelt and ground thaw. This paper presents observations of surface energy and water balances from eddy covariance instrumentation deployed at three open sites in southern Alberta, Canada during winter 2011{--}2012. Energy balances, snow and soil moisture budgets of three select chinook events were analysed in detail. These three events ranged in duration from two to nine days, and are representative of winter through early spring chinooks. Precipitation data from gauges and reanalyses (CaPA and ERA-interim) were used to assess water balances. Variations in precipitation and snowpacks caused the greatest differences in energy and water balances. Cumulative winter precipitation varied by a factor of two over the three sites: heaviest at the more northern site immediately east of the Rocky Mountains and lightest at the easternmost and southernmost site. The temporal progression of chinook-driven surface water loss is explained, beginning with strong blowing snow events through to evaporation of meltwater as snowpacks disappear. At the two sites with considerable winter precipitation and snowcover, large upward latent heat fluxes, often exceeding 100~W~m−2, were driven by downward sensible heat fluxes but were unrelated to net radiation. Conversely, at the southernmost site with little snowcover, upward latent heat fluxes were much smaller (less than 50~W~m−2) and were associated with periods of positive net radiation. Upward sensible heat fluxes during periods of positive net radiation were observed at this site throughout winter, but were not observed at the more northerly sites until March when the snowcovers ablated. Daily sublimation plus evaporation rates during chinooks at the sites with heaviest and lightest precipitation were 1.3{--}2.1~mm/day and 0.1{--}0.3~mm/day, respectively. Evaporation of soil water occurred while soils were partially to fully unfrozen in November. There was little change in soil water content between fall freeze-up and spring thaw (December through most of March), indicating that over-winter infiltration was balanced by soil water evaporation and both terms were likely to be small. Winter precipitation resulted in only 2{\%} to 4{\%} increases in near-surface water storage at the more northern sites with greater precipitation, whereas there was a net loss over winter at the southernmost site.",
}

repository: gwf-uwaterloo/gwf-publications

license_type: permissive

repo_name: gwf-uwaterloo/gwf-publications

branch_name: refs/heads/main

gha_language: Python

extension: bib


text:
@article{ch2019resolving,
  title={Resolving Marker Pose Ambiguity by Robust Rotation Averaging with Clique Constraints},
  author={Ch'ng, Shin-Fang and Sogi, Naoya and Purkait, Pulak and Chin, Tat-Jun and Fukui, Kazuhiro},
  journal={arXiv preprint arXiv:1909.11888},
  year={2019}
}

license: MIT

repository: sfchng/academic-kickstart

repo_name: sfchng/academic-kickstart

branch_name: refs/heads/master

gha_license_id: MIT


text:
package database

import (
	"fmt"
)

// UserStore implements database operations on `users`.
type UserStore struct {
	*DataStore
}

// ByID returns a composable query for filtering by _table_.group_id.
func (s *UserStore) ByID(id int64) *DB {
	return s.Where(s.tableName+".group_id = ?", id)
}

const deleteWithTrapsBatchSize = 1000

// DeleteTemporaryWithTraps deletes temporary users who don't have active sessions.
// It also removes linked rows in the tables:
//  1. [`filters`, `sessions`, `refresh_tokens`]
//     having `user_id` = `users.group_id`;
//  2. `answers` having `author_id`/`participant_id` = `users.group_id`;
//  3. [`permissions_granted`, `permissions_generated`, `attempts`]
//     having `group_id` = `users.group_id`;
//  4. [`attempts`, `results`]
//     having `participant_id` = `users.group_id`;
//  5. `groups_groups` having `parent_group_id` or `child_group_id` equal to `users.group_id`;
//  6. `groups_ancestors` having `ancestor_group_id` or `child_group_id` equal to `users.group_id`;
//  7. [`groups_propagate`, `groups`] having `id` equal to `users.group_id`.
func (s *UserStore) DeleteTemporaryWithTraps() (err error) {
	defer recoverPanics(&err)

	s.executeBatchesInTransactions(func(store *DataStore) int {
		userScope := store.Users().
			Joins("LEFT JOIN sessions ON sessions.user_id = users.group_id AND NOW() < sessions.expires_at").
			Where("sessions.user_id IS NULL").Where("temp_user = 1")
		return store.Users().deleteWithTraps(userScope)
	})
	return nil
}

// DeleteWithTraps deletes a given user. It also removes linked rows in the same way as DeleteTemporaryWithTraps.
func (s *UserStore) DeleteWithTraps(user *User) (err error) {
	return s.InTransaction(func(store *DataStore) error {
		deleteOneBatchOfUsers(store.DB, []int64{user.GroupID})
		store.GroupGroups().createNewAncestors()
		return nil
	})
}

// DeleteWithTrapsByScope deletes users matching the given scope.
// It also removes linked rows in the same way as DeleteTemporaryWithTraps.
func (s *UserStore) DeleteWithTrapsByScope(scopeFunc func(store *DataStore) *DB) (err error) {
	defer recoverPanics(&err)

	s.executeBatchesInTransactions(func(store *DataStore) int {
		scope := scopeFunc(store)
		return store.Users().deleteWithTraps(scope)
	})
	return nil
}

func (s *UserStore) executeBatchesInTransactions(f func(store *DataStore) int) {
	for {
		var usersDeleted int
		mustNotBeError(s.InTransaction(func(store *DataStore) error {
			usersDeleted = f(store)
			return nil
		}))
		if usersDeleted < deleteWithTrapsBatchSize {
			return
		}
	}
}

// deleteWithTraps deletes the first deleteWithTrapsBatchSize users satisfying the scope's conditions
// and all the users' stuff.
func (s *UserStore) deleteWithTraps(userScope *DB) int {
	userScope.mustBeInTransaction()

	userIDs := make([]int64, 0, deleteWithTrapsBatchSize)

	mustNotBeError(
		userScope.WithWriteLock().Select("group_id").Limit(deleteWithTrapsBatchSize).
			ScanIntoSlices(&userIDs).Error())

	if len(userIDs) == 0 {
		return 0
	}

	deleteOneBatchOfUsers(userScope, userIDs)
	s.GroupGroups().createNewAncestors()

	return len(userIDs)
}

func deleteOneBatchOfUsers(db *DB, userIDs []int64) {
	db.mustBeInTransaction()

	// we should delete from groups_groups explicitly in order to invoke triggers on groups_groups
	executeDeleteQuery(db, "groups_groups", "WHERE parent_group_id IN (?)", userIDs)
	// deleting from `groups` triggers deletion from
	// `groups_propagate`, `groups_groups`, `groups_ancestors`, `group_pending_requests`, `group_membership_changes`,
	// `permissions_granted`, `permissions_generated", `attempts`, `results`,
	// `users`, `answers`, `filters`, `sessions`, `refresh_tokens`
	executeDeleteQuery(db, "groups", "WHERE id IN (?)", userIDs)
}

func executeDeleteQuery(s *DB, table, condition string, args ...interface{}) {
	mustNotBeError(
		s.Exec(fmt.Sprintf("DELETE %[1]s FROM %[1]s ", QuoteName(table))+condition, args...).Error())
}

repository: France-ioi/AlgoreaBackend

repo_name: France-ioi/AlgoreaBackend

gha_language: Gherkin

extension: go


text:
package commands

import (
	"io"
	"os"

	"gopkg.in/urfave/cli.v1"

	colorable "github.com/mattn/go-colorable"

	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/log/term"

	tmlog "github.com/tendermint/tendermint/libs/log"
)

var glogger *log.GlogHandler

func init() {
	usecolor := term.IsTty(os.Stderr.Fd()) && os.Getenv("TERM") != "dumb"
	output := io.Writer(os.Stderr)
	if usecolor {
		output = colorable.NewColorableStderr()
	}
	glogger = log.NewGlogHandler(log.StreamHandler(output, log.TerminalFormat(usecolor)))
}

// Setup sets up the logging infrastructure
// #unstable
func Setup(ctx *cli.Context) error {
	glogger.Verbosity(log.Lvl(ctx.GlobalInt(VerbosityFlag.Name)))
	log.Root().SetHandler(glogger)

	return nil
}

// ---------------------------
// TendermintLogger - wraps the logger in tmlibs

// Interface assertions
var _ tmlog.Logger = (*tendermintLogger)(nil)

type tendermintLogger struct {
	keyvals []interface{}
}

// TendermintLogger returns a new instance of an tendermint logger. With() should
// be called upon the returned instance to set default keys
// #unstable
func TendermintLogger() tmlog.Logger {
	logger := tendermintLogger{keyvals: make([]interface{}, 0)}
	return logger
}

// Debug proxies everything to the go-ethereum logging facilities
// #unstable
func (l tendermintLogger) Debug(msg string, ctx ...interface{}) {
	ctx = append(l.keyvals, ctx...)
	log.Debug(msg, ctx...)
}

// Info proxies everything to the go-ethereum logging facilities
// #unstable
func (l tendermintLogger) Info(msg string, ctx ...interface{}) {
	ctx = append(l.keyvals, ctx...)
	log.Info(msg, ctx...)
}

// Error proxies everything to the go-ethereum logging facilities
// #unstable
func (l tendermintLogger) Error(msg string, ctx ...interface{}) {
	ctx = append(l.keyvals, ctx...)
	log.Error(msg, ctx...)
}

// With proxies everything to the go-ethereum logging facilities
// #unstable
func (l tendermintLogger) With(ctx ...interface{}) tmlog.Logger {
	l.keyvals = append(l.keyvals, ctx...)

	return l
}

repository: songyuqing-cloud/UNetwork

repo_name: songyuqing-cloud/UNetwork


text:
SUMMARY = "Remote control and meeting solution"
HOMEPAGE = "https://www.teamviewer.com/"
LICENSE = "TeamViewer"
LIC_FILES_CHKSUM = "file://opt/teamviewer/doc/License.txt;md5=72c21b75397df780de34b238c61c86e4"

SRC_URI = "http://download.teamviewer.com/download/linux/version_11x/teamviewer-host_armhf.deb"
SRC_URI[md5sum] = "77e9bcf2874090bf2288dacf6b6cb901"
SRC_URI[sha256sum] = "ba48a3ffabbf233091aba62333e6c9a1c16be4838e6b506596f181384dac2a2d"

S = "${WORKDIR}"

COMPATIBLE_HOST = 'arm.*-linux'

DEPENDS = " \
    qtbase \
    qtx11extras \
    qtwebkit \
"

inherit distro_features_check systemd gtk-icon-cache

REQUIRED_DISTRO_FEATURES = "x11"

do_install() {
    cp -r ${WORKDIR}/opt ${D}
    cp -r ${WORKDIR}/usr ${D}
    cp -r ${WORKDIR}/var ${D}

    # libdepend is some x86 tool
    rm -f ${D}/opt/teamviewer/tv_bin/script/libdepend

    # systemd
    install -d ${D}${systemd_system_unitdir}
    mv ${D}/opt/teamviewer/tv_bin/script/teamviewerd.service ${D}${systemd_system_unitdir}/teamviewerd.service

    # desktop+icon
    install -d ${D}${datadir}/applications
    ln -sf /opt/teamviewer/tv_bin/desktop/com.teamviewer.teamviewer-host.desktop ${D}${datadir}/applications/teamviewer-host.desktop
    install -d ${D}${datadir}/icons/hicolor/48x48/apps
    ln -sf /opt/teamviewer/tv_bin/desktop/teamviewer.png ${D}${datadir}/icons/hicolor/48x48/apps/teamviewer.png
}

SYSTEMD_SERVICE_${PN} = "teamviewerd.service"

FILES_${PN} += " \
    opt \
"

RDEPENDS_${PN} += "bash"

INSANE_SKIP_${PN} = "already-stripped ldflags"

repository: twoerner/meta-raspi-light

repo_name: twoerner/meta-raspi-light

extension: bb


text:
@incollection{MOC+18,
  author = {Sara Magliacane and Thijs van Ommen and Tom Claassen and Stephan Bongers and Philip Versteeg and Joris M. Mooij},
  title = {Domain Adaptation by Using Causal Inference to Predict Invariant Conditional Distributions},
  booktitle = {Advances in Neural Information Processing Systems 31 ({N}eur{IPS}2018)},
  location = {Montr\'{e}al, Canada},
  editor = {S. Bengio and H. Wallach and H. Larochelle and K. Grauman and N. Cesa-Bianchi and R. Garnett},
  publisher = {Curran Associates, Inc.},
  pages = {10869–-10879},
  year = 2018,
  url = {http://papers.nips.cc/paper/8282-domain-adaptation-by-using-causal-inference-to-predict-invariant-conditional-distributions.pdf}
}

gha_language: SCSS


text:
package cmd

import (
	"os"

	"github.com/cosmos/cosmos-sdk/cosmovisor"
)

// RunArgs are the strings that indicate a cosmovisor run command.
var RunArgs = []string{"run"}

// IsRunCommand checks if the given args indicate that a run is desired.
func IsRunCommand(arg string) bool {
	return isOneOf(arg, RunArgs)
}

// Run runs the configured program with the given args and monitors it for upgrades.
func Run(args []string) error {
	cfg, err := cosmovisor.GetConfigFromEnv()
	if err != nil {
		return err
	}
	launcher, err := cosmovisor.NewLauncher(cfg)
	if err != nil {
		return err
	}

	doUpgrade, err := launcher.Run(args, os.Stdout, os.Stderr)
	// if RestartAfterUpgrade, we launch after a successful upgrade (only condition LaunchProcess returns nil)
	for cfg.RestartAfterUpgrade && err == nil && doUpgrade {
		cosmovisor.Logger.Info().Str("app", cfg.Name).Msg("upgrade detected, relaunching")
		doUpgrade, err = launcher.Run(args, os.Stdout, os.Stderr)
	}
	if doUpgrade && err == nil {
		cosmovisor.Logger.Info().Msg("upgrade detected, DAEMON_RESTART_AFTER_UPGRADE is off. Verify new upgrade and start cosmovisor again.")
	}

	return err
}

repository: FirmaChain/cosmos-sdk

repo_name: FirmaChain/cosmos-sdk


text:
// Copyright 2016-2023 terraform-provider-sakuracloud 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 main

import (
	"context"
	"flag"
	"log"

	"github.com/hashicorp/terraform-plugin-go/tfprotov5/tf5server"
	"github.com/hashicorp/terraform-plugin-mux/tf5muxserver"
	"github.com/sacloud/terraform-provider-sakuracloud/sakuracloud"
)

func main() {
	debugFlag := flag.Bool("debug", false, "Start provider in debug mode.")
	flag.Parse()

	serverFactory, err := sakuracloud.ProtoV5ProviderServerFactory(context.Background())
	if err != nil {
		log.Fatal(err)
	}

	muxServer, err := tf5muxserver.NewMuxServer(context.Background(), serverFactory)
	if err != nil {
		log.Fatal(err)
	}

	var serveOpts []tf5server.ServeOpt
	if *debugFlag {
		serveOpts = append(serveOpts, tf5server.WithManagedDebug())
	}

	logFlags := log.Flags()
	logFlags = logFlags &^ (log.Ldate | log.Ltime)
	log.SetFlags(logFlags)

	err = tf5server.Serve(
		"registry.terraform.io/sacloud/sakuracloud",
		muxServer.ProviderServer,
		serveOpts...,
	)

	if err != nil {
		log.Fatal(err)
	}
}

repository: sacloud/terraform-provider-sakuracloud

repo_name: sacloud/terraform-provider-sakuracloud

gha_language: Go


text:
package lexical

import (
	"fmt"
	"os"
	"path/filepath"

	"context"

	"github.com/georgysavva/scany/v2/pgxscan"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/urfave/cli"
)

type SlateOutput struct {
	Content string
	Slug    string
}

const query = `SELECT content,slug from content`

func LexicalContent(c *cli.Context) error {
	dburl := fmt.Sprintf(
		"postgres://%s:%s@%s:%d/%s",
		c.String("user"),
		c.String("pass"),
		c.String("host"),
		c.Int("port"),
		c.String("database"),
	)
	pool, err := pgxpool.New(context.Background(), dburl)
	defer pool.Close()
	if err != nil {
		cli.NewExitError(
			fmt.Sprintf("error in creating database connection pool %s", err),
			2,
		)
	}
	so := make([]*SlateOutput, 0)
	if err := pgxscan.Select(context.Background(), pool, &so, query); err != nil {
		return cli.NewExitError(
			fmt.Sprintf("error in running query %s", err),
			2,
		)
	}
	for _, row := range so {
		output := filepath.Join(c.String("output-folder"), row.Slug+".json")
		w, err := os.Create(output)
		if err != nil {
			return cli.NewExitError(
				fmt.Sprintf("error in opening file %s %s", output, err),
				2,
			)
		}
		defer w.Close()
		fmt.Fprint(w, row.Content)
	}
	return nil
}

func LexicalContentFlags() []cli.Flag {
	return []cli.Flag{
		cli.StringFlag{
			Name:     "user,u",
			Usage:    "postgresql database user",
			Required: true,
		},
		cli.StringFlag{
			Name:     "pass,p",
			Usage:    "postgresql database password",
			Required: true,
		},
		cli.StringFlag{
			Name:     "host",
			Usage:    "postgresql database host",
			Required: true,
		},
		cli.IntFlag{
			Name:  "port",
			Usage: "postgresql database port",
			Value: 5432,
		},
		cli.StringFlag{
			Name:     "database,d",
			Usage:    "postgresql database name",
			Required: true,
		},
		cli.StringFlag{
			Name:     "output-folder",
			Usage:    "output folder where all the content json files will be saved",
			Required: true,
		},
	}
}

repository: dictybase-playground/draftjs-to-slatejs

repo_name: dictybase-playground/draftjs-to-slatejs

branch_name: refs/heads/develop


text:
package models

import (
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
)

type User struct {
	gorm.Model
	PhoneNumber string
	Password    string
	NickName    string
	Bio         string
	Status      string
	Role        string
	Avatar      string
}

const (
	PasswordCost = 12
	// Active 激活用户
	Active string = "active"
	// Inactive 未激活用户
	Inactive string = "inactive"
	// Suspend 被封禁用户
	Suspend string = "suspend"
)

func RegisterUser(user *User) error {
	err := DB.Create(&user).Error

	if err != nil {
		return nil
	}

	return err
}

func GetUserById(ID interface{}) (*User, error) {
	var user User

	err := DB.First(&user, ID).Error
	if err != nil {
		return nil, err
	}

	return &user, nil
}

func UpdateUserProfile(user *User) error {
	err := DB.Save(&user).Error

	if err != nil {
		return err
	}

	return nil
}

func (user *User) SetPassword(password string) error {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), PasswordCost)
	if err != nil {
		return err
	}
	user.Password = string(bytes)
	return nil
}

func (user *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	return err == nil
}


text:
SUMMARY = "TI Multimedia card(MMC)/Secure Digital(SD) low level driver for RTOS "

inherit ti-pdk ti-pdk-fetch

TI_PDK_COMP = "ti.drv.mmcsd"

PE = "1"

LICENSE = "BSD-3-Clause"
LIC_FILES_CHKSUM = "file://MMCSD.h;beginline=1;endline=32;md5=f74069541d4d165a000a66b4043cb065"

COMPATIBLE_MACHINE = "ti33x|ti43x|omap-a15|k2g|omapl1|k3"
PACKAGE_ARCH = "${MACHINE_ARCH}"

PR = "r0"

DEPENDS_append = " edma3-lld-rtos \
                   osal-rtos \
"
DEPENDS_append_ti33x = " starterware-rtos \
"
DEPENDS_append_ti43x = " starterware-rtos \
"
DEPENDS_remove_k3 = "edma3-lld-rtos "

DEPENDS_append_k3 = " sciclient-rtos \
"

# Build with make instead of XDC
TI_PDK_XDCMAKE = "0"

export PDK_MMCSD_ROOT_PATH ="${WORKDIR}/build"
export DEST_ROOT="${S}"

export EDMA3LLD_BIOS6_INSTALLDIR = "${EDMA3_LLD_INSTALL_DIR}"
XDCPATH_append = ";${EDMA3_LLD_INSTALL_DIR}/packages"

# HTML doc link params
PDK_COMP_LINK_TEXT = "MMCSD LLD"

repository: acrlinux/acrlinux-yocto

repo_name: acrlinux/acrlinux-yocto


text:
LICENSE = "GPL"
DESCRIPTION = "A file-synchronization tool"
SECTION = "console/network"
PRIORITY = "optional"
MAINTAINER = "Chris Larson <kergoth@handhelds.org>"

SRC_URI = "http://rsync.samba.org/ftp/rsync/rsync-${PV}.tar.gz"

inherit autotools

EXTRA_OEMAKE='STRIP=""'

repository: Terentyev/familiar-linux

repo_name: Terentyev/familiar-linux


text:
DESCRIPTION = "FUSE Python bindings."
SECTION = "devel/python"
LICENSE = "GPLv2"
DEPENDS = "fuse"
SRCNAME = "fuse-python"
PR = "ml0"

SRC_URI = "${SOURCEFORGE_MIRROR}/fuse/${SRCNAME}-${PV}.tar.gz"
S = "${WORKDIR}/${SRCNAME}-${PV}"

inherit distutils

FILES_${PN}-dbg += "${libdir}/python*/site-packages/fuseparts/.debu*"

SRC_URI[md5sum] = "68be744e71a42cd8a92905a49f346278"
SRC_URI[sha256sum] = "89f3e9ac096759e10b6292632216c9653d7e35c2c99847267173d94afdf85b92"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
require hal-info.inc

SRC_URI[md5sum] = "ae7177ab8f0163d3ef2df71f0de2b357"
SRC_URI[sha256sum] = "33dd87dc9452227375b8b9cdad940581714a55d55ff18ae2990905ac2f81fa0f"


text:
@book{preussler2020,
  title     = "Integrated Planning of Pilot and Subsequent Confirmatory Study in Clinical Research",
  subtitle  = "Finding Optimal Designs in a Utility-Based Framework",
  author    = "Preussler, Stella",
  year      = 2020,
  publisher = "Dissertation, supervised by Kieser, M.",
  address   = "Heidelberg"
}
@article{goette2015,
  author = {Götte, Heiko and Schüler, Armin and Kirchner, Marietta and Kieser, Meinhard},
  title = {Sample size planning for phase II trials based on success probabilities for phase III},
  journal = {Pharmaceutical Statistics},
  volume = {14},
  number = {6},
  pages = {515-524},
  keywords = {drug development programme, phase II trials, probability of success, sample size, time-to-event analysis},
  doi = {10.1002/pst.1717},
  year = {2015}
}

@article{kieser2018,
  author = {Kieser, Meinhard and Kirchner, Marietta and Dölger, Eva and Götte, Heiko},
  title = {Optimal planning of phase II/III programs for clinical trials with multiple endpoints},
  journal = {Pharmaceutical Statistics},
  volume = {17},
  number = {5},
  pages = {437-457},
  keywords = {drug development program, multiple endpoints, phase II/III, probability of success, sample size},
  doi = {10.1002/pst.1861},
  url = {https://onlinelibrary.wiley.com/doi/abs/10.1002/pst.1861},
  eprint = {https://onlinelibrary.wiley.com/doi/pdf/10.1002/pst.1861},
  year = {2018}
}

@manual{hughes2021,
  title = {Automate Validated Package Creation},
  author = {{Hughes} and {E.} and {Vendettuoli} and {M.} and {Miller} and {E.} and {Peyman} and {E.}},
  year = {2021},
  url = {https://github.com/phuse-org/valtools},
  note = {See also: `R Validation Framework`},
}

@online{phuse2021,
  author = {Hughes, E.},
  organization = {PHUSE Working Group: Data Visualisation & Open Source Technology},
  title = {White Paper WP-059: R Package Validation Framework},
  url = {https://advance.phuse.global/display/WEL/R+Package+Validation+Framework},
  version = {1.0},
  urldate = {09/05/2022},
  year = {2021}
}

gha_license_id: NOASSERTION

gha_language: R


text:
/*
Copyright 2020 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 netpol

import (
	"fmt"
	"strings"

	"github.com/pkg/errors"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/kubernetes/test/e2e/framework"
	imageutils "k8s.io/kubernetes/test/utils/image"
)

// Model defines the namespaces, deployments, services, pods, containers and associated
// data for network policy test cases and provides the source of truth
type Model struct {
	Namespaces    []*Namespace
	allPodStrings *[]PodString
	allPods       *[]*Pod
	// the raw data
	NamespaceNames []string
	PodNames       []string
	Ports          []int32
	Protocols      []v1.Protocol
	DNSDomain      string
}

// NewModel instantiates a model based on:
// - namespaces
// - pods
// - ports to listen on
// - protocols to listen on
// The total number of pods is the number of namespaces x the number of pods per namespace.
// The number of containers per pod is the number of ports x the number of protocols.
// The *total* number of containers is namespaces x pods x ports x protocols.
func NewModel(namespaces []string, podNames []string, ports []int32, protocols []v1.Protocol, dnsDomain string) *Model {
	model := &Model{
		NamespaceNames: namespaces,
		PodNames:       podNames,
		Ports:          ports,
		Protocols:      protocols,
		DNSDomain:      dnsDomain,
	}
	framework.Logf("DnsDomain %v", model.DNSDomain)

	// build the entire "model" for the overall test, which means, building
	// namespaces, pods, containers for each protocol.
	for _, ns := range namespaces {
		var pods []*Pod
		for _, podName := range podNames {
			var containers []*Container
			for _, port := range ports {
				for _, protocol := range protocols {
					containers = append(containers, &Container{
						Port:     port,
						Protocol: protocol,
					})
				}
			}
			pods = append(pods, &Pod{
				Namespace:  ns,
				Name:       podName,
				Containers: containers,
			})
		}
		model.Namespaces = append(model.Namespaces, &Namespace{Name: ns, Pods: pods})
	}
	return model
}

// NewReachability instantiates a default-true reachability from the model's pods
func (m *Model) NewReachability() *Reachability {
	return NewReachability(m.AllPods(), true)
}

// AllPodStrings returns a slice of all pod strings
func (m *Model) AllPodStrings() []PodString {
	if m.allPodStrings == nil {
		var pods []PodString
		for _, ns := range m.Namespaces {
			for _, pod := range ns.Pods {
				pods = append(pods, pod.PodString())
			}
		}
		m.allPodStrings = &pods
	}
	return *m.allPodStrings
}

// AllPods returns a slice of all pods
func (m *Model) AllPods() []*Pod {
	if m.allPods == nil {
		var pods []*Pod
		for _, ns := range m.Namespaces {
			for _, pod := range ns.Pods {
				pods = append(pods, pod)
			}
		}
		m.allPods = &pods
	}
	return *m.allPods
}

// FindPod returns the pod of matching namespace and name, or an error
func (m *Model) FindPod(ns string, name string) (*Pod, error) {
	for _, namespace := range m.Namespaces {
		for _, pod := range namespace.Pods {
			if namespace.Name == ns && pod.Name == name {
				return pod, nil
			}
		}
	}
	return nil, errors.Errorf("unable to find pod %s/%s", ns, name)
}

// Namespace is the abstract representation of what matters to network policy
// tests for a namespace; i.e. it ignores kube implementation details
type Namespace struct {
	Name string
	Pods []*Pod
}

// Spec builds a kubernetes namespace spec
func (ns *Namespace) Spec() *v1.Namespace {
	return &v1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name:   ns.Name,
			Labels: ns.LabelSelector(),
		},
	}
}

// LabelSelector returns the default labels that should be placed on a namespace
// in order for it to be uniquely selectable by label selectors
func (ns *Namespace) LabelSelector() map[string]string {
	return map[string]string{"ns": ns.Name}
}

// Pod is the abstract representation of what matters to network policy tests for
// a pod; i.e. it ignores kube implementation details
type Pod struct {
	Namespace  string
	Name       string
	Containers []*Container
}

// PodString returns a corresponding pod string
func (p *Pod) PodString() PodString {
	return NewPodString(p.Namespace, p.Name)
}

// ContainerSpecs builds kubernetes container specs for the pod
func (p *Pod) ContainerSpecs() []v1.Container {
	var containers []v1.Container
	for _, cont := range p.Containers {
		containers = append(containers, cont.Spec())
	}
	return containers
}

func (p *Pod) labelSelectorKey() string {
	return "pod"
}

func (p *Pod) labelSelectorValue() string {
	return p.Name
}

// LabelSelector returns the default labels that should be placed on a pod/deployment
// in order for it to be uniquely selectable by label selectors
func (p *Pod) LabelSelector() map[string]string {
	return map[string]string{
		p.labelSelectorKey(): p.labelSelectorValue(),
	}
}

// KubePod returns the kube pod
func (p *Pod) KubePod() *v1.Pod {
	zero := int64(0)
	return &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      p.Name,
			Labels:    p.LabelSelector(),
			Namespace: p.Namespace,
		},
		Spec: v1.PodSpec{
			TerminationGracePeriodSeconds: &zero,
			Containers:                    p.ContainerSpecs(),
		},
	}
}

// QualifiedServiceAddress returns the address that can be used to hit a service from
// any namespace in the cluster
func (p *Pod) QualifiedServiceAddress(dnsDomain string) string {
	return fmt.Sprintf("%s.%s.svc.%s", p.ServiceName(), p.Namespace, dnsDomain)
}

// ServiceName returns the unqualified service name
func (p *Pod) ServiceName() string {
	return fmt.Sprintf("s-%s-%s", p.Namespace, p.Name)
}

// Service returns a kube service spec
func (p *Pod) Service() *v1.Service {
	service := &v1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      p.ServiceName(),
			Namespace: p.Namespace,
		},
		Spec: v1.ServiceSpec{
			Selector: p.LabelSelector(),
		},
	}
	for _, container := range p.Containers {
		service.Spec.Ports = append(service.Spec.Ports, v1.ServicePort{
			Name:     fmt.Sprintf("service-port-%s-%d", strings.ToLower(string(container.Protocol)), container.Port),
			Protocol: container.Protocol,
			Port:     container.Port,
		})
	}
	return service
}

// Container is the abstract representation of what matters to network policy tests for
// a container; i.e. it ignores kube implementation details
type Container struct {
	Port     int32
	Protocol v1.Protocol
}

// Name returns the container name
func (c *Container) Name() string {
	return fmt.Sprintf("cont-%d-%s", c.Port, strings.ToLower(string(c.Protocol)))
}

// PortName returns the container port name
func (c *Container) PortName() string {
	return fmt.Sprintf("serve-%d-%s", c.Port, strings.ToLower(string(c.Protocol)))
}

// Spec returns the kube container spec
func (c *Container) Spec() v1.Container {
	var (
		// agnHostImage is the image URI of AgnHost
		agnHostImage = imageutils.GetE2EImage(imageutils.Agnhost)
		env          = []v1.EnvVar{}
		cmd          []string
	)

	switch c.Protocol {
	case v1.ProtocolTCP:
		cmd = []string{"/agnhost", "serve-hostname", "--tcp", "--http=false", "--port", fmt.Sprintf("%d", c.Port)}
	case v1.ProtocolUDP:
		cmd = []string{"/agnhost", "serve-hostname", "--udp", "--http=false", "--port", fmt.Sprintf("%d", c.Port)}
	case v1.ProtocolSCTP:
		env = append(env, v1.EnvVar{
			Name:  fmt.Sprintf("SERVE_SCTP_PORT_%d", c.Port),
			Value: "foo",
		})
		cmd = []string{"/agnhost", "porter"}
	default:
		framework.Failf("invalid protocol %v", c.Protocol)
	}

	return v1.Container{
		Name:            c.Name(),
		ImagePullPolicy: v1.PullIfNotPresent,
		Image:           agnHostImage,
		Command:         cmd,
		Env:             env,
		SecurityContext: &v1.SecurityContext{},
		Ports: []v1.ContainerPort{
			{
				ContainerPort: c.Port,
				Name:          c.PortName(),
				Protocol:      c.Protocol,
			},
		},
	}
}

repository: brendandburns/kubernetes

repo_name: brendandburns/kubernetes


text:
SUMMARY = "PyEphem astronomical calculations"
HOMEPAGE = "http://rhodesmill.org/pyephem/"

LICENSE = "LGPL-3.0"
LIC_FILES_CHKSUM = "file://COPYING;md5=f288303760f6e5ceaafe3aaa32186ab1"

SRC_URI[sha256sum] = "36b51a8dc7cfdeb456dd6b8ab811accab8341b2d562ee3c6f4c86f6d3dbb984e"

PYPI_PACKAGE = "ephem"

inherit pypi setuptools3

RDEPENDS_${PN} += "\
    ${PYTHON_PN}-datetime \
    ${PYTHON_PN}-math \
    "

repository: ni/meta-openembedded

repo_name: ni/meta-openembedded

branch_name: refs/heads/nilrt/master/hardknott

gha_language: BitBake


text:
SUMMARY = "An image that builds a Docker image of the environment \
for GNSS-SDR testing purposes."

EXTRA_IMAGE_FEATURES += "tools-debug tools-profile tools-sdk dev-pkgs"
LICENSE = "MIT"

require core-image-container.bb
require gnuradio-dev-image.bb

RDEPENDS_packagegroup-sdr-base-python += " python3-six"

SDK_EXTRA_TOOLS += "nativesdk-python3-six"

IMAGE_INSTALL = " \
                 packagegroup-core-container \
                 packagegroup-gnss-sdr-base \
                "

CORE_IMAGE_EXTRA_INSTALL += " \
    packagegroup-gnss-sdr-base \
"

IMAGE_CLASSES += "image_type_docker"
IMAGE_FSTYPES = "docker"

inherit core-image

# set a meaningful name  and tag for the docker output image
DOCKER_IMAGE_TAG = "latest"
DOCKER_IMAGE_NAME_EXPORT = "gnsssdr-dev-arm32v7:${DOCKER_IMAGE_TAG}"

repository: zarym/meta-gnss-sdr

repo_name: zarym/meta-gnss-sdr


text:
package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/bcmk/siren/lib"
	"gopkg.in/yaml.v3"
)

var print = flag.Bool("p", false, "print translations")
var printKeys = flag.Bool("k", false, "print keys")

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [options]\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()
	_, raw := lib.LoadEndpointTranslations(flag.Args())
	if *print {
		bytes, err := yaml.Marshal(raw)
		lib.CheckErr(err)
		fmt.Println(string(bytes))
	} else if *printKeys {
		for _, t := range raw {
			fmt.Println(t.Key)
		}
	} else {
		fmt.Println("OK")
	}
}

repository: bcmk/siren

repo_name: bcmk/siren


text:
@inproceedings{strachan2020methodology,
  title={A methodology for distinguishing copying and reconstruction in cultural transmission episodes.},
  author={Strachan, James and Curioni, Arianna and Constable, Merryn and Knoblich, G{\"u}nther and Charbonneau, Mathieu},
  booktitle={Proceedings of the 42nd Meeting of the Cognitive Science Society},
  year={2020}
}

repository: jstrchn/website

repo_name: jstrchn/website


text:
package db

import (
	"database/sql"

	"github.com/jackc/pgx/v4"
	"github.com/lib/pq"
	"github.com/nanzhong/tester"
)

type pgTest tester.Test

func (t *pgTest) Columns() []string {
	return []string{
		"id",
		"package",
		"run_id",
		"result",
		"logs",
	}
}

func (t *pgTest) Values() []interface{} {
	return []interface{}{
		t.ID,
		t.Package,
		t.RunID,
		t.Result,
		t.Logs,
	}
}

func (t *pgTest) Scan(row pgx.Row) error {
	err := row.Scan(
		&t.ID,
		&t.Package,
		&t.RunID,
		&t.Result,
		&t.Logs,
	)
	if err != nil && err == pgx.ErrNoRows {
		err = ErrNotFound
	}
	return err
}

type pgRun tester.Run

func (r *pgRun) Columns() []string {
	return []string{
		"id",
		"package",
		"args",
		"meta",
		"enqueued_at",
		"started_at",
		"finished_at",
		"error",
	}
}

func (r *pgRun) Values() []interface{} {
	startedAt := sql.NullTime{Valid: !r.StartedAt.IsZero(), Time: r.StartedAt}
	finishedAt := sql.NullTime{Valid: !r.FinishedAt.IsZero(), Time: r.FinishedAt}
	error := sql.NullString{Valid: r.Error != "", String: r.Error}

	return []interface{}{
		r.ID,
		r.Package,
		pq.Array(r.Args),
		r.Meta,
		r.EnqueuedAt,
		startedAt,
		finishedAt,
		error,
	}
}

func (r *pgRun) Scan(row pgx.Row) error {
	var (
		startedAt  sql.NullTime
		finishedAt sql.NullTime
		error      sql.NullString
	)

	err := row.Scan(
		&r.ID,
		&r.Package,
		pq.Array(&r.Args),
		&r.Meta,
		&r.EnqueuedAt,
		&startedAt,
		&finishedAt,
		&error,
	)
	if err != nil {
		if err == pgx.ErrNoRows {
			err = ErrNotFound
		}
		return err
	}

	if startedAt.Valid {
		r.StartedAt = startedAt.Time
	}
	if finishedAt.Valid {
		r.FinishedAt = finishedAt.Time
	}
	if error.Valid {
		r.Error = error.String
	}
	return nil
}

repository: nanzhong/tester

repo_name: nanzhong/tester


text:
// Package nico provides accessing the Niconico API.
package nico

import (
	"bufio"
	"context"
	"encoding/xml"
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"path"
	"regexp"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
)

var findCommunityID = func() func(string) string {
	re := regexp.MustCompile(`co\d+`)
	return func(s string) string {
		return re.Copy().FindString(s)
	}
}()

// Client is a API client for niconico.
type Client struct {
	http.Client
	loginRawurl         string
	liveBaseRawurl      string
	communityBaseRawurl string
	ceBaseRawurl        string
	UserSession         string
}

// NewClient return new niconico client.
func NewClient() *Client {
	return &Client{
		loginRawurl:         "https://secure.nicovideo.jp/secure/login",
		liveBaseRawurl:      "http://live.nicovideo.jp",
		communityBaseRawurl: "http://com.nicovideo.jp",
		ceBaseRawurl:        "http://api.ce.nicovideo.jp",
	}
}

// Login is login to niconico and get user session.
func (c *Client) Login(ctx context.Context, mail, password string) (string, error) {
	v := url.Values{}
	v.Set("mail", mail)
	v.Set("password", password)

	req, err := http.NewRequest(http.MethodPost, c.loginRawurl, strings.NewReader(v.Encode()))
	if err != nil {
		return "", err
	}
	req = req.WithContext(ctx)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	cr := c.CheckRedirect
	defer func() { c.CheckRedirect = cr }()
	c.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }
	resp, err := c.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusFound {
		return "", errors.New(resp.Status)
	}

	cookies := resp.Cookies()
	for i := len(cookies) - 1; i >= 0; i-- {
		if cookies[i].Name == "user_session" {
			c.UserSession = cookies[i].Value
			return c.UserSession, nil
		}
	}
	return "", errors.New("login failed")
}

// GetPostkey gets the key to be specified when posting a comment.
func (c *Client) GetPostkey(ctx context.Context, thread int64) (string, error) {
	u, err := url.Parse(c.liveBaseRawurl)
	if err != nil {
		return "", err
	}
	u.Path = "api/getpostkey"

	v := url.Values{}
	v.Set("thread", fmt.Sprint(thread))
	u.RawQuery = v.Encode()

	req, err := http.NewRequest(http.MethodGet, u.String(), nil)
	if err != nil {
		return "", err
	}
	req = req.WithContext(ctx)
	req.AddCookie(&http.Cookie{Name: "user_session", Value: c.UserSession})

	resp, err := c.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", errors.New(resp.Status)
	}

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	rv, err := url.ParseQuery(string(b))
	if err != nil {
		return "", err
	}
	postkey := rv.Get("postkey")
	if postkey == "" {
		return "", errors.New("postkey is empty")
	}
	return postkey, nil
}

// FollowCommunity follows community of communityID.
func (c *Client) FollowCommunity(ctx context.Context, communityID string) error {
	u, err := url.Parse(c.communityBaseRawurl)
	if err != nil {
		return err
	}
	u.Path = path.Join("motion", communityID)

	v := url.Values{}
	v.Set("mode", "commit")

	req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(v.Encode()))
	if err != nil {
		return err
	}
	req = req.WithContext(ctx)
	req.Header.Set("Referer", u.String())
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(&http.Cookie{Name: "user_session", Value: c.UserSession})

	cr := c.CheckRedirect
	defer func() { c.CheckRedirect = cr }()
	c.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }
	resp, err := c.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusFound {
		return errors.New(resp.Status)
	} else if !strings.Contains(resp.Header.Get("Location"), "done") {
		return errors.New("community follow failed")
	}
	return nil
}

func (c *Client) getLeaveCommunityFormData(ctx context.Context, communityID string) (url.Values, error) {
	u, err := url.Parse(c.communityBaseRawurl)
	if err != nil {
		return nil, err
	}
	u.Path = path.Join("leave", communityID)

	req, err := http.NewRequest(http.MethodGet, u.String(), nil)
	if err != nil {
		return nil, err
	}
	req = req.WithContext(ctx)
	req.AddCookie(&http.Cookie{Name: "user_session", Value: c.UserSession})

	resp, err := c.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, errors.New(resp.Status)
	}

	doc, err := goquery.NewDocumentFromResponse(resp)
	if err != nil {
		return nil, err
	}

	v := url.Values{}
	doc.Find(".leave_form input").Each(func(i int, s *goquery.Selection) {
		name, ok := s.Attr("name")
		if !ok {
			return
		}
		value, ok := s.Attr("value")
		if !ok {
			return
		}
		v.Set(name, value)
	})
	return v, nil
}

// LeaveCommunity leaves the community of communityID.
func (c *Client) LeaveCommunity(ctx context.Context, communityID string) error {
	u, err := url.Parse(c.communityBaseRawurl)
	if err != nil {
		return err
	}
	u.Path = path.Join("leave", communityID)

	v, err := c.getLeaveCommunityFormData(ctx, communityID)
	if err != nil {
		return err
	}

	req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(v.Encode()))
	if err != nil {
		return err
	}
	req = req.WithContext(ctx)
	req.Header.Set("Referer", u.String())
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(&http.Cookie{Name: "user_session", Value: c.UserSession})

	cr := c.CheckRedirect
	defer func() { c.CheckRedirect = cr }()
	c.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }
	resp, err := c.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusFound {
		return errors.New(resp.Status)
	} else if !strings.Contains(resp.Header.Get("Location"), "done") {
		return errors.New("community leave failed")
	}
	return nil
}

// GetCommunityIDFromLiveID gets the ID of the community that is broadcasting in liveID.
// No login required.
func (c *Client) GetCommunityIDFromLiveID(ctx context.Context, liveID string) (string, error) {
	u, err := url.Parse(c.liveBaseRawurl)
	if err != nil {
		return "", err
	}
	u.Path = path.Join("watch", liveID)

	req, err := http.NewRequest(http.MethodGet, u.String(), nil)
	if err != nil {
		return "", err
	}
	req = req.WithContext(ctx)

	resp, err := c.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", errors.New(resp.Status)
	}

	doc, err := goquery.NewDocumentFromResponse(resp)
	if err != nil {
		return "", err
	}
	href, ok := doc.Find(".shosai > a").Attr("href")
	if !ok {
		return "", errors.New("community not found")
	}
	return findCommunityID(href), nil
}

// MakeLiveClient creates a client with broadcast information from liveID.
func (c *Client) MakeLiveClient(ctx context.Context, liveID string) (*LiveClient, error) {
	ps, err := c.GetPlayerStatus(ctx, liveID)
	if err != nil {
		return nil, err
	}

	var d net.Dialer
	conn, err := d.DialContext(ctx, "tcp", fmt.Sprintf("%s:%d", ps.Ms.Addr, ps.Ms.Port))
	if err != nil {
		return nil, err
	}
	go func() {
		<-ctx.Done()
		conn.Close()
	}()
	return &LiveClient{Client: c, PlayerStatus: ps, conn: conn}, nil
}

// LiveClient is a client with broadcast information.
type LiveClient struct {
	*Client
	PlayerStatus *PlayerStatus
	conn         net.Conn
}

// StreamingComment return the channel that receives comment.
func (c *LiveClient) StreamingComment(ctx context.Context, resFrom int64) (chan Comment, error) {
	b, err := xml.Marshal(SendThread{Thread: c.PlayerStatus.Ms.Thread, Version: 20061206, ResFrom: resFrom})
	if err != nil {
		return nil, err
	}
	b = append(b, 0)
	_, err = c.conn.Write(b)
	if err != nil {
		return nil, err
	}

	r := bufio.NewReader(c.conn)
	ch := make(chan Comment)
	go func() {
		defer close(ch)
		for {
			select {
			case <-ctx.Done():
				return
			default:
			}
			rb, err := r.ReadSlice(0)
			if err != nil {
				ch <- &CommentError{err}
			}
			var thread Thread
			if err := xml.Unmarshal(rb, &thread); err == nil {
				ch <- &thread
			}
			var chat Chat
			if err := xml.Unmarshal(rb, &chat); err == nil {
				ch <- &chat
			}
			var chatResult ChatResult
			if err := xml.Unmarshal(rb, &chatResult); err == nil {
				ch <- &chatResult
			}
		}
	}()
	return ch, nil
}

// PostComment post the comment.
func (c *LiveClient) PostComment(ctx context.Context, comment string, mail Mail) error {
	postkey, err := c.GetPostkey(ctx, c.PlayerStatus.Ms.Thread)
	if err != nil {
		return err
	}
	chat := SendChat{
		Vpos:    (time.Now().UnixNano() - c.PlayerStatus.Stream.BaseTime*int64(time.Second)) / (int64(time.Millisecond) * 10),
		Mail:    mail.String(),
		UserID:  fmt.Sprint(c.PlayerStatus.User.UserID),
		Postkey: postkey,
		Comment: comment,
	}
	b, err := xml.Marshal(chat)
	if err != nil {
		return err
	}
	b = append(b, 0)
	if _, err := c.conn.Write(b); err != nil {
		return err
	}
	return nil
}

// SendThread is an xml struct of the thread to send.
type SendThread struct {
	XMLName xml.Name `xml:"thread"`
	Thread  int64    `xml:"thread,attr"`
	Version int64    `xml:"version,attr"`
	ResFrom int64    `xml:"res_from,attr"`
}

// Comment is a interface of struct received on the chan returned by PostComment.
type Comment interface {
	comment()
}

// Thread is a struct of xml received immediately after connection.
type Thread struct {
	XMLName    xml.Name `xml:"thread"`
	Resultcode int64    `xml:"resultcode,attr"`
	Thread     int64    `xml:"thread,attr"`
	LastRes    int64    `xml:"last_res,attr"`
	Ticket     string   `xml:"ticket,attr"`
	Revision   int64    `xml:"revision,attr"`
	ServerTime int64    `xml:"server_time,attr"`
}

func (t *Thread) comment() {}

// Chat is an xml struct of comment.
type Chat struct {
	XMLName   xml.Name `xml:"chat"`
	Thread    int64    `xml:"thread,attr"`
	No        int64    `xml:"no,attr"`
	Vpos      int64    `xml:"vpos,attr"`
	Date      int64    `xml:"date,attr"`
	DateUsec  int64    `xml:"date_usec,attr"`
	Mail      string   `xml:"mail,attr"`
	Yourpost  int64    `xml:"yourpost,attr"`
	UserID    string   `xml:"user_id,attr"`
	Premium   int64    `xml:"premium,attr"`
	Anonymity int64    `xml:"anonymity,attr"`
	Locale    string   `xml:"locale,attr"`
	Score     int64    `xml:"score,attr"`
	Comment   string   `xml:",chardata"`
}

func (c *Chat) comment() {}

// ChatResult is an xml struct that returns the posting result of comment.
type ChatResult struct {
	XMLName xml.Name `xml:"chat_result"`
	Thread  int64    `xml:"thread,attr"`
	Status  int64    `xml:"status,attr"`
	No      int64    `xml:"no,attr"`
}

func (r *ChatResult) comment() {}

// CommentError is a struct containing error of StreamingComment function.
type CommentError struct{ error }

func (e *CommentError) comment() {}

// SendChat is a struct to use when posting comment.
type SendChat struct {
	XMLName xml.Name `xml:"chat"`
	Vpos    int64    `xml:"vpos,attr"`
	Mail    string   `xml:"mail,attr,omitempty"`
	UserID  string   `xml:"user_id,attr"`
	Postkey string   `xml:"postkey,attr"`
	Comment string   `xml:",chardata"`
}

// Error code of PlayerStatus.
const (
	PlayerStatusErrorCodeFull                   = "full"
	PlayerStatusErrorCodeNotlogin               = "notlogin"
	PlayerStatusErrorCodeRequireCommunityMember = "require_community_member"
)

// PlayerStatusError is an error to return if Status of PlayerStatus is not ok.
type PlayerStatusError struct {
	Status string
	Code   string
}

func (e PlayerStatusError) Error() string {
	return fmt.Sprintf("%s: %s", e.Status, e.Code)
}


text:
package elem

import (
	"sync"

	"github.com/Bitspark/slang/pkg/core"
	"github.com/google/uuid"
)

type memoryStore struct {
	mutex *sync.Mutex
	items map[string]interface{}
}

var memoryStores map[string]*memoryStore
var memoryMutex *sync.Mutex

func getMemoryStore(store string) *memoryStore {
	memoryMutex.Lock()
	ms, ok := memoryStores[store]
	if !ok {
		ms = &memoryStore{}
		ms.mutex = &sync.Mutex{}
		ms.items = make(map[string]interface{})
		memoryStores[store] = ms
	}
	memoryMutex.Unlock()
	return ms
}

var databaseMemoryReadId = uuid.MustParse("2fcd32f5-c83c-4fff-9ac2-ccd6d02139fa")
var databaseMemoryReadCfg = &builtinConfig{
	safe: true,
	blueprint: core.Blueprint{
		Id: databaseMemoryReadId,
		Meta: core.BlueprintMetaDef{
			Name:             "read from memory",
			ShortDescription: "reads an item from memory associated with a key string",
			Icon:             "memory",
			Tags:             []string{"database"},
			DocURL:           "https://bitspark.de/slang/docs/operator/memory-read",
		},
		ServiceDefs: map[string]*core.ServiceDef{
			core.MAIN_SERVICE: {
				In: core.TypeDef{
					Type: "map",
					Map: map[string]*core.TypeDef{
						"key": {
							Type: "string",
						},
						"keyValue": {
							Type:    "generic",
							Generic: "keyType",
						},
					},
				},
				Out: core.TypeDef{
					Type:    "generic",
					Generic: "valueType",
				},
			},
		},
		DelegateDefs: map[string]*core.DelegateDef{
			"creator": {
				Out: core.TypeDef{
					Type:    "generic",
					Generic: "keyType",
				},
				In: core.TypeDef{
					Type:    "generic",
					Generic: "valueType",
				},
			},
		},
		PropertyDefs: core.PropertyMap{
			"store": {
				Type: "string",
			},
		},
	},
	opFunc: func(op *core.Operator) {
		in := op.Main().In()
		out := op.Main().Out()

		creatorOut := op.Delegate("creator").Out()
		creatorIn := op.Delegate("creator").In()

		// Get store
		store := op.Property("store").(string)
		ms := getMemoryStore(store)

		for {
			i := in.Pull()
			if core.IsMarker(i) {
				out.Push(i)
				continue
			}

			keyMap := i.(map[string]interface{})
			key := keyMap["key"].(string)
			keyValue := keyMap["keyValue"]

			ms.mutex.Lock()
			if value, ok := ms.items[key]; ok {
				out.Push(value)
			} else {
				creatorOut.Push(keyValue)
				value := creatorIn.Pull()
				ms.items[key] = value
				out.Push(value)
			}
			ms.mutex.Unlock()
		}
	},
}

repository: Bitspark/slang

repo_name: Bitspark/slang


text:
DESCRIPTION = "Engrave is an Edje Editing Library"
LICENSE = "MIT"
# also requires yacc and lex on host
DEPENDS = "evas ecore"
PV = "0.0.0+svnr${SRCPV}"
PR = "r1"
SRCREV = "${EFL_SRCREV}"

inherit efl

SRC_URI = "svn://svn.enlightenment.org/svn/e/OLD;module=${PN};proto=http;scmdata=keep"

repository: trini/openembedded

repo_name: trini/openembedded


text:
require libmpc.inc

DEPENDS = "gmp mpfr"

SRC_URI = "http://www.multiprecision.org/mpc/download/mpc-${PV}.tar.gz"
S = "${WORKDIR}/mpc-${PV}"

do_stage() {
	autotools_stage_all
}

repository: demsey/openembedded

repo_name: demsey/openembedded


text:
import React from 'react';
import '../styles/components/Certificate.styl'

const Certificate = ({ certificate }) => {
  return (

Certificados:

      {
        certificate.map(certification =>

{certification.name}

{certification.institution}

              {certification.date}

{certification.description}

        )
      }

  )
}

export default Certificate

repository: mister-ramoon/frontend

repo_name: mister-ramoon/frontend

extension: jsx


text:
require valgrind.inc

SRC_URI[md5sum] = "b289c5f4ab8e39741602445f1dd09b34"
SRC_URI[sha256sum] = "bc0f0153b5a47b986f1d8efa2c488e0aea85a1cf2c4b11c52be127903080285f"

repository: buglabs/oe-buglabs

repo_name: buglabs/oe-buglabs


text:
require xorg-driver-video.inc
PE = "1"
SRC_URI[archive.md5sum] = "07fa32958aff9b463dd3af5481ef6626"
SRC_URI[archive.sha256sum] = "8ed85a0e94523539d81d5ae6639fa22ceb1c1e3baf89128915db65d4d2900d7a"


text:
package main

import (
	"fmt"
	"os"
	"time"
)

// MovementState ...
type MovementState int64

// ...
const (
	MovementStateNorth MovementState = iota
	MovementStateSouth               = iota
	MovementStateEast                = iota
	MovementStateWest                = iota
	MovementStateCnt                 = iota
)

// Status ...
type Status int64

// ...
const (
	StatusWall         = iota
	StatusSuccess      = iota
	StatusOxygenSystem = iota
)

// Robot ...
type Robot struct {
	row, col       int
	moveState      MovementState
	steps          []MovementState
	isBacktracking bool
}

// Point ...
type Point struct {
	row, col int
	steps    int
}

var visitedTiles [][]bool
var startingRow, startingCol = rows / 2, cols / 2
var robot = &Robot{row: startingRow, col: startingCol, moveState: MovementStateNorth}
var targetRow, targetCol = -1, -1

func main() {
	initScreen()

	prog := newProgram(initProgram)

	visitedTiles = initVisitedTiles()
	screen[robot.row][robot.col] = 'D'

	run(prog, inputCallback, outputCallback)
}

func findShortestPath() int {
	visitedTiles = initVisitedTiles()

	queue := []Point{}
	queue = append(queue, Point{startingRow, startingCol, 0})
	for len(queue) > 0 {
		p := queue[0]
		queue = queue[1:]

		if screen[p.row][p.col] == 'X' {
			return p.steps
		}

		north, south := Point{p.row - 1, p.col, p.steps + 1}, Point{p.row + 1, p.col, p.steps + 1}
		west, east := Point{p.row, p.col - 1, p.steps + 1}, Point{p.row, p.col + 1, p.steps + 1}

		if screen[north.row][north.col] != '#' && !visitedTiles[north.row][north.col] {
			visitedTiles[north.row][north.col] = true
			queue = append(queue, north)
		}

		if screen[east.row][east.col] != '#' && !visitedTiles[east.row][east.col] {
			visitedTiles[east.row][east.col] = true
			queue = append(queue, east)
		}

		if screen[south.row][south.col] != '#' && !visitedTiles[south.row][south.col] {
			visitedTiles[south.row][south.col] = true
			queue = append(queue, south)
		}

		if screen[west.row][west.col] != '#' && !visitedTiles[west.row][west.col] {
			visitedTiles[west.row][west.col] = true
			queue = append(queue, west)
		}
	}

	return -1
}

func inputCallback() int64 {
	switch robot.moveState {
	case MovementStateNorth:
		return 1
	case MovementStateEast:
		return 4
	case MovementStateSouth:
		return 2
	case MovementStateWest:
		return 3
	default:
		panic("no such movement state")
	}
}

func outputCallback(val int64) {
	switch val {
	case StatusWall:
		row, col := nextPosition(robot)
		screen[row][col] = '#'

		robot.moveState, robot.isBacktracking = chooseNextStep(robot)
		visitedTiles[row][col] = true
	case StatusSuccess:
		if targetRow == robot.row && targetCol == robot.col {
			screen[robot.row][robot.col] = 'X'
		} else {
			screen[robot.row][robot.col] = '.'
		}

		robot.row, robot.col = nextPosition(robot)
		screen[robot.row][robot.col] = 'D'

		if !robot.isBacktracking {
			fmt.Printf("recording step %s\n", mnemonicOf(robot.moveState))
			robot.steps = append(robot.steps, robot.moveState)
		}

		robot.moveState, robot.isBacktracking = chooseNextStep(robot)
		visitedTiles[robot.row][robot.col] = true

	case StatusOxygenSystem:
		screen[robot.row][robot.col] = '.'

		robot.row, robot.col = nextPosition(robot)
		screen[robot.row][robot.col] = 'D'
		targetRow, targetCol = robot.row, robot.col

		if !robot.isBacktracking {
			fmt.Printf("recording step %s\n", mnemonicOf(robot.moveState))
			robot.steps = append(robot.steps, robot.moveState)
		}

		robot.moveState, robot.isBacktracking = chooseNextStep(robot)
		visitedTiles[robot.row][robot.col] = true

	default:
		panic("received unknown status code")
	}

	fmt.Println("Drawing screen")
	showScreen()
	time.Sleep(50 * time.Millisecond)
}

func chooseNextStep(robot *Robot) (MovementState, bool) {
	if !visitedTiles[robot.row-1][robot.col] {
		return MovementStateNorth, false
	} else if !visitedTiles[robot.row][robot.col+1] {
		return MovementStateEast, false
	} else if !visitedTiles[robot.row+1][robot.col] {
		return MovementStateSouth, false
	} else if !visitedTiles[robot.row][robot.col-1] {
		return MovementStateWest, false
	}

	if len(robot.steps) == 0 {
		fmt.Printf("The shortest path is %d\n", findShortestPath())
		os.Exit(0)
	}

	backtrackStep := robot.steps[len(robot.steps)-1]
	robot.steps = robot.steps[:len(robot.steps)-1]
	fmt.Printf("backtracking to %d\n", oppositeMovementStateOf(backtrackStep))

	return oppositeMovementStateOf(backtrackStep), true
}

func oppositeMovementStateOf(state MovementState) MovementState {
	if state == MovementStateNorth {
		return MovementStateSouth
	} else if state == MovementStateSouth {
		return MovementStateNorth
	} else if state == MovementStateEast {
		return MovementStateWest
	} else if state == MovementStateWest {
		return MovementStateEast
	}

	panic("no such movement state")
}

func nextPosition(robot *Robot) (int, int) {
	switch robot.moveState {
	case MovementStateNorth:
		return robot.row - 1, robot.col
	case MovementStateEast:
		return robot.row, robot.col + 1
	case MovementStateSouth:
		return robot.row + 1, robot.col
	case MovementStateWest:
		return robot.row, robot.col - 1
	default:
		panic("no such movement state")
	}
}

func mnemonicOf(state MovementState) string {
	switch state {
	case MovementStateNorth:
		return "north"
	case MovementStateEast:
		return "east"
	case MovementStateSouth:
		return "south"
	case MovementStateWest:
		return "west"
	default:
		panic("unknown movement state")
	}
}

func initVisitedTiles() [][]bool {
	res := make([][]bool, len(screen))
	for row := range screen {
		res[row] = make([]bool, len(screen[row]))
	}

	return res
}

repository: preslavmihaylov/adventofcode

repo_name: preslavmihaylov/adventofcode


text:
#
#   Copyright (C) 2015 Pelagicore AB
#
#   SPDX-License-Identifier: MIT
#
require common-api-cmdline-common.inc

inherit cmake maven-properties

S = "${WORKDIR}/git/host-tools"

FILES_${PN} += "${datadir}/* \
${libdir}/cmake/* \
"

ALLOW_EMPTY_${PN} = "1"

BBCLASSEXTEND = "native nativesdk"

repository: sashko/meta-bistro

repo_name: sashko/meta-bistro


text:
require u-boot-ti.inc

DESCRIPTION = "u-boot bootloader for Multi-Core BU devices"

COMPATIBLE_MACHINE = "keystone"

PR = "r6"
PV_append = "+git${SRCPV}"

# Tag "K2_UBOOT_2013_01_15.07_01"
SRCREV = "5eaedcc4c2bca0ed971ee46694df7edc0cfa36cf"
BRANCH = "master"

SRC_URI = "git://git.ti.com/keystone-linux/u-boot.git;protocol=git;branch=${BRANCH}"

S = "${WORKDIR}/git"

UBOOT_SUFFIX = "bin"
UBOOT_MAKE_TARGET = "u-boot-spi.gph u-boot-nand.gph"

# SPI NOR Flash binaries
UBOOT_SPI_SPL_BINARY = "u-boot-spl.bin"
UBOOT_SPI_BINARY = "u-boot.img"
UBOOT_SPI_GPH_BINARY = "u-boot-spi.gph"
UBOOT_NAND_GPH_BINARY = "u-boot-nand.gph"

# SPI NOR Flash deployed images
UBOOT_SPI_SPL_IMAGE = "u-boot-spl-${MACHINE}-${PV}-${PR}.bin"
UBOOT_SPI_SPL_SYMLINK = "u-boot-spl-${MACHINE}.bin"
UBOOT_SPI_IMAGE = "u-boot-${MACHINE}-${PV}-${PR}.img"
UBOOT_SPI_SYMLINK = "u-boot-${MACHINE}.img"
UBOOT_SPI_GPH_IMAGE = "u-boot-spi-${MACHINE}-${PV}-${PR}.gph"
UBOOT_SPI_GPH_SYMLINK = "u-boot-spi-${MACHINE}.gph"
UBOOT_NAND_GPH_IMAGE = "u-boot-nand-${MACHINE}-${PV}-${PR}.gph"
UBOOT_NAND_GPH_SYMLINK = "u-boot-nand-${MACHINE}.gph"

do_install_append () {
	install ${S}/spl/${UBOOT_SPI_SPL_BINARY} ${D}/boot/${UBOOT_SPI_SPL_IMAGE}
	ln -sf ${UBOOT_SPI_SPL_IMAGE} ${D}/boot/${UBOOT_SPI_SPL_BINARY}

	install ${S}/${UBOOT_SPI_BINARY} ${D}/boot/${UBOOT_SPI_IMAGE}
	ln -sf ${UBOOT_SPI_IMAGE} ${D}/boot/${UBOOT_SPI_BINARY}

	install ${S}/${UBOOT_SPI_GPH_BINARY} ${D}/boot/${UBOOT_SPI_GPH_IMAGE}
	ln -sf ${UBOOT_SPI_GPH_IMAGE} ${D}/boot/${UBOOT_SPI_GPH_BINARY}

        install ${S}/${UBOOT_NAND_GPH_BINARY} ${D}/boot/${UBOOT_NAND_GPH_IMAGE}
        ln -sf ${UBOOT_NAND_GPH_IMAGE} ${D}/boot/${UBOOT_NAND_GPH_BINARY}
}

do_deploy_append () {
	install ${S}/spl/${UBOOT_SPI_SPL_BINARY} ${DEPLOYDIR}/${UBOOT_SPI_SPL_IMAGE}
	rm -f ${UBOOT_SPI_SPL_BINARY} ${UBOOT_SPI_SPL_SYMLINK}
	ln -sf ${UBOOT_SPI_SPL_IMAGE} ${UBOOT_SPI_SPL_SYMLINK}
	ln -sf ${UBOOT_SPI_SPL_IMAGE} ${UBOOT_SPI_SPL_BINARY}

	install ${S}/${UBOOT_SPI_BINARY} ${DEPLOYDIR}/${UBOOT_SPI_IMAGE}
	rm -f ${UBOOT_SPI_BINARY} ${UBOOT_SPI_SYMLINK}
	ln -sf ${UBOOT_SPI_IMAGE} ${UBOOT_SPI_SYMLINK}
	ln -sf ${UBOOT_SPI_IMAGE} ${UBOOT_SPI_BINARY}

	install ${S}/${UBOOT_SPI_GPH_BINARY} ${DEPLOYDIR}/${UBOOT_SPI_GPH_IMAGE}
	rm -f ${UBOOT_SPI_GPH_BINARY} ${UBOOT_SPI_GPH_SYMLINK}
	ln -sf ${UBOOT_SPI_GPH_IMAGE} ${UBOOT_SPI_GPH_SYMLINK}
	ln -sf ${UBOOT_SPI_GPH_IMAGE} ${UBOOT_SPI_GPH_BINARY}

        install ${S}/${UBOOT_NAND_GPH_BINARY} ${DEPLOYDIR}/${UBOOT_NAND_GPH_IMAGE}
        rm -f ${UBOOT_NAND_GPH_BINARY} ${UBOOT_NAND_GPH_SYMLINK}
        ln -sf ${UBOOT_NAND_GPH_IMAGE} ${UBOOT_NAND_GPH_SYMLINK}
        ln -sf ${UBOOT_NAND_GPH_IMAGE} ${UBOOT_NAND_GPH_BINARY}
}

repository: joelagnel/meta-ti

repo_name: joelagnel/meta-ti