text:
package main

import (
	"bufio"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/davecgh/go-spew/spew"
	"github.com/gogo/protobuf/proto"
	"github.com/teamtalk-remix/test-client-go/cmd/test-client/help"
	"github.com/teamtalk-remix/test-client-go/cmd/test-client/utils"
	"github.com/teamtalk-remix/test-client-go/pkg/pdubase"
	b "github.com/teamtalk-remix/test-client-go/proto/IM_BaseDefine"
	"github.com/teamtalk-remix/test-client-go/proto/IM_Login"
	"github.com/teamtalk-remix/test-client-go/proto/IM_Message"
	"github.com/teamtalk-remix/test-client-go/proto/IM_Other"
)

var (
	logfileStr = fmt.Sprintf("/tmp/testc-%s.log", time.Now().Format("20060102150405"))
	logpath    = flag.String("logpath", logfileStr, "Log Path")
)

var globalConn net.Conn
var msgid uint32

const CLIENT_HEARTBEAT_INTERVAL = 30000

func Connect(serverIP, serverPort string) (net.Conn, error) {
	c, err := net.Dial("tcp", serverIP+":"+serverPort)
	if err != nil {
		return nil, err
	}
	return c, nil
}

func SendMsg(conn net.Conn, from, to uint32, s string) {
	msgid = msgid + 1
	mt := b.MsgType_MSG_TYPE_SINGLE_TEXT
	msg := &IM_Message.IMMsgData{
		FromUserId:  proto.Uint32(from),
		ToSessionId: proto.Uint32(to),
		MsgId:       proto.Uint32(msgid),
		MsgData:     []byte(s),
		CreateTime:  proto.Uint32(uint32(time.Now().Unix())),
		MsgType:     &mt,
	}
	var pdu pdubase.CImPdu
	pdu.SetServiceId(b.ServiceID_SID_MSG)
	pdu.SetCommandId(b.CommandID_CID_MSG_DATA)
	pdu.SetPB(msg)

	_, err := conn.Write(pdu.Buffer().Bytes())
	if err != nil {
		checkErr(err)
	}
}

func SendLogin(conn net.Conn, userName, userPass string) {
	ols := b.UserStatType_USER_STATUS_ONLINE
	ct := b.ClientType_CLIENT_TYPE_WINDOWS

	msg := &IM_Login.IMLoginReq{
		UserName:      proto.String(userName),
		Password:      proto.String(getMD5Hash(userPass)),
		OnlineStatus:  &ols,
		ClientType:    &ct,
		ClientVersion: proto.String("1.0"),
	}
	var pdu pdubase.CImPdu
	pdu.SetServiceId(b.ServiceID_SID_LOGIN)
	pdu.SetCommandId(b.CommandID_CID_LOGIN_REQ_USERLOGIN)
	pdu.SetPB(msg)

	_, err := conn.Write(pdu.Buffer().Bytes())
	if err != nil {
		checkErr(err)
	}
}

func SendHeartBeat(conn net.Conn, d time.Duration) {
	for x := range time.Tick(d) {
		if conn != nil {
			utils.Log.Println("Time: ", x)
			msg := &IM_Other.IMHeartBeat{}
			var pdu pdubase.CImPdu
			pdu.SetServiceId(b.ServiceID_SID_OTHER)
			pdu.SetCommandId(b.CommandID_CID_OTHER_HEARTBEAT)
			pdu.SetPB(msg)
			_, err := conn.Write(pdu.Buffer().Bytes())
			if err != nil {
				checkErr(err)
			}
			utils.Log.Println("Sending heartbeat succeed")
		} else {
			utils.Log.Println("globalConn is null exit....")
			break
		}
	}
}

func HandleLoginResponse(conn net.Conn, pdu pdubase.CImPdu) {
	msg := IM_Login.IMLoginRes{}
	pdu.GetPBMsg(pdu.Buffer().Bytes(), &msg)
	spew.Dump(msg.String())
	spew.Dump(msg.GetResultCode())
	spew.Dump(msg.GetResultString())
	spew.Dump(msg.GetUserInfo())

	if msg.GetResultCode() == b.ResultType_REFUSE_REASON_NONE {
		go SendHeartBeat(conn, CLIENT_HEARTBEAT_INTERVAL*time.Millisecond)
	}
}

func HandleMsgDataResponse(conn net.Conn, pdu pdubase.CImPdu) {
	msg := IM_Message.IMMsgData{}
	pdu.GetPBMsg(pdu.Buffer().Bytes(), &msg)
	spew.Dump("receive HandleMsgDataResponse from:", msg.FromUserId, msg.MsgType)
	spew.Dump(msg.String())
}

func HandleListAllUserResponse(conn net.Conn, pdu pdubase.CImPdu) {
	//IM::Buddy::IMAllUserRsp msgResp;
	//uint32_t nSeqNo = pPdu->GetSeqNum();
	//if(msgResp.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
	//{
	//	uint32_t userCnt = msgResp.user_list_size();
	//	printf("get %d users\n", userCnt);
	//	list<IM::BaseDefine::UserInfo> lsUsers;
	//	for(uint32_t i=0; i<userCnt; ++i)
	//	{
	//	IM::BaseDefine::UserInfo cUserInfo = msgResp.user_list(i);
	//	lsUsers.push_back(cUserInfo);
	//	}
	//	m_pCallback->onGetChangedUser(nSeqNo, lsUsers);
	//}
	//else
	//{
	//	m_pCallback->onError(nSeqNo, pPdu->GetCommandId(), "parse pb error");
	//}
}

func HandleListUserInfoResponse(conn net.Conn, pdu pdubase.CImPdu) {
	//IM::Buddy::IMUsersInfoRsp msgResp;
	//uint32_t nSeqNo = pPdu->GetSeqNum();
	//if(msgResp.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
	//{
	//	uint32_t userCnt = msgResp.user_info_list_size();
	//	list<IM::BaseDefine::UserInfo> lsUser;
	//	for (uint32_t i=0; i<userCnt; ++i) {
	//IM::BaseDefine::UserInfo userInfo = msgResp.user_info_list(i);
	//	lsUser.push_back(userInfo);
	//}
	//	m_pCallback->onGetUserInfo(nSeqNo, lsUser);
	//}
	//else
	//{
	//	m_pCallback->onError(nSeqNo, pPdu->GetCommandId(), "parse pb error");
	//}
}

func HandleMsgDataAck(conn net.Conn, pdu pdubase.CImPdu) {
	//IM::Message::IMMsgDataAck msgResp;
	//uint32_t nSeqNo = pPdu->GetSeqNum();
	//if(msgResp.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
	//{
	//uint32_t nSendId = msgResp.user_id();
	//uint32_t nRecvId = msgResp.session_id();
	//uint32_t nMsgId = msgResp.msg_id();
	//IM::BaseDefine::SessionType nType = msgResp.session_type();
	//m_pCallback->onSendMsg(nSeqNo, nSendId, nRecvId, nType, nMsgId);
	//}
	//else
	//{
	//m_pCallback->onError(nSeqNo, pPdu->GetCommandId(), "parse pb error");
	//}
}

func HandleMsgListResponse(conn net.Conn, pdu pdubase.CImPdu) {
	//IM::Message::IMGetMsgListRsp msgResp;
	//uint32_t nSeqNo = pPdu->GetSeqNum();
	//if(msgResp.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
	//{
	//	uint32_t nUserId= msgResp.user_id();
	//IM::BaseDefine::SessionType nSessionType = msgResp.session_type();
	//	uint32_t nPeerId = msgResp.session_id();
	//	uint32_t nMsgId = msgResp.msg_id_begin();
	//	uint32_t nMsgCnt = msgResp.msg_list_size();
	//	list<IM::BaseDefine::MsgInfo> lsMsg;
	//	for(uint32_t i=0; i<nMsgCnt; ++i)
	//	{
	//	IM::BaseDefine::MsgInfo msgInfo = msgResp.msg_list(i);
	//	lsMsg.push_back(msgInfo);
	//	}
	//	m_pCallback->onGetMsgList(nSeqNo, nUserId, nPeerId, nSessionType, nMsgId, nMsgCnt, lsMsg);
	//}
	//else
	//{
	//	m_pCallback->onError(nSeqNo, pPdu->GetCommandId(), "parse pb falied");
	//}
}

func HandleMsgUnreadCntResponse(conn net.Conn, pdu pdubase.CImPdu) {
	//IM::Message::IMUnreadMsgCntRsp msgResp;
	//uint32_t nSeqNo = pPdu->GetSeqNum();
	//if(msgResp.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
	//{
	//	list<IM::BaseDefine::UnreadInfo> lsUnreadInfo;
	//	uint32_t nUserId = msgResp.user_id();
	//	uint32_t nTotalCnt = msgResp.total_cnt();
	//	uint32_t nCnt = msgResp.unreadinfo_list_size();
	//	for (uint32_t i=0; i<nCnt; ++i) {
	//IM::BaseDefine::UnreadInfo unreadInfo = msgResp.unreadinfo_list(i);
	//	lsUnreadInfo.push_back(unreadInfo);
	//}
	//	m_pCallback->onGetUnreadMsgCnt(nSeqNo, nUserId, nTotalCnt, lsUnreadInfo);
	//}
	//else
	//{
	//	m_pCallback->onError(nSeqNo, pPdu->GetCommandId(), "parse pb fail");
	//}
}
func HandleRecentContactSessionResponse(conn net.Conn, pdu pdubase.CImPdu) {
	//IM::Buddy::IMRecentContactSessionRsp msgResp;
	//uint32_t nSeqNo = pPdu->GetSeqNum();
	//if(msgResp.ParseFromArray(pPdu->GetBodyData(), pPdu->GetBodyLength()))
	//{
	//	list<IM::BaseDefine::ContactSessionInfo> lsSession;
	//	uint32_t nUserId = msgResp.user_id();
	//	uint32_t nCnt = msgResp.contact_session_list_size();
	//	for (uint32_t i=0; i<nCnt; ++i) {
	//IM::BaseDefine::ContactSessionInfo session = msgResp.contact_session_list(i);
	//	lsSession.push_back(session);
	//}
	//	m_pCallback->onGetRecentSession(nSeqNo, nUserId, lsSession);
	//}
	//else
	//{
	//	m_pCallback->onError(nSeqNo, pPdu->GetCommandId(), "parse pb error");
	//}
}

//func Timer
func HandlePdu(conn net.Conn, pdu pdubase.CImPdu) {
	switch pdu.CommandId() {
	case b.CommandID_CID_OTHER_HEARTBEAT:
		utils.Log.Println("HandlePdu:  heartbeat received....")
	case b.CommandID_CID_LOGIN_RES_USERLOGIN:
		HandleLoginResponse(conn, pdu)
	case b.CommandID_CID_BUDDY_LIST_ALL_USER_RESPONSE:
		HandleListAllUserResponse(conn, pdu)
	case b.CommandID_CID_BUDDY_LIST_USER_INFO_RESPONSE:
		HandleListUserInfoResponse(conn, pdu)
	case b.CommandID_CID_MSG_UNREAD_CNT_RESPONSE:
		HandleMsgUnreadCntResponse(conn, pdu)
	case b.CommandID_CID_BUDDY_LIST_RECENT_CONTACT_SESSION_RESPONSE:
		HandleRecentContactSessionResponse(conn, pdu)
	case b.CommandID_CID_MSG_LIST_RESPONSE:
		HandleMsgListResponse(conn, pdu)
	case b.CommandID_CID_MSG_DATA_ACK:
		HandleMsgDataAck(conn, pdu)
	case b.CommandID_CID_MSG_DATA:
		HandleMsgDataResponse(conn, pdu)
	case b.CommandID_CID_BUDDY_LIST_STATUS_NOTIFY:

	default:
		utils.Log.Println("wrong msg_type", pdu.CommandId(), pdu.ServiceId())
	}
}

func checkErr(err error) {
	if err == nil {
		utils.Log.Println("Ok")
		return

	} else if netError, ok := err.(net.Error); ok && netError.Timeout() {
		utils.Log.Println("Timeout")
		return
	}

	switch t := err.(type) {
	case *net.OpError:
		if t.Op == "dial" {
			utils.Log.Println("Unknown host")
		} else if t.Op == "read" {
			utils.Log.Println("Connection refused")
		}

	case syscall.Errno:
		if t == syscall.ECONNREFUSED {
			utils.Log.Println("Connection refused")
		}
	}
}

func testReceiveLoginResponse(conn net.Conn) {
	for {
		headerBuf := make([]byte, pdubase.PduHeaderSize)
		_, err := conn.Read(headerBuf)
		if err != nil {
			utils.Log.Println("Breaking......:", err.Error())
			checkErr(err)
			break
		}

		//deal with heartbeat
		var pdu pdubase.CImPdu
		pdu.GetHeader(headerBuf)
		pdu.Length()
		bodyBuf := make([]byte, pdu.Length()-pdubase.PduHeaderSize)
		_, err = conn.Read(bodyBuf[:pdu.Length()-pdubase.PduHeaderSize])
		if err != nil {
			utils.Log.Println("Breaking......:", err.Error())
			checkErr(err)
			break
		}
		//copy
		pdu.WriteBuffer(bodyBuf)
		HandlePdu(conn, pdu)
	}
}

func recvMsg(conn net.Conn) {
	utils.Log.Println("\n-> start lisiten.....")
	testReceiveLoginResponse(conn)
}

func getMD5Hash(text string) string {
	hash := md5.Sum([]byte(text))
	return hex.EncodeToString(hash[:])
}

func login(conn net.Conn, userName, userPass string) {
	SendLogin(conn, userName, userPass)
}

type httpResponse struct {
	BackupIP   string `json:"backupIP"`
	Code       int    `json:"code"`
	Discovery  string `json:"discovery"`
	MsfsBackup string `json:"msfsBackup"`
	MsfsPrior  string `json:"msfsPrior"`
	Msg        string `json:"msg"`
	Port       string `json:"port"`
	PriorIP    string `json:"priorIP"`
}

func getMsgServerIPPort() (string, string) {
	resp, err := http.Get("http://teamtalk-ng-login.cloud.matrix.int.iwarp.org/msg_server")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	res := httpResponse{}
	err = json.Unmarshal(body, &res)
	if err != nil {
		panic(err)
	}
	if res.Code != 0 {
		utils.Log.Panic("res.Code is not 0")
	}

	if res.PriorIP == "" {
		return res.BackupIP, res.Port
	}
	return "10.110.196.118", "8000"
	//return res.PriorIP, res.Port
}

func main() {

	utils.NewLog(*logpath)
	fmt.Println("Simple Client, type 'help' to show commands")
	fmt.Println("---------------------")

	for {
		fmt.Print("-> ")
		reader := bufio.NewReader(os.Stdin)
		text, _ := reader.ReadString('\n')
		// convert CRLF to LF
		text = strings.Replace(text, "\n", "", -1)

		cmds := strings.Fields(text)
		if len(cmds) <= 0 {
			continue
		}

		switch cmds[0] {
		case "help":
			help.PrintHelp()
		case "login":
			if globalConn != nil {
				fmt.Println("client already login in...")
				continue
			}
			userName, userPass := cmds[1], cmds[2]
			serverIP, serverPort := getMsgServerIPPort()
			var err error
			globalConn, err = Connect(serverIP, serverPort)
			if err != nil {
				panic(err)
			}
			login(globalConn, userName, userPass)
			//TODO: this recvMsg could move out of switch block
			go recvMsg(globalConn)
		case "sendmsg":
			if globalConn == nil {
				fmt.Println("globalConn does not exist... please run connect command first...")
				os.Exit(1)
			}
			from, err := strconv.Atoi(cmds[1])
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
			to, err := strconv.Atoi(cmds[2])
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
			go SendMsg(globalConn, uint32(from), uint32(to), cmds[3])
		case "exit":
			if globalConn != nil {
				globalConn.Close()
			}
			fmt.Println("haha exit...")
			os.Exit(0)
		default:
			help.PrintHelp()
		}
	}
}

repository: teamtalk-remix/test-client-go

repo_name: teamtalk-remix/test-client-go


text:
# Copyright (c) 2012-2018 LG Electronics, Inc.

SUMMARY="The Download Manager service supports the downloading and uploading of files to and from a HP webOS device."
AUTHOR = "Sangwoo Kang <sangwoo82.kang@lge.com>"
SECTION = "webos/apps"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10"

DEPENDS = "libpbnjson luna-service2 sqlite3 curl uriparser pmloglib jemalloc luna-prefs boost glib-2.0"

RDEPENDS:${PN} = "applicationinstallerutility"

PV = "4.0.0-11+git${SRCPV}"
SRCREV = "53db994c5e00f653a3d663c50a95b566237f087b"

inherit webos_cmake
inherit webos_system_bus
inherit webos_public_repo
inherit webos_systemd
inherit pkgconfig

SRC_URI = "${WEBOSOSE_GIT_REPO_COMPLETE} \
file://0001-luna-webappmanager-Install-to-usr-sbin-instead-of-us.patch \
file://0002-luna-downloadmanager-Fix-format-warnings-remove-unus.patch \
file://0003-Add-systemd-service-file-at-expected-location-unify-.patch \
file://0004-luna-downloadmgr-Fix-LS2-permissions.patch \
file://0005-filesystemStatusCheck-first-implementation.patch \
file://0006-DownloadManager.cpp-Make-org.webosports-privileged-a.patch \
"
S = "${WORKDIR}/git"

FILES:${PN} += " \
    ${systemd_unitdir}/system \
"

license: MIT

repository: webOS-ports/meta-webos-ports

license_type: permissive

repo_name: webOS-ports/meta-webos-ports

branch_name: refs/heads/kirkstone

gha_language: BitBake

extension: bb


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

// @author Su Wei <suwei007@gmail.com>

package model

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

	"github.com/aws/aws-sdk-go/aws"
	uuid "github.com/satori/go.uuid"
	log "github.com/sirupsen/logrus"
)

//EC2Profile is model struct
type EC2Profile struct {
	PriceModel   *string `json:"priceModel,omitempty"`
	InstanceType *string `json:"instanceType,omitempty"`
}

//FFmpegProfile  is model struct
type FFmpegProfile struct {
	Codec       *string `json:"codec,omitempty"`
	OriginCodec *string `json:"originCodec,omitempty"`
	Scale       *string `json:"scale,omitempty"`
	Bitrate     *string `json:"bitrate,omitempty"`
	BufferSize  *string `json:"buffersize,omitempty"`
	Profile     *string `json:"profile,omitempty"`
	Platform    *string `json:"platform,omitempty"`
}

//JobProfile is API
type JobProfile struct {
	EC2Profile    *EC2Profile    `json:"ec2,omitempty"`
	FFmpegProfile *FFmpegProfile `json:"ffmpeg,omitempty"`
	VMAFProfile   *VMAFProfile   `json:"vmaf,omitempty"`
}

//Job is model struct use UI and SQS_Worker
type Job struct {
	UserID      *string     `json:"userid,omitempty"`
	JobID       *string     `json:"jobid,omitempty"`
	Input       *string     `json:"input,omitempty"`
	BatchInputs []string    `json:"batchInputs,omitempty"`
	Output      *string     `json:"output,omitempty"`
	Priority    int         `json:"priority,omitempty"`
	Profile     *JobProfile `json:"profile,omitempty"`
}

type JobOutput struct {
	UserID *string    `json:"userid,omitempty"`
	JobID  *string    `json:"jobid,omitempty"`
	Input  *string    `json:"input,omitempty"`
	Output *string    `json:"output,omitempty"`
	Status *JobStatus `json:"status,omitempty"`
}

type JobStatus struct {
	Event   *string `json:"event,omitempty"`
	Status  *string `json:"status,omitempty"`
	Message *string `json:"message,omitempty"`
}

type VMAFJob struct {
	UserID     *string     `json:"userid,omitempty"`
	JobID      *string     `json:"jobid,omitempty"`
	InputFile  *string     `json:"input,omitempty"`
	OriginFile *string     `json:"origin,omitempty"`
	Output     *string     `json:"output,omitempty"`
	Profile    *JobProfile `json:"profile,omitempty"`
	Status     *JobStatus  `json:"status,omitempty"`
}

type VMAFProfile struct {
	Scale  *string `json:"scale,omitempty"`
	SSIM   *string `json:"ssim,omitempty"`
	PSNR   *string `json:"psnr,omitempty"`
	MSSSIM *string `json:"ms-ssim,omitempty"`
}

const JobEventSummit = "JobSummit"
const JobEventStart = "JobStart"
const JobEventFinished = "JobFinished"

func int2size(size int) string {
	if size < 1024 {
		return fmt.Sprintf("%dK", size)
	}
	return fmt.Sprintf("%dM", size/1024)
}

func size2int(size string) (int, error) {

	invalidByteQuantityError := fmt.Errorf("invalid format %s,  etc. 1K,1KB, 1M, 1MB", size)
	size = strings.TrimSpace(size)
	size = strings.ToUpper(size)

	i := strings.IndexFunc(size, unicode.IsLetter)

	if i == -1 {
		return 0, invalidByteQuantityError
	}

	bytesString, multiple := size[:i], size[i:]
	bytes, err := strconv.ParseFloat(bytesString, 64)
	if err != nil || bytes < 0 {
		return 0, invalidByteQuantityError
	}

	switch multiple {
	case "M", "MB", "MIB":
		return int(bytes * 1024), nil
	case "K", "KB", "KIB":
		return int(bytes), nil
	default:
		return 0, invalidByteQuantityError
	}

}

func (j *VMAFJob) prepareCommonProfile() error {
	if j.Profile == nil || j.Profile.VMAFProfile == nil {
		return fmt.Errorf("not found profile %s, %s", *j.UserID, *j.JobID)
	}
	if _, exits := vmafScaleMap[*j.Profile.VMAFProfile.Scale]; !exits {
		return fmt.Errorf("scale config error %s, %s, %s", *j.UserID, *j.JobID, *j.Profile.VMAFProfile.Scale)
	}
	j.Profile.VMAFProfile.Scale = aws.String(vmafScaleMap[*j.Profile.VMAFProfile.Scale])

	return nil
}

func (j *Job) prepareCommonProfile() error {

	var scale string
	var exits bool

	platform := *j.Profile.FFmpegProfile.Platform
	profile := *j.Profile.FFmpegProfile.Profile

	//check platform ["CPU", "GPU"]
	if !HasElem(ec2Platform, platform) {
		return fmt.Errorf("Profile build Wrong, invalid FFmpeg platform: %s ", *j.Profile.FFmpegProfile.Platform)
	}

	//check profile ["quality", "latency"]
	if !HasElem(ffmpegProfile, *j.Profile.FFmpegProfile.Profile) {
		return fmt.Errorf("Profile build Wrong, invalid FFmpeg profile: %s ", *j.Profile.FFmpegProfile.Profile)
	}

	bitrate, err := size2int(*j.Profile.FFmpegProfile.Bitrate)
	if err != nil {
		return fmt.Errorf("Profile build Wrong, invalid bitrate : %s ", *j.Profile.FFmpegProfile.BufferSize)
	}

	//check job priority [0,100]
	if j.Priority < 0 || j.Priority > 100 {
		return fmt.Errorf("Profile build Wrong, invalid Job Priority: %d ", j.Priority)
	}

	//check scale ["1080p", "720p", "480p", "360p", "240p"]
	if scale, exits = ffmpegScaleMap[*j.Profile.FFmpegProfile.Scale]; !exits {
		return fmt.Errorf("Profile build Wrong, invalid Scale: %s ", *j.Profile.FFmpegProfile.Scale)
	}

	//check profile , set buffersize
	if profile == "quality" {
		j.Profile.FFmpegProfile.BufferSize = aws.String(int2size(bitrate * 2))
	}

	if profile == "latency" {
		j.Profile.FFmpegProfile.BufferSize = aws.String(int2size(bitrate / 25))
	}

	j.Profile.FFmpegProfile.Scale = aws.String(scale)

	if platform == "cpu" {
		return j.prepareCPUProfile()
	}

	if platform == "gpu" {
		if j.Profile.FFmpegProfile.OriginCodec == nil {
			j.Profile.FFmpegProfile.OriginCodec = aws.String("h264")
		}
		return j.prepareGPUProfile()
	}

	return nil

}

func (j *Job) prepareCPUProfile() error {

	var codec string
	var exits bool

	if codec, exits = ffmpegCPUCodesMap[*j.Profile.FFmpegProfile.Codec]; !exits {
		return fmt.Errorf("CPUProfile build Wrong, invalid CODEC: %s ", *j.Profile.FFmpegProfile.Codec)
	}

	j.Profile.FFmpegProfile.Codec = aws.String(codec)

	return nil
}

func (j *Job) prepareGPUProfile() error {

	var codec string
	var exits bool

	if codec, exits = ffmpegGPUCodesMap[*j.Profile.FFmpegProfile.Codec]; !exits {
		return fmt.Errorf("GPUProfile build Wrong, invalid CODEC: %s ", *j.Profile.FFmpegProfile.Codec)
	}

	j.Profile.FFmpegProfile.Codec = aws.String(codec)

	//设置originCodec
	if codec, exits = ffmpegGPUOriginCodesMap[*j.Profile.FFmpegProfile.OriginCodec]; !exits {
		return fmt.Errorf("CPUProfile build Wrong, invalid CODEC: %s ", *j.Profile.FFmpegProfile.Codec)
	}

	j.Profile.FFmpegProfile.Codec = aws.String(codec)

	return nil
}

func HasElem(s interface{}, elem interface{}) bool {
	arrV := reflect.ValueOf(s)

	if arrV.Kind() == reflect.Slice {
		for i := 0; i < arrV.Len(); i++ {

			// XXX - panics if slice element points to an unexported struct field
			// see https://golang.org/pkg/reflect/#Value.Interface
			if arrV.Index(i).Interface() == elem {
				return true
			}
		}
	}

	return false
}

//NewJob build job from job
func NewJob(data []byte) (*Job, error) {

	job := &Job{}
	err := json.Unmarshal(data, job)
	if err != nil {
		return nil, err
	}

	u1 := uuid.Must(uuid.NewV4())
	job.JobID = aws.String(u1.String())
	err = job.prepareCommonProfile()
	if err != nil {
		return nil, err
	}

	return job, nil
}

//NewVMAFJob build job from job
func NewVMAFJob(data []byte) (*VMAFJob, error) {

	job := &VMAFJob{}
	err := json.Unmarshal(data, job)
	if err != nil {
		return nil, err
	}

	u1 := uuid.Must(uuid.NewV4())
	job.JobID = aws.String(u1.String())
	err = job.prepareCommonProfile()
	if err != nil {
		return nil, err
	}

	return job, nil
}

func (job *Job) IsBatchJob() bool {
	if job.Input == nil && len(job.BatchInputs) > 0 {
		return true
	}
	return false
}

func (job *Job) BuildBatchJobs() ([]*Job, error) {
	if !job.IsBatchJob() {
		data, err := json.Marshal(job)
		if err != nil {
			log.Errorf("Job marshal failed [userid:%s] ", *job.UserID)
		}
		log.Errorf("Job [userid:%s] is not batch job ", *job.UserID)
		log.Debugf("Job %s", string(data))
		return nil, fmt.Errorf("Job [userid:%s] is not batch job ", *job.UserID)

	}

	batchInputs := job.BatchInputs
	jobs := []*Job{}
	for idx := range batchInputs {
		u1 := uuid.Must(uuid.NewV4())

		jobs = append(jobs, &Job{

			UserID:      aws.String(*job.UserID),
			JobID:       aws.String(u1.String()),
			Input:       aws.String(batchInputs[idx]),
			BatchInputs: nil,
			Output:      aws.String(*job.Output),
			Priority:    job.Priority,
			Profile:     job.Profile,
		})
	}

	return jobs, nil
}

repository: mpc-sigs/mpc-elastic-recode

repo_name: mpc-sigs/mpc-elastic-recode

branch_name: refs/heads/main

extension: go


text:
package apiserver

import "testing"

func TestCreateDatabase(t *testing.T) {

}

func TestGetDatabaseStatus(t *testing.T) {

}

func TestUpdateDatabaseStatus(t *testing.T) {

}

branch_name: refs/heads/master


text:
require midori.inc

DEPENDS += "python-native python-docutils-native"

# increment PR every time SRCREV is updated!
PR = "r2"
PV = "0.1.2+${PR}+gitr${SRCREV}"

SRC_URI = "git://git.xfce.org/kalikiana/midori;protocol=git"
S = "${WORKDIR}/git"

do_configure() {
	./configure \
            --prefix=${prefix} \
            --bindir=${bindir} \
            --sbindir=${sbindir} \
            --libexecdir=${libexecdir} \
            --datadir=${datadir} \
            --sysconfdir=${sysconfdir} \
            --sharedstatedir=${sharedstatedir} \
            --localstatedir=${localstatedir} \
            --libdir=${libdir} \
            --includedir=${includedir} \
            --infodir=${infodir} \
            --mandir=${mandir} \
            ${EXTRA_OECONF}

	sed -i /LINK_CC/d ./_build_/c4che/default.cache.py
	echo "LINK_CC = '${CXX}'" >>  ./_build_/c4che/default.cache.py
}


text:
package cmd

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/luckydog8686/ginlogger"
)

func Run(listenAddr string,handlers map[string]gin.HandlerFunc)  {
	router := gin.New()
	router.Use(ginlogger.Logger(), gin.Recovery())
	for k,v := range handlers {
		router.POST(fmt.Sprintf("/%s",k),v)
	}
	router.Run(listenAddr)
}

gha_license_id: MIT

gha_language: Go


text:
FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}-${PV}:"

LINUX_VERSION ?= "4.16.2"
KBRANCH ?= "linux-4.16.y"
SRCREV ?= "216f33936eaa006a8b4f5bb992592e34f6432fc2"

require linux-stable.inc

SRC_URI_append = " file://odroid.scc"
SRC_URI_append_odroid-xu3 = " file://${O_KERNEL_CONFIG}/fb.cfg"
SRC_URI_append_odroid-xu3-lite = " file://${O_KERNEL_CONFIG}/fb.cfg"
SRC_URI_append_odroid-xu4 = " file://${O_KERNEL_CONFIG}/fb.cfg"

repository: DerelictRobot/meta-odroid

repo_name: DerelictRobot/meta-odroid


text:
package user

import (
	"Gf-Vben/app/service/response"
	"Gf-Vben/app/service/user"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func Register(r *ghttp.Request) {
	var req *user.RegisterReq
	if err := r.Parse(&req); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if err := req.Register(); err != nil {
		response.JsonExit(r, 2, err.Error())
	}
	response.JsonExit(r, 0, "注册成功")

}
func Info(r *ghttp.Request) {
	var req *user.Req
	if err := r.Parse(&req); err != nil {
		response.JsonExit(r, 1, err.Error())
	}

	//if err != nil {
	//	response.JsonExit(r, 2, err.Error())
	//}
	response.JsonExit(r, 0, "", g.Map{"username": "vben", "roles": []string{"admin"}})
}

repository: gostool/gf-vben

repo_name: gostool/gf-vben


text:
DESCRIPTION = "Packagegroup for Intrusion Detection System (IDS) utilities."
LICENSE = "MIT"
LIC_FILES_CHKSUM = "\
    file://${COREBASE}/LICENSE;md5=4d92cd373abda3937c2bc47fbc49d690 \
    file://${COREBASE}/meta/COPYING.MIT;md5=3da9cfbcb788c80a0384361b4de20420 \
"

inherit packagegroup

RDEPENDS_${PN} += "\
    snort \
    mtree \
"

repository: GuojianZhou/meta-secure-core

repo_name: GuojianZhou/meta-secure-core


text:
package viz

import (
    "reflect"
	"testing"
)

func TestDot2SVG(t *testing.T) {
    dotExample := "digraph G { A -> B } graph H { C - D }"

	tests := []struct {
		name string
        args string
		notWant string
	}{
		{"smoke", dotExample, ""},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := Dot2SVG(tt.args); reflect.DeepEqual(got, tt.notWant) {
				t.Errorf("Dot2SVG() = %v, NOT want %v", got, tt.notWant)
            } else {
                t.Log(got)
            }
		})
	}
}

repository: pennz/DataViz

repo_name: pennz/DataViz


text:
#pragma once

#include <cstdint>

namespace NWNXLib {

namespace API {

struct NWModuleHeader_st
{
    char pModuleID[32];
    int32_t nModuleCreatorID;
    uint32_t nModuleVersion;
};

}

}

repository: presscad/nwnee

repo_name: presscad/nwnee

extension: hpp


text:
package account

import (
	"encoding/json"
	"github.com/DancesportSoftware/das/auth"
	"github.com/DancesportSoftware/das/businesslogic"
	"github.com/DancesportSoftware/das/controller/util"
	"github.com/DancesportSoftware/das/viewmodel"
	"gopkg.in/validator.v2"
	"log"
	"net/http"
	"time"
)

type RoleApplicationServer struct {
	auth    auth.IAuthenticationStrategy
	service businesslogic.RoleProvisionService
}

func NewRoleApplicationServer(authStrat auth.IAuthenticationStrategy, service businesslogic.RoleProvisionService) RoleApplicationServer {
	return RoleApplicationServer{
		auth:    authStrat,
		service: service,
	}
}

// CreateRoleApplicationHandler handles the request:
//	POST /api/v1.0/account/role/application
// Accepted JSON payload:
//	{
//		"role": 2,
//		"description": "I am applying this role because..."
//	}
// Sample response payload:
//	{
//		"status": 200,
//		"message":
//		"data": null
//	}
func (server RoleApplicationServer) CreateRoleApplicationHandler(w http.ResponseWriter, r *http.Request) {
	currentUser, authErr := server.auth.GetCurrentUser(r)
	if authErr != nil {
		util.RespondJsonResult(w, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	applicationDTO := new(viewmodel.SubmitRoleApplication)
	parseErr := util.ParseRequestBodyData(r, applicationDTO)

	if parseErr != nil {
		util.RespondJsonResult(w, http.StatusBadRequest, "bad application data, please try again", nil)
		return
	}

	if errs := validator.Validate(applicationDTO); errs != nil {
		util.RespondJsonResult(w, http.StatusBadRequest, errs.Error(), nil)
		return
	}

	application := businesslogic.RoleApplication{
		AccountID:       currentUser.ID,
		AppliedRoleID:   applicationDTO.RoleID,
		Description:     applicationDTO.Description,
		StatusID:        businesslogic.RoleApplicationStatusPending,
		ApprovalUserID:  nil,
		CreateUserID:    currentUser.ID,
		DateTimeCreated: time.Now(),
		UpdateUserID:    currentUser.ID,
		DateTimeUpdated: time.Now(),
	}

	createErr := server.service.CreateRoleApplication(currentUser, &application)
	if createErr != nil {
		util.RespondJsonResult(w, http.StatusInternalServerError, createErr.Error(), nil)
		return
	}
	util.RespondJsonResult(w, http.StatusOK, "role application has been submitted successfully", nil)
	return
}

func (server RoleApplicationServer) GetAllApplicationStatus(w http.ResponseWriter, r *http.Request) {
	statuses, err := server.service.GetAllRoleApplicationStatuses()
	if err != nil {
		util.RespondJsonResult(w, http.StatusInternalServerError, err.Error(), nil)
	}

	output := make([]viewmodel.RoleApplicationStatusViewModel, 0)
	for _, each := range statuses {
		view := viewmodel.RoleApplicationStatusViewModel{}
		view.PopulateFromModel(each)
		output = append(output, view)
	}

	jsonOutput, _ := json.Marshal(output)
	w.Write(jsonOutput)
}

// SearchRoleApplicationHandler handles the request:
//	GET /api/v1.0/account/role/application
func (server RoleApplicationServer) SearchRoleApplicationHandler(w http.ResponseWriter, r *http.Request) {
	currentUser, userErr := server.auth.GetCurrentUser(r)
	if userErr != nil {
		util.RespondJsonResult(w, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	criteria := new(businesslogic.SearchRoleApplicationCriteria)
	if parseErr := util.ParseRequestData(r, criteria); parseErr != nil {
		util.RespondJsonResult(w, http.StatusBadRequest, "bad search criteria, please try again", nil)
		return
	}

	criteria.AccountID = currentUser.ID // only searches applications made by current user

	applications, searchErr := server.service.SearchRoleApplication(currentUser, *criteria)
	if searchErr != nil {
		log.Println(searchErr.Error())
		util.RespondJsonResult(w, http.StatusInternalServerError, "cannot search role application", nil)
		return
	}

	dtos := make([]viewmodel.RoleApplicationAdminView, 0)
	for _, each := range applications {
		dtos = append(dtos, viewmodel.RoleApplicationAdminView{
			ID:                each.ID,
			ApplicantName:     each.Account.FullName(),
			RoleApplied:       each.AppliedRoleID,
			Description:       each.Description,
			Status:            each.StatusID,
			DateTimeSubmitted: each.DateTimeCreated,
			DateTimeResponded: each.DateTimeApproved,
		})
	}

	output, _ := json.Marshal(dtos)
	w.Write(output)
}

// AdminGetRoleApplicationHandler handles the request:
//	GET /api/v1/admin/role/application
// This will return all role applications to the admin user. This handler is for admin uses only and should enforce role check
func (server RoleApplicationServer) AdminGetRoleApplicationHandler(w http.ResponseWriter, r *http.Request) {
	currentUser, userErr := server.auth.GetCurrentUser(r)
	if userErr != nil {
		util.RespondJsonResult(w, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	if !currentUser.HasRole(businesslogic.AccountTypeAdministrator) {
		util.RespondJsonResult(w, http.StatusUnauthorized, "admin priviledge is required", nil)
		return
	}

	criteria := new(businesslogic.SearchRoleApplicationCriteria)
	if parseErr := util.ParseRequestData(r, criteria); parseErr != nil {
		util.RespondJsonResult(w, http.StatusBadRequest, "bad search criteria, please double check", nil)
		return
	}
	// admin user can search requests without additional moderation of search criteria

	applications, searchErr := server.service.SearchRoleApplication(currentUser, *criteria)
	if searchErr != nil {
		log.Println(searchErr.Error())
		util.RespondJsonResult(w, http.StatusInternalServerError, "cannot search role application", nil)
		return
	}

	dtos := make([]viewmodel.RoleApplicationAdminView, 0)
	for _, each := range applications {
		dtos = append(dtos, viewmodel.RoleApplicationAdminView{
			ID:                each.ID,
			ApplicantName:     each.Account.FullName(),
			RoleApplied:       each.AppliedRoleID,
			Description:       each.Description,
			Status:            each.StatusID,
			DateTimeSubmitted: each.DateTimeCreated,
			DateTimeResponded: each.DateTimeApproved,
		})
	}

	output, _ := json.Marshal(dtos)
	w.Write(output)
}

// ProvisionRoleApplicationHandler handles the request:
//	PUT /api/v1.o/account/role/provision
func (server RoleApplicationServer) ProvisionRoleApplicationHandler(w http.ResponseWriter, r *http.Request) {
	currentUser, userErr := server.auth.GetCurrentUser(r)
	if userErr != nil {
		util.RespondJsonResult(w, http.StatusUnauthorized, "unauthorized", nil)
		return
	}

	responseDTO := new(viewmodel.RespondRoleApplication)
	parseErr := util.ParseRequestBodyData(r, responseDTO)

	if parseErr != nil {
		util.RespondJsonResult(w, http.StatusBadRequest, "bad response data, please try again", nil)
		return
	}
	if validator.Validate(responseDTO) != nil {
		util.RespondJsonResult(w, http.StatusBadRequest, "bad response data, please try again", nil)
		return
	}

	applications, searchErr := server.service.SearchRoleApplication(currentUser, businesslogic.SearchRoleApplicationCriteria{
		ID: responseDTO.ApplicationID,
	})
	if searchErr != nil {
		util.RespondJsonResult(w, http.StatusInternalServerError, "cannot search this application", nil)
		return
	}
	if len(applications) == 0 {
		util.RespondJsonResult(w, http.StatusInternalServerError, "cannot find this application", nil)
		return
	}

	updateErr := server.service.UpdateApplication(currentUser, &applications[0], responseDTO.Response)
	if updateErr != nil {
		util.RespondJsonResult(w, http.StatusInternalServerError, updateErr.Error(), nil)
		return
	}

	util.RespondJsonResult(w, http.StatusOK, "done", nil)
}

// RoleServer handles the role information of user
type RoleServer struct {
	Auth        auth.IAuthenticationStrategy
	AccountRepo businesslogic.IAccountRepository
}

// GetAccountRoles get the roles of current user
func (server RoleServer) GetAccountRolesHandler(w http.ResponseWriter, r *http.Request) {
	currentUser, userErr := server.Auth.GetCurrentUser(r)
	if userErr != nil {
		w.WriteHeader(http.StatusUnauthorized)
		util.RespondJsonResult(w, http.StatusUnauthorized, "Invalid token", nil)
		return
	}

	roles := currentUser.GetAccountRoles()
	data := make([]viewmodel.AccountRoleDTO, 0)
	for _, each := range roles {
		data = append(data, viewmodel.AccountRoleToAccountRoleDTO(each))
	}
	util.RespondJsonResult(w, http.StatusOK, "done", data)
}

repository: krasnopv/das

repo_name: krasnopv/das


text:
package session

// SessionLoader is the interface which allows you to access sessions from different storages (like
// filesystem, database, s3 storage, etc.)
type SessionLoader interface {
	Load() (*Session, error)
	Store(*Session) error
}

// Sesion is a basic data of specific session. Typically, session stores default hostname of mtproto server
// (cause all accounts ties to specific server after sign in), session key, server hash and salt.
type Session struct {
	Key      []byte
	Hash     []byte
	Salt     int64
	Hostname string
}

repository: xelaj/mtproto

repo_name: xelaj/mtproto


text:
package dull

import (
	"fmt"
)

// CellGrid represents the grid of cells that are displayed in a window.
//
// The cells may be modified in a callback that runs on the main thread.
// Do not modify the cells outside of a mainthread callback.
//
// Cells are addressed at a column and row.
// An alternative point of view would be x and y.
//
// Column and row indexes are zero-based.
type CellGrid struct {
	width  int
	height int
	cells  []*Cell
}

func NewCellGrid(width, height int, bg, fg Color) *CellGrid {
	g := &CellGrid{
		width:  width,
		height: height,
		cells:  make([]*Cell, width*height),
	}

	for index := 0; index < width*height; index++ {
		g.cells[index] = &Cell{
			grid: g,
			Bg:   bg,
			Fg:   fg,
			Rune: ' ',
		}
	}

	return g
}

// Size returns the size of the grid.
// That is, the number of columns of cells
// and the number of rows of cells.
func (g *CellGrid) Size() (columns int, rows int) {
	return g.width, g.height
}

// Cell gets a Cell at a particular column and row.
func (g *CellGrid) Cell(column, row int) (*Cell, error) {
	index := (row * g.width) + column
	if index >= len(g.cells) {
		return nil, fmt.Errorf("Cell at %d,%d exceeds grid bounds of 0,0 to %d,%d",
			column, row, g.width-1, g.height-1)
	}

	return g.cells[index], nil
}

// SetCell sets a cell's contents.
func (g *CellGrid) SetCell(column, row int, cell *Cell) error {
	index := (row * g.width) + column
	if index >= len(g.cells) {
		return fmt.Errorf("Cell at %d,%d exceeds grid bounds of 0,0 to %d,%d",
			column, row, g.width-1, g.height-1)
	}

	g.cells[index] = cell
	return nil
}

// Clear sets the Rune for all cells to the space character \u0020.
func (g *CellGrid) Clear() {
	g.SetAllCellsRune(' ')
}

// SetAllCellsRune sets the Rune for all cells to the provided value.
func (g *CellGrid) SetAllCellsRune(rune rune) {
	for _, c := range g.cells {
		c.Rune = rune
	}
}

// ForAllCells calls the fn function for all cells in the grid.
//
// Do not forget to call Cell.MakeDirty for a Cell if any of its
// fields are changed.
func (g *CellGrid) ForAllCells(fn func(column, row int, cell *Cell)) {
	for index, cell := range g.cells {
		column := index % g.width
		row := index / g.width
		fn(column, row, cell)
	}
}

func (g *CellGrid) markAllDirty() {
	g.ForAllCells(func(column, row int, cell *Cell) {
	})
}

// PrintAt sets the runes for a sequence of cells from the runes
// in a string.
func (g *CellGrid) PrintAt(column, row int, text string) {
	index := (row * g.width) + column

	for _, r := range text {
		if index < 0 || index >= len(g.cells) {
			return
		}

		g.cells[index].Rune = r

		index++
	}
}

repository: pekim/dull

repo_name: pekim/dull

gha_language: C


text:
@proceedings{ws-2019-financial-narrative,
    title = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    editor = "{Mahmoud El-Haj}  and
      Rayson, Paul  and
      Young, Steven  and
      Bouamor, Houda  and
      Ferradans, Sira",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6400",
}
@inproceedings{tian-peng-2019-finance,
    title = "Finance document Extraction Using Data Augmentation and Attention",
    author = "Tian, Ke  and
      Peng, Zi Jun",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6401",
    pages = "1--4",
}
@inproceedings{blumenthal-graf-2019-utilizing,
    title = "Utilizing Pre-Trained Word Embeddings to Learn Classification Lexicons with Little Supervision",
    author = "Blumenthal, Frederick  and
      Graf, Ferdinand",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6402",
    pages = "5--15",
}
@inproceedings{mariam-mokalled-jaber-2019-automated,
    title = "Automated Stock Price Prediction Using Machine Learning",
    author = "Mariam Mokalled, Wassim El-Hajj  and
      Jaber, Mohamad",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6403",
    pages = "16--24",
}
@inproceedings{gooding-briscoe-2019-active,
    title = "Active Learning for Financial Investment Reports",
    author = "Gooding, Sian  and
      Briscoe, Ted",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6404",
    pages = "25--32",
}
@inproceedings{manandise-2019-towards,
    title = "Towards Unlocking the Narrative of the United States Income Tax Forms",
    author = "Manandise, Esme",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6405",
    pages = "33--41",
}
@inproceedings{moreno-sandoval-etal-2019-tone,
    title = "Tone Analysis in {S}panish Financial Reporting Narratives",
    author = "Moreno-Sandoval, Antonio  and
      Ana Gisbert, Pablo Alfonso Haya  and
      Guerrero, Marta  and
      Montoro, Helena",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6406",
    pages = "42--50",
}
@inproceedings{juge-etal-2019-fintoc,
    title = "The {F}in{TOC}-2019 Shared Task: Financial Document Structure Extraction",
    author = "Juge, Remi  and
      Bentabet, Imane  and
      Ferradans, Sira",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6407",
    pages = "51--57",
}
@inproceedings{akl-etal-2019-fintoc,
    title = "{F}in{TOC}-2019 Shared Task: Finding Title in Text Blocks",
    author = "Akl, Hanna Abi  and
      Gupta, Anubhav  and
      Mariko, Dominique",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6408",
    pages = "58--62",
}
@inproceedings{giguet-lejeune-2019-daniel,
    title = "Daniel@{F}in{TOC}-2019 Shared Task : {TOC} Extraction and Title Detection",
    author = {Giguet, Emmanuel  and
      Lejeune, Ga{\"e}l},
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6409",
    pages = "63--68",
}
@inproceedings{abreu-etal-2019-findse,
    title = "{F}in{DSE}@{F}in{TOC}-2019 Shared Task",
    author = "Abreu, Carla  and
      Cardoso, Henrique  and
      Oliveira, Eug{\'e}nio",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6410",
    pages = "69--73",
}
@inproceedings{tomas-hercig-2019-uwb,
    title = "{UWB}@{F}in{TOC}-2019 Shared Task: Financial Document Title Detection",
    author = "Tomas Hercig, Pavel Kr{\'a}l",
    booktitle = "Proceedings of the Second Financial Narrative Processing Workshop (FNP 2019)",
    month = sep,
    year = "2019",
    address = "Turku, Finland",
    publisher = {Link{\"o}ping University Electronic Press},
    url = "https://www.aclweb.org/anthology/W19-6411",
    pages = "74--78",
}

repository: emorynlp/nlprankings

repo_name: emorynlp/nlprankings

gha_license_id: NOASSERTION

gha_language: TeX

extension: bib


text:
package main

import "fmt"

/* 4ms */
func maxSumAfterPartitioning(A []int, K int) int {
	if len(A) == 0 {
		return 0
	}
	dp := make([]int, len(A))
	for i := 0; i < len(A); i++ {
		maxV := A[i]
		for j := 0; j < K && i-j >= 0; j++ {
			if maxV < A[i-j] {
				maxV = A[i-j]
			}
			sum := maxV * (j + 1)
			if i != j {
				sum += dp[i-j-1]
			}
			if dp[i] < sum {
				dp[i] = sum
			}
		}
	}
	return dp[len(A)-1]
}

func main() {
	var A []int
	var K int

	A = []int{1, 15, 7, 9, 2, 5, 10}
	K = 3
	fmt.Println(K, A)
	fmt.Println(maxSumAfterPartitioning(A, K))
}

repository: BoundaryH/LeetCode-Go

repo_name: BoundaryH/LeetCode-Go


text:
package config

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"os/user"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"

	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"k8s.io/client-go/tools/clientcmd"

	"github.com/kelda-inc/kelda/cmd/util"
	"github.com/kelda-inc/kelda/pkg/config"
	"github.com/kelda-inc/kelda/pkg/errors"
)

// Mocked for unit testing.
var (
	stdout              io.Writer = os.Stdout
	stdin               io.Reader = os.Stdin
	guessDefaults                 = guessDefaultsImpl
	parseUserConfig               = config.ParseUser
	stat                          = os.Stat
	getWorkingDirectory           = os.Getwd
	loadKubeconfig                = clientcmd.NewDefaultClientConfigLoadingRules().Load
	getCurrentUser                = user.Current
)

// New creates a new `config` command.
func New() *cobra.Command {
	var cliOpts config.User
	cmd := &cobra.Command{
		Use:   "config",
		Short: "Setup the Kelda user configuration",
		Run: func(_ *cobra.Command, _ []string) {
			if err := SetupConfig(cliOpts); err != nil {
				err = errors.NewFriendlyError("Failed to setup configuration:\n%s", err)
				util.HandleFatalError(err)
			}
		},
	}
	cmd.Flags().StringVar(&cliOpts.Context, "context", "",
		"Set the context in the config. "+
			"Optional: If not set, `kelda config` will interactively prompt.")
	cmd.Flags().StringVar(&cliOpts.Namespace, "namespace", "",
		"Set the namespace in the config. "+
			"Optional: If not set, `kelda config` will interactively prompt.")
	cmd.Flags().StringVar(&cliOpts.Workspace, "workspace", "",
		"Set the workspace in the config. "+
			"Optional: If not set, `kelda config` will interactively prompt.")

	// Setup the commands for querying the contents of the user config.
	type getterSpec struct {
		use, short string
		fn         func(config.User) string
	}

	getters := []getterSpec{
		{
			use:   "get-namespace",
			short: "Get the currently configured development namespace",
			fn:    func(cfg config.User) string { return cfg.Namespace },
		},
		{
			use:   "get-context",
			short: "Get the currently configured kubectl context",
			fn:    func(cfg config.User) string { return cfg.Context },
		},
	}
	for _, getter := range getters {
		getter := getter
		cmd.AddCommand(&cobra.Command{
			Use:   getter.use,
			Short: getter.short,
			Run: func(_ *cobra.Command, _ []string) {
				cfg, err := parseUserConfig()
				if err != nil {
					err = errors.WithContext(err, "read config")
					util.HandleFatalError(err)
				}

				fmt.Fprintln(stdout, getter.fn(cfg))
			},
		})
	}

	return cmd
}

func SetupConfig(cliOpts config.User) error {
	cfg, err := generateConfig(cliOpts)
	if err != nil {
		return errors.WithContext(err, "generate config")
	}

	if err := config.WriteUser(cfg); err != nil {
		return errors.WithContext(err, "write config")
	}

	path, err := config.GetUserConfigPath()
	if err != nil {
		return errors.WithContext(err, "get user config path")
	}

	fmt.Printf("Wrote config to %s\n", path)
	return nil
}

func namespaceValidationFn(ns string) (string, bool) {
	// Ensure Compliance with DNS-1123.
	// 1) Must be lowercase alphanumeric.
	// 2) The `-` character can also be used in any interior character
	//    of the string.
	// 3) Max of 63 characters.
	dns1123MaxLen := 63

	if ns == "kelda" {
		return "The `kelda` namespace is reserved for the Kelda minion. " +
			"Please pick another namespace.", false
	}

	if len(ns) > dns1123MaxLen {
		return "The namespace name must not be more than 63 characters. " +
			"Please pick another namespace.", false
	}

	re := regexp.MustCompile(`^[-a-z0-9]*$`)
	if !strings.HasPrefix(ns, "-") && !strings.HasSuffix(ns, "-") &&
		re.MatchString(ns) {
		return "", true
	}

	return "This namespace contains invalid characters. " +
		"Please pick another namespace that only  " +
		"uses the following characters:\n" +
		"1) lowercase letters (a-z) \n" +
		"2) numbers (0-9) \n" +
		"3) - \n" +
		"Please ensure that your chosen namespace " +
		"does not start or end with the `-` character.", false

}

type prompt struct {
	helpString, prompt, defaultAnswer, currAnswer string
	field                                         *string
	validationFn                                  func(string) (string, bool)
}

// generateConfig interacts with the user to decide what the user's desired
// configuration is.
// It makes best guesses at reasonable defaults, and allows users to explicitly
// override them if desired.
func generateConfig(cliOpts config.User) (config.User, error) {
	defaults := guessDefaults()
	currConfig, err := parseUserConfig()
	if err != nil {
		currConfig = config.User{}
		log.WithError(err).Debug("Failed to read current config")
	}

	cfg := cliOpts
	var prompts []prompt
	if cliOpts.Context == "" {
		prompts = append(prompts, prompt{
			helpString: "Enter the `kubectl` context for the development cluster.\n" +
				"This cluster should be running the Kelda minion.\n" +
				"It defaults to the current context.",
			prompt:        "Development context",
			defaultAnswer: defaults.Context,
			currAnswer:    currConfig.Context,
			field:         &cfg.Context,
		})
	}

	if cliOpts.Namespace == "" {
		prompts = append(prompts, prompt{
			helpString: "Enter the namespace to use for development.\n" +
				"Your deployment will be isolated from other developers based on this namespace.\n" +
				"Any string is valid as long as it's unique within the Kubernetes cluster.",
			prompt:        "Development namespace",
			defaultAnswer: defaults.Namespace,
			currAnswer:    currConfig.Namespace,
			field:         &cfg.Namespace,
			validationFn:  namespaceValidationFn,
		})
	}

	if cliOpts.Workspace == "" {
		prompts = append(prompts, prompt{
			helpString: "Enter the path to the Kelda workspace configuration " +
				"(which describes how to boot your application).\n" +
				"It defaults to the configuration located in the current directory.",
			prompt:        "Path to Kelda Workspace file",
			defaultAnswer: defaults.Workspace,
			currAnswer:    currConfig.Workspace,
			field:         &cfg.Workspace,
		})
	}

	for _, prompt := range prompts {
		var resp string
		for {
			resp, err = promptUser(prompt.helpString, prompt.prompt,
				prompt.defaultAnswer, prompt.currAnswer)
			if err != nil {
				return config.User{}, errors.WithContext(err, "read response")
			}

			if prompt.validationFn == nil {
				break
			}

			validationErr, ok := prompt.validationFn(resp)
			if ok {
				break
			}

			fmt.Fprintln(stdout, validationErr)
		}

		*prompt.field = resp
	}

	return cfg, nil
}

// guessDefaults tries to guess reasonable defaults for the fields in the user
// config.
func guessDefaultsImpl() (cfg config.User) {
	if namespace, err := guessNamespace(); err == nil {
		cfg.Namespace = namespace
	} else {
		log.WithError(err).Info("Failed to guess namespace")
	}

	if context, err := getCurrentContext(); err == nil {
		cfg.Context = context
	} else {
		log.WithError(err).Info("Failed to guess context")
	}

	if workspace, err := guessWorkspace(); err == nil {
		cfg.Workspace = workspace
	} else {
		log.WithError(err).Info("Failed to guess workspace")
	}

	return cfg
}

func sanitizeNamespace(original string) (sanitized string) {
	sanitized = strings.ToLower(original)
	noInvalidChar := regexp.MustCompile(`[^-a-z0-9]`)
	sanitized = noInvalidChar.ReplaceAllString(sanitized, "")
	noLeadingOrTrailingHyphen := regexp.MustCompile(`^-*(.*?)-*$`)
	sanitized = noLeadingOrTrailingHyphen.ReplaceAllString(sanitized, "$1")
	if len(sanitized) > 63 {
		sanitized = sanitized[:63]
	}

	// As a sanity check, make sure the sanitized namespace passes the namespace
	// validation. This should never fail unless there's a bug in the sanitization
	// logic above.
	if _, ok := namespaceValidationFn(sanitized); !ok {
		return ""
	}
	return sanitized
}

func guessNamespace() (string, error) {
	currConfig, err := parseUserConfig()
	if err == nil && currConfig.Namespace != "" {
		return currConfig.Namespace, nil
	}
	user, err := getCurrentUser()
	if err != nil {
		return "", errors.WithContext(err, "get current user")
	}
	return sanitizeNamespace(user.Username), nil
}

func getCurrentContext() (string, error) {
	cfg, err := loadKubeconfig()
	if err != nil {
		return "", errors.WithContext(err, "load kubeconfig")
	}
	return cfg.CurrentContext, nil
}

// guessWorkspace returns the path to the workspace.yaml in the current
// directory if it exists.
func guessWorkspace() (string, error) {
	currDir, err := getWorkingDirectory()
	if err != nil {
		return "", errors.WithContext(err, "get current directory")
	}

	path := filepath.Join(currDir, "workspace.yaml")
	if _, err := stat(path); err != nil {
		if os.IsNotExist(err) {
			return "", nil
		}
		return "", errors.WithContext(err, "stat")
	}
	return path, nil
}

func promptUser(helpString, prompt, defaultAnswer, currAnswer string) (string, error) {
	// Display a new line at the end to separate different fields to make it
	// look clearer.
	defer fmt.Fprintln(stdout)

	options := []string{}
	if defaultAnswer != "" {
		options = append(options, defaultAnswer)
	}
	if currAnswer != "" && currAnswer != defaultAnswer {
		options = append(options, currAnswer)
	}
	options = append(options, "(Enter manually)")

	fmt.Fprintln(stdout, helpString+"\n"+prompt+":")

	stdinReader := bufio.NewReader(stdin)

	if nOptions := len(options); nOptions > 1 {
		// defaultAnswer or currAnswer exists.
		fmt.Fprintln(stdout)
		for i, option := range options {
			if i == 0 {
				option = fmt.Sprintf("%s (recommended)", option)
			}
			fmt.Fprintf(stdout, "\t%d. %s\n", i+1, option)
		}
		fmt.Fprintln(stdout)

		for {
			fmt.Fprintf(stdout, "Please choose one [1-%d]: ", nOptions)
			choiceStr, err := stdinReader.ReadString('\n')
			if err != nil {
				return "", err
			}

			var choice int
			choiceStr = strings.TrimRight(choiceStr, "\n")

			// Default to the first choice if user doesn't enter anything.
			if choiceStr == "" {
				choice = 1
			} else {
				choice, err = strconv.Atoi(choiceStr)
				if err != nil || choice < 1 || choice > nOptions {
					// Try again if the input is invalid.
					continue
				}
			}

			if choice == nOptions {
				// Enter manually.
				break
			}

			return options[choice-1], nil
		}
	}

	fmt.Fprint(stdout, "Please enter manually: ")
	resp, err := stdinReader.ReadString('\n')
	if err != nil {
		return "", err
	}

	return strings.TrimRight(resp, "\n"), nil
}


text:
inherit esw_examples features_check

REQUIRED_MACHINE_FEATURES = "llfifo"

ESW_COMPONENT_SRC = "/XilinxProcessorIPLib/drivers/llfifo/examples/"

repository: Xilinx/meta-xilinx

repo_name: Xilinx/meta-xilinx


text:
package schema

import (
	"encoding/json"
	"errors"
	"time"
)

type APIConfig struct {
	Authenticated bool
	AllowedIPs    []string
	Username      string
	Password      string
	CORS          *string
	Enabled       bool
	HTTPHeaders   map[string]interface{}
	SSL           bool
	SSLCert       string
	SSLKey        string
}

type TorConfig struct {
	Password   string
	TorControl string
}

type IpnsExtraConfig struct {
	DHTQuorumSize int
	APIRouter     string
}

type WalletsConfig struct {
	PHR *CoinConfig `json:"PHR"`
	BTC *CoinConfig `json:"BTC"`
	BCH *CoinConfig `json:"BCH"`
	LTC *CoinConfig `json:"LTC"`
	ZEC *CoinConfig `json:"ZEC"`
	ETH *CoinConfig `json:"ETH"`
}

type CoinConfig struct {
	Type             string                 `json:"Type"`
	APIPool          []string               `json:"API"`
	APITestnetPool   []string               `json:"APITestnet"`
	MaxFee           uint64                 `json:"MaxFee"`
	FeeAPI           string                 `json:"FeeAPI"`
	HighFeeDefault   uint64                 `json:"HighFeeDefault"`
	MediumFeeDefault uint64                 `json:"MediumFeeDefault"`
	LowFeeDefault    uint64                 `json:"LowFeeDefault"`
	TrustedPeer      string                 `json:"TrustedPeer"`
	WalletOptions    map[string]interface{} `json:"WalletOptions"`
}

type DataSharing struct {
	AcceptStoreRequests bool
	PushTo              []string
}

var MalformedConfigError = errors.New("config file is malformed")

func DefaultWalletsConfig() *WalletsConfig {
	var feeAPI = "https://btc.fees.openbazaar.org"
	return &WalletsConfig{
		PHR: &CoinConfig{
			Type:             WalletTypeAPI,
			APIPool:          CoinPoolPHR,
			APITestnetPool:   CoinPoolTPHR,
			FeeAPI:           "https://phr.fees.phore.io",
			LowFeeDefault:    1,
			MediumFeeDefault: 20,
			HighFeeDefault:   50,
			MaxFee:           200,
			WalletOptions:    nil,
		},
		BTC: &CoinConfig{
			Type:             WalletTypeAPI,
			APIPool:          CoinPoolBTC,
			APITestnetPool:   CoinPoolTBTC,
			FeeAPI:           feeAPI,
			LowFeeDefault:    1,
			MediumFeeDefault: 10,
			HighFeeDefault:   50,
			MaxFee:           200,
			WalletOptions:    nil,
		},
	}
}

func GetAPIConfig(cfgBytes []byte) (*APIConfig, error) {
	var cfgIface interface{}
	err := json.Unmarshal(cfgBytes, &cfgIface)
	if err != nil {
		return nil, MalformedConfigError
	}

	cfg, ok := cfgIface.(map[string]interface{})
	if !ok {
		return nil, MalformedConfigError
	}

	apiIface, ok := cfg["JSON-API"]
	if !ok {
		return nil, MalformedConfigError
	}

	api, ok := apiIface.(map[string]interface{})
	if !ok {
		return nil, MalformedConfigError
	}

	var headers map[string]interface{}
	h, ok := api["HTTPHeaders"]
	if h == nil || !ok {
		headers = nil
	} else {
		headers, ok = h.(map[string]interface{})
		if !ok {
			return nil, MalformedConfigError
		}
	}

	enabled, ok := api["Enabled"]
	if !ok {
		return nil, MalformedConfigError
	}
	enabledBool, ok := enabled.(bool)
	if !ok {
		return nil, MalformedConfigError
	}
	authenticated := api["Authenticated"]
	if !ok {
		return nil, MalformedConfigError
	}
	authenticatedBool, ok := authenticated.(bool)
	if !ok {
		return nil, MalformedConfigError
	}
	allowedIPs, ok := api["AllowedIPs"]
	if !ok {
		return nil, MalformedConfigError
	}
	allowedIPsIface, ok := allowedIPs.([]interface{})
	if !ok {
		return nil, MalformedConfigError
	}
	var allowedIPstrings []string
	for _, ip := range allowedIPsIface {
		ipStr, ok := ip.(string)
		if !ok {
			return nil, MalformedConfigError
		}
		allowedIPstrings = append(allowedIPstrings, ipStr)
	}

	username, ok := api["Username"]
	if !ok {
		return nil, MalformedConfigError
	}
	usernameStr, ok := username.(string)
	if !ok {
		return nil, MalformedConfigError
	}

	password, ok := api["Password"]
	if !ok {
		return nil, MalformedConfigError
	}
	passwordStr, ok := password.(string)
	if !ok {
		return nil, MalformedConfigError
	}

	c, ok := api["CORS"]
	var cors *string
	if c == nil || !ok {
		cors = nil
	} else {
		crs, ok := c.(string)
		if !ok {
			return nil, MalformedConfigError
		}
		cors = &crs
	}
	sslEnabled, ok := api["SSL"]
	if !ok {
		return nil, MalformedConfigError
	}
	sslEnabledBool, ok := sslEnabled.(bool)
	if !ok {
		return nil, MalformedConfigError
	}

	certFile, ok := api["SSLCert"]
	if !ok {
		return nil, MalformedConfigError
	}
	certFileStr, ok := certFile.(string)
	if !ok {
		return nil, MalformedConfigError
	}
	keyFile, ok := api["SSLKey"]
	if !ok {
		return nil, MalformedConfigError
	}
	keyFileStr, ok := keyFile.(string)
	if !ok {
		return nil, MalformedConfigError
	}

	apiConfig := &APIConfig{
		Authenticated: authenticatedBool,
		AllowedIPs:    allowedIPstrings,
		Username:      usernameStr,
		Password:      passwordStr,
		CORS:          cors,
		Enabled:       enabledBool,
		HTTPHeaders:   headers,
		SSL:           sslEnabledBool,
		SSLCert:       certFileStr,
		SSLKey:        keyFileStr,
	}

	return apiConfig, nil
}

func GetWalletsConfig(cfgBytes []byte) (*WalletsConfig, error) {
	var cfgIface map[string]interface{}
	err := json.Unmarshal(cfgBytes, &cfgIface)
	if err != nil {
		return nil, MalformedConfigError
	}

	walletIface, ok := cfgIface["Wallets"]
	if !ok {
		return nil, MalformedConfigError
	}

	b, err := json.Marshal(walletIface)
	if err != nil {
		return nil, err
	}
	wCfg := new(WalletsConfig)
	err = json.Unmarshal(b, wCfg)
	if err != nil {
		return nil, err
	}
	return wCfg, nil
}

func GetTorConfig(cfgBytes []byte) (*TorConfig, error) {
	var cfgIface interface{}
	err := json.Unmarshal(cfgBytes, &cfgIface)
	if err != nil {
		return nil, MalformedConfigError
	}

	cfg, ok := cfgIface.(map[string]interface{})
	if !ok {
		return nil, MalformedConfigError
	}

	tcIface, ok := cfg["Tor-config"]
	if !ok {
		return nil, MalformedConfigError
	}
	tc, ok := tcIface.(map[string]interface{})
	if !ok {
		return nil, MalformedConfigError
	}

	pw, ok := tc["Password"]
	if !ok {
		return nil, MalformedConfigError
	}
	pwStr, ok := pw.(string)
	if !ok {
		return nil, MalformedConfigError
	}
	controlUrl, ok := tc["TorControl"]
	if !ok {
		return nil, MalformedConfigError
	}
	controlUrlStr, ok := controlUrl.(string)
	if !ok {
		return nil, MalformedConfigError
	}

	return &TorConfig{TorControl: controlUrlStr, Password: pwStr}, nil
}

func GetIPNSExtraConfig(cfgBytes []byte) (*IpnsExtraConfig, error) {
	var cfgIface interface{}
	err := json.Unmarshal(cfgBytes, &cfgIface)
	if err != nil {
		return nil, MalformedConfigError
	}

	cfg, ok := cfgIface.(map[string]interface{})
	if !ok {
		return nil, MalformedConfigError
	}

	ieIface, ok := cfg["IpnsExtra"]
	if !ok {
		return nil, MalformedConfigError
	}
	ieCfg, ok := ieIface.(map[string]interface{})
	if !ok {
		return nil, MalformedConfigError
	}

	quorumSize, ok := ieCfg["DHTQuorumSize"]
	if !ok {
		return nil, MalformedConfigError
	}
	qsInt, ok := quorumSize.(float64)
	if !ok {
		return nil, MalformedConfigError
	}
	apiRouter, ok := ieCfg["APIRouter"]
	if !ok {
		return nil, MalformedConfigError
	}
	apiRouterStr, ok := apiRouter.(string)
	if !ok {
		return nil, MalformedConfigError
	}

	return &IpnsExtraConfig{int(qsInt), apiRouterStr}, nil
}

func GetDropboxApiToken(cfgBytes []byte) (string, error) {
	var cfgIface interface{}
	err := json.Unmarshal(cfgBytes, &cfgIface)
	if err != nil {
		return "", MalformedConfigError
	}

	cfg, ok := cfgIface.(map[string]interface{})
	if !ok {
		return "", MalformedConfigError
	}

	token, ok := cfg["Dropbox-api-token"]
	if !ok {
		return "", MalformedConfigError
	}
	tokenStr, ok := token.(string)
	if !ok {
		return "", MalformedConfigError
	}

	return tokenStr, nil
}

func GetRepublishInterval(cfgBytes []byte) (time.Duration, error) {
	var cfgIface interface{}
	err := json.Unmarshal(cfgBytes, &cfgIface)
	if err != nil {
		return time.Duration(0), MalformedConfigError
	}

	cfg, ok := cfgIface.(map[string]interface{})
	if !ok {
		return time.Duration(0), MalformedConfigError
	}

	interval, ok := cfg["RepublishInterval"]
	if !ok {
		return time.Duration(0), MalformedConfigError
	}
	intervalStr, ok := interval.(string)
	if !ok {
		return time.Duration(0), MalformedConfigError
	}
	if intervalStr == "" {
		return time.Duration(0), nil
	}
	d, err := time.ParseDuration(intervalStr)
	if err != nil {
		return d, err
	}
	return d, nil
}

func GetDataSharing(cfgBytes []byte) (*DataSharing, error) {
	var cfgIface interface{}
	err := json.Unmarshal(cfgBytes, &cfgIface)
	if err != nil {
		return nil, MalformedConfigError
	}

	dataSharing := new(DataSharing)

	cfg, ok := cfgIface.(map[string]interface{})
	if !ok {
		return dataSharing, MalformedConfigError
	}

	dscfg, ok := cfg["DataSharing"]
	if !ok {
		return dataSharing, MalformedConfigError
	}
	ds, ok := dscfg.(map[string]interface{})
	if !ok {
		return dataSharing, MalformedConfigError
	}

	acceptcfg, ok := ds["AcceptStoreRequests"]
	if !ok {
		return dataSharing, MalformedConfigError
	}
	accept, ok := acceptcfg.(bool)
	if !ok {
		return dataSharing, MalformedConfigError
	}
	dataSharing.AcceptStoreRequests = accept

	pushcfg, ok := ds["PushTo"]
	if !ok {
		return dataSharing, MalformedConfigError
	}
	pushList, ok := pushcfg.([]interface{})
	if !ok {
		return dataSharing, MalformedConfigError
	}

	for _, nd := range pushList {
		ndStr, ok := nd.(string)
		if !ok {
			return dataSharing, MalformedConfigError
		}
		dataSharing.PushTo = append(dataSharing.PushTo, ndStr)
	}
	return dataSharing, nil
}

func GetTestnetBootstrapAddrs(cfgBytes []byte) ([]string, error) {
	var cfgIface interface{}
	err := json.Unmarshal(cfgBytes, &cfgIface)
	if err != nil {
		return nil, MalformedConfigError
	}

	var addrs []string

	cfg, ok := cfgIface.(map[string]interface{})
	if !ok {
		return addrs, MalformedConfigError
	}

	bootstrap, ok := cfg["Bootstrap-testnet"]
	if !ok {
		return addrs, MalformedConfigError
	}
	addrList, ok := bootstrap.([]interface{})
	if !ok {
		return addrs, MalformedConfigError
	}

	for _, addr := range addrList {
		addrStr, ok := addr.(string)
		if !ok {
			return addrs, MalformedConfigError
		}
		addrs = append(addrs, addrStr)
	}

	return addrs, nil
}

repository: phoreproject/pm-go

repo_name: phoreproject/pm-go


text:
/* Some of the code is taken from - https://developers.google.com/calendar/api/quickstart/go */

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/calendar/v3"
	"google.golang.org/api/option"
)

func getClient(credentialsFile string) (*http.Client, error) {
	b, err := ioutil.ReadFile(credentialsFile)
	if err != nil {
		return nil, fmt.Errorf("unable to read client secret file: %v", err)
	}

	config, err := google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
	if err != nil {
		return nil, fmt.Errorf("unable to parse client secret file to config: %v", err)
	}

	tokFile := "token.json"
	tok, err := tokenFromFile(tokFile)
	if err != nil {
		tok = getTokenFromWeb(config)
		saveToken(tokFile, tok)
	}
	return config.Client(context.Background(), tok), nil
}

func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
	authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
	fmt.Printf("Go to the following link in your browser then type the "+
		"authorization code: \n%v\n", authURL)

	var authCode string
	if _, err := fmt.Scan(&authCode); err != nil {
		log.Fatalf("Unable to read authorization code: %v", err)
	}

	tok, err := config.Exchange(context.TODO(), authCode)
	if err != nil {
		log.Fatalf("Unable to retrieve token from web: %v", err)
	}
	return tok
}

func tokenFromFile(file string) (*oauth2.Token, error) {
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	tok := &oauth2.Token{}
	err = json.NewDecoder(f).Decode(tok)
	return tok, err
}

func saveToken(path string, token *oauth2.Token) {
	fmt.Printf("Saving credential file to: %s\n", path)
	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		log.Fatalf("Unable to cache oauth token: %v", err)
	}
	defer f.Close()
	json.NewEncoder(f).Encode(token)
}

func getEvents(client *http.Client, calendarIds []string, dueInMinutes time.Duration, timeLoc string) ([]*calendar.Event, error) {

	var events []*calendar.Event
	now := time.Now()

	ctx := context.Background()

	srv, err := calendar.NewService(ctx, option.WithHTTPClient(client))
	if err != nil {
		return nil, fmt.Errorf("unable to retrieve Calendar client: %v", err)
	}

	for _, calendarId := range calendarIds {
		eventsItem, err := srv.Events.List(calendarId).
			ShowDeleted(false).
			ShowHiddenInvitations(false).
			SingleEvents(true).
			TimeMin(now.Format(time.RFC3339)).
			TimeMax(now.Add(dueInMinutes).Format(time.RFC3339)).
			MaxResults(10).
			OrderBy("startTime").
			TimeZone(timeLoc).
			Do()
		if err != nil {
			return nil, fmt.Errorf("unable to get list of events: %v", err)
		}
		{
			var startTime time.Time
			for _, event := range eventsItem.Items {
				startTime, _ = time.Parse(time.RFC3339, event.Start.DateTime)
				if startTime.Sub(now) > 0 {
					events = append(events, event)
				}
			}
		}
	}

	return events, nil
}

func do(events []*calendar.Event, webhookUrl string) {
	if len(events) > 0 {
		for _, event := range events {
			data, err := event.MarshalJSON()
			if err != nil {
				log.Fatalf("failed to create json: %v", err)
			}
			_, err = http.Post(webhookUrl, "application/json", bytes.NewBuffer(data))
			if err != nil {
				log.Fatalf("ERROR: %v", err)
			}
		}
	}
}

func main() {
	var (
		webhookUrl,
		credentialsFile,
		waitFor,
		calendarIds,
		timeLoc,
		eventInMax string
		duration time.Duration
		err      error
		client   *http.Client
	)
	flag.StringVar(&webhookUrl, "webhook", "", "Enter the webhook url you got from Rocket.Chat.")
	flag.StringVar(&credentialsFile, "credentials", "credentials.json", "Enter path to the credentials file.")
	flag.StringVar(&waitFor, "waitfor", "5m", "Time to wait before attempting a POST to Rocket.Chat webhook.")
	flag.StringVar(&eventInMax, "eventin", "30m", "The upper limit of upcoming event start time. Lower bound is the moment of API access.")
	flag.StringVar(&calendarIds, "calendars", "primary", "List of calendar IDs, separated by commas.")
	flag.StringVar(&timeLoc, "timezone", "UTC", "Specify a timezone.")
	flag.Parse()

	if webhookUrl == "" {
		log.Fatal("[ERROR] You must pass a webhook url. Read more: https://docs.rocket.chat/guides/rocket.chat-administrator-guides/administration/integrations/google-calendar")
	}

	if duration, err = time.ParseDuration(waitFor); err != nil {
		log.Fatalf("Incorrect duration format: %v", err)
	}
	ticker := time.NewTicker(duration)

	if duration, err = time.ParseDuration(eventInMax); err != nil {
		log.Fatalf("Incorrect duration format: %v", err)
	}

	if client, err = getClient(credentialsFile); err != nil {
		log.Fatalf("Failed to capture client: %v", err)
	}

	if _, err = time.LoadLocation(timeLoc); err != nil {
		panic(err)
	}

	for {
		<-ticker.C

		events, err := getEvents(client, strings.Split(calendarIds, ","), duration, timeLoc)
		if err != nil {
			log.Fatalf("ERROR: %v", err)
		}

		do(events, webhookUrl)
	}

}

repository: debdutdeb/rocketchat-google-calendar

repo_name: debdutdeb/rocketchat-google-calendar


text:
# Determine python version string -
# this is missing in Cmake versions <2.8.6 (i.e. packages for Ubuntu <12.04)
#
# Sets the variables, PYTHON_VERSION_MAJOR and PYTHON_VERSION_MINOR
# which can then be used to set the python install dir.
#
if(PYTHON_EXECUTABLE)
    execute_process(COMMAND "${PYTHON_EXECUTABLE}" --version ERROR_VARIABLE _VERSION OUTPUT_QUIET ERROR_STRIP_TRAILING_WHITESPACE)
    string(REPLACE "Python " "" PYTHON_VERSION_STRING "${_VERSION}")
    string(REGEX REPLACE "^([0-9]+)\\.[0-9]+\\.[0-9]+.*" "\\1" PYTHON_VERSION_MAJOR "${PYTHON_VERSION_STRING}")
    string(REGEX REPLACE "^[0-9]+\\.([0-9])+\\.[0-9]+.*" "\\1" PYTHON_VERSION_MINOR "${PYTHON_VERSION_STRING}")
    string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" PYTHON_VERSION_PATCH "${PYTHON_VERSION_STRING}")
endif()

repository: timstaley/coelacanth

repo_name: timstaley/coelacanth

extension: cmake


text:
package xxl

import (
	"context"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"sync"
	"syscall"
	"time"
)

// Executor 执行器
type Executor interface {
	// Init 初始化
	Init(...Option)
	// LogHandler 日志查询
	LogHandler(handler LogHandler)
	// Use 使用中间件
	Use(middlewares ...Middleware)
	// RegTask 注册任务
	RegTask(pattern string, task TaskFunc)
	// RunTask 运行任务
	RunTask(writer http.ResponseWriter, request *http.Request)
	// KillTask 杀死任务
	KillTask(writer http.ResponseWriter, request *http.Request)
	// TaskLog 任务日志
	TaskLog(writer http.ResponseWriter, request *http.Request)
	// Beat 心跳检测
	Beat(writer http.ResponseWriter, request *http.Request)
	// IdleBeat 忙碌检测
	IdleBeat(writer http.ResponseWriter, request *http.Request)
	// Run 运行服务
	Run() error
	// Stop 停止服务
	Stop()
}

// NewExecutor 创建执行器
func NewExecutor(opts ...Option) Executor {
	return newExecutor(opts...)
}

func newExecutor(opts ...Option) *executor {
	options := newOptions(opts...)
	e := &executor{
		opts: options,
	}
	return e
}

type executor struct {
	opts    Options
	address string
	regList *taskList //注册任务列表
	runList *taskList //正在执行任务列表
	mu      sync.RWMutex
	log     Logger

	logHandler  LogHandler   //日志查询handler
	middlewares []Middleware //中间件
}

func (e *executor) Init(opts ...Option) {
	for _, o := range opts {
		o(&e.opts)
	}
	if e.opts.l == nil {
		e.opts.l = &logger{
			level:     e.opts.LogLevel,
			CallDepth: e.opts.depth,
		}
	}
	e.log = e.opts.l
	e.regList = &taskList{
		data: make(map[string]*Task),
	}
	e.runList = &taskList{
		data: make(map[string]*Task),
	}
	e.address = e.opts.ExecutorIp + ":" + e.opts.ExecutorPort
	go e.registry()
}

// LogHandler 日志handler
func (e *executor) LogHandler(handler LogHandler) {
	e.logHandler = handler
}

func (e *executor) Use(middlewares ...Middleware) {
	e.middlewares = middlewares
}

func (e *executor) Run() (err error) {
	// 创建路由器
	mux := http.NewServeMux()
	// 设置路由规则
	mux.HandleFunc("/run", e.runTask)
	mux.HandleFunc("/kill", e.killTask)
	mux.HandleFunc("/log", e.taskLog)
	mux.HandleFunc("/beat", e.beat)
	mux.HandleFunc("/idleBeat", e.idleBeat)
	// 创建服务器
	server := &http.Server{
		Addr:         ":" + e.opts.ExecutorPort,
		WriteTimeout: time.Second * 3,
		Handler:      mux,
	}
	// 监听端口并提供服务
	e.log.Info("Starting server at " + e.address)
	go server.ListenAndServe()
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGKILL, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	e.registryRemove()
	return nil
}

func (e *executor) Stop() {
	e.registryRemove()
}

// RegTask 注册任务
func (e *executor) RegTask(pattern string, task TaskFunc) {
	var t = &Task{}
	t.fn = e.chain(task)
	e.regList.Set(pattern, t)
	return
}

// 运行一个任务
func (e *executor) runTask(writer http.ResponseWriter, request *http.Request) {
	e.mu.Lock()
	defer e.mu.Unlock()

	req, _ := io.ReadAll(request.Body)
	param := &RunReq{}
	err := json.Unmarshal(req, &param)
	if err != nil {
		_, _ = writer.Write(returnCall(param, FailureCode, "params err"))
		e.log.Error("参数解析错误:" + string(req))
		return
	}
	e.log.Info("任务参数:%v", param)
	if !e.regList.Exists(param.ExecutorHandler) {
		_, _ = writer.Write(returnCall(param, FailureCode, "Task not registered"))
		e.log.Error("任务[" + Int64ToStr(param.JobID) + "]没有注册:" + param.ExecutorHandler)
		return
	}

	//阻塞策略处理
	if e.runList.Exists(Int64ToStr(param.JobID)) {
		if param.ExecutorBlockStrategy == coverEarly { //覆盖之前调度
			oldTask := e.runList.Get(Int64ToStr(param.JobID))
			if oldTask != nil {
				oldTask.Cancel()
				e.runList.Del(Int64ToStr(oldTask.Id))
			}
		} else { //单机串行,丢弃后续调度 都进行阻塞
			_, _ = writer.Write(returnCall(param, FailureCode, "There are tasks running"))
			e.log.Error("任务[" + Int64ToStr(param.JobID) + "]已经在运行了:" + param.ExecutorHandler)
			return
		}
	}

	cxt := context.Background()
	task := e.regList.Get(param.ExecutorHandler)
	if param.ExecutorTimeout > 0 {
		task.Ext, task.Cancel = context.WithTimeout(cxt, time.Duration(param.ExecutorTimeout)*time.Second)
	} else {
		task.Ext, task.Cancel = context.WithCancel(cxt)
	}
	task.Id = param.JobID
	task.Name = param.ExecutorHandler
	task.Param = param
	task.log = e.log

	e.runList.Set(Int64ToStr(task.Id), task)
	go task.Run(func(er *ExecuteResult) {
		e.callback(task, er.Code, er.Msg)
	})
	e.log.Info("任务[" + Int64ToStr(param.JobID) + "]开始执行:" + param.ExecutorHandler)
	_, _ = writer.Write(returnGeneral())
}

// 删除一个任务
func (e *executor) killTask(writer http.ResponseWriter, request *http.Request) {
	e.mu.Lock()
	defer e.mu.Unlock()
	req, _ := io.ReadAll(request.Body)
	param := &killReq{}
	_ = json.Unmarshal(req, &param)
	if !e.runList.Exists(Int64ToStr(param.JobID)) {
		_, _ = writer.Write(returnKill(param, FailureCode))
		e.log.Error("任务[" + Int64ToStr(param.JobID) + "]没有运行")
		return
	}
	task := e.runList.Get(Int64ToStr(param.JobID))
	task.Cancel()
	e.runList.Del(Int64ToStr(param.JobID))
	_, _ = writer.Write(returnGeneral())
}

// 任务日志
func (e *executor) taskLog(writer http.ResponseWriter, request *http.Request) {
	var res *LogRes
	data, err := io.ReadAll(request.Body)
	req := &LogReq{}
	if err != nil {
		e.log.Error("日志请求失败:" + err.Error())
		reqErrLogHandler(writer, req, err)
		return
	}
	err = json.Unmarshal(data, &req)
	if err != nil {
		e.log.Error("日志请求解析失败:" + err.Error())
		reqErrLogHandler(writer, req, err)
		return
	}
	e.log.Info("日志请求参数:%+v", req)
	if e.logHandler != nil {
		res = e.logHandler(req)
	} else {
		res = defaultLogHandler(req)
	}
	str, _ := json.Marshal(res)
	_, _ = writer.Write(str)
}

// 心跳检测
func (e *executor) beat(writer http.ResponseWriter, request *http.Request) {
	e.log.Info("心跳检测")
	_, _ = writer.Write(returnGeneral())
}

// 忙碌检测
func (e *executor) idleBeat(writer http.ResponseWriter, request *http.Request) {
	e.mu.Lock()
	defer e.mu.Unlock()
	defer request.Body.Close()
	req, _ := io.ReadAll(request.Body)
	param := &idleBeatReq{}
	err := json.Unmarshal(req, &param)
	if err != nil {
		_, _ = writer.Write(returnIdleBeat(FailureCode))
		e.log.Error("参数解析错误:" + string(req))
		return
	}
	if e.runList.Exists(Int64ToStr(param.JobID)) {
		_, _ = writer.Write(returnIdleBeat(FailureCode))
		e.log.Error("idleBeat任务[" + Int64ToStr(param.JobID) + "]正在运行")
		return
	}
	e.log.Info("忙碌检测任务参数:%v", param)
	_, _ = writer.Write(returnGeneral())
}

// 注册执行器到调度中心
func (e *executor) registry() {

	t := time.NewTimer(time.Second * 0) //初始立即执行
	defer t.Stop()
	req := &Registry{
		RegistryGroup: "EXECUTOR",
		RegistryKey:   e.opts.RegistryKey,
		RegistryValue: "http://" + e.address,
	}
	param, err := json.Marshal(req)
	if err != nil {
		log.Fatal("执行器注册信息解析失败:" + err.Error())
	}
	for {
		<-t.C
		t.Reset(time.Second * time.Duration(20)) //20秒心跳防止过期
		func() {
			result, err := e.post("/api/registry", string(param))
			if err != nil {
				e.log.Error("执行器注册失败1:" + err.Error())
				return
			}
			defer result.Body.Close()
			body, err := io.ReadAll(result.Body)
			if err != nil {
				e.log.Error("执行器注册失败2:" + err.Error())
				return
			}
			res := &res{}
			_ = json.Unmarshal(body, &res)
			if res.Code != SuccessCode {
				e.log.Error("执行器注册失败3:" + string(body))
				return
			}
			e.log.Info("执行器注册成功:" + string(body))
		}()

	}
}

// 执行器注册摘除
func (e *executor) registryRemove() {
	t := time.NewTimer(time.Second * 0) //初始立即执行
	defer t.Stop()
	req := &Registry{
		RegistryGroup: "EXECUTOR",
		RegistryKey:   e.opts.RegistryKey,
		RegistryValue: "http://" + e.address,
	}
	param, err := json.Marshal(req)
	if err != nil {
		e.log.Error("执行器摘除失败:" + err.Error())
		return
	}
	res, err := e.post("/api/registryRemove", string(param))
	if err != nil {
		e.log.Error("执行器摘除失败:" + err.Error())
		return
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	e.log.Info("执行器摘除成功:" + string(body))
}

// 回调任务列表
func (e *executor) callback(task *Task, code int64, msg string) {
	e.runList.Del(Int64ToStr(task.Id))
	res, err := e.post("/api/callback", string(returnCall(task.Param, code, msg)))
	if err != nil {
		e.log.Error("callback err : ", err.Error())
		return
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		e.log.Error("callback ReadAll err : ", err.Error())
		return
	}
	e.log.Info("任务回调成功:" + string(body))
}

// post
func (e *executor) post(action, body string) (resp *http.Response, err error) {
	request, err := http.NewRequest("POST", e.opts.ServerAddr+action, strings.NewReader(body))
	if err != nil {
		return nil, err
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("XXL-JOB-ACCESS-TOKEN", e.opts.AccessToken)
	request.Header.Set("APP_NAME", e.opts.AppName)
	client := http.Client{
		Timeout: e.opts.Timeout,
	}
	return client.Do(request)
}

// RunTask 运行任务
func (e *executor) RunTask(writer http.ResponseWriter, request *http.Request) {
	e.runTask(writer, request)
}

// KillTask 删除任务
func (e *executor) KillTask(writer http.ResponseWriter, request *http.Request) {
	e.killTask(writer, request)
}

// TaskLog 任务日志
func (e *executor) TaskLog(writer http.ResponseWriter, request *http.Request) {
	e.taskLog(writer, request)
}

// Beat 心跳检测
func (e *executor) Beat(writer http.ResponseWriter, request *http.Request) {
	e.beat(writer, request)
}

// IdleBeat 忙碌检测
func (e *executor) IdleBeat(writer http.ResponseWriter, request *http.Request) {
	e.idleBeat(writer, request)
}

repository: sunmi-OS/gocore

repo_name: sunmi-OS/gocore


text:
DESCRIPTION = "Apache Portable Runtime (APR) companion library"
SECTION = "libs"
DEPENDS = "apr expat gdbm"
LICENSE = "Apache License, Version 2.0"

PR = "r2"

# apache mirrors?
SRC_URI = "${APACHE_MIRROR}/apr/${P}.tar.gz"

EXTRA_OECONF = "--with-apr=${STAGING_BINDIR_CROSS} --with-dbm=gdbm \
		--with-gdbm=${STAGING_DIR}/${HOST_SYS} \
		--without-sqlite2 \
		--without-sqlite3 \
		--with-expat=${STAGING_DIR}/${HOST_SYS}"

inherit autotools lib_package binconfig

do_configure() {
  oe_runconf
}

do_stage() {
	autotools_stage_all
}

repository: jdegges/gumstix-pip-oe

repo_name: jdegges/gumstix-pip-oe


text:
package mcolor

import (
	"image"
	"image/color"

	"github.com/dontomato/mandelbrot/pkg/mcalc"
)

func getGreyPalette() []color.Color {
	pal := make([]color.Color, 255*3)
	for i := 0; i < 255*3; i++ {
		pal[i] = color.RGBA{uint8(i / 3), uint8((i + 1) / 3), uint8((i + 2) / 3), 255}
	}
	return pal
}

// CreateSmoothGreyRGBA returns smooth RGBA with Grey palette
func CreateSmoothGreyRGBA(data []mcalc.MandelIterationResult, settings *mcalc.MandelSettings) *image.RGBA {
	return createPaletteRGBA(data, settings, getGreyPalette())
}

repository: DonTomato/mandelgo

repo_name: DonTomato/mandelgo


text:
package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

type Queue []int

func (q *Queue) Push(item int) {
	*q = append(*q, item)
}

func (q *Queue) Pop() int {
	if !q.IsEmpty() {
		item := (*q)[0]
		*q = (*q)[1:len(*q)]
		return item
	}
	return 0
}

func (q *Queue) Len() int {
	return len(*q)
}

func (q *Queue) IsEmpty() bool {
	return q.Len() == 0
}

var (
	cond      *sync.Cond = sync.NewCond(new(sync.Mutex))
	workQueue Queue
)

func produce() {
	i := 0
	for {
		time.Sleep(time.Duration(rand.Intn(300)) * time.Millisecond)
		cond.L.Lock()
		workQueue.Push(i)
		i++
		cond.Signal()
		cond.L.Unlock()
	}
}

func consume(name string) {
	for {
		cond.L.Lock()
		for workQueue.IsEmpty() {
			cond.Wait()
			fmt.Println(name, "is awoken")
		}
		item := workQueue.Pop()
		cond.L.Unlock()
		fmt.Println(name, item)
		time.Sleep(time.Duration(rand.Intn(200)+100) * time.Millisecond)
	}
}

func main() {
	go consume("First")
	go consume("Second")
	go consume("Third")
	produce()
}

repository: boyanio/go-lectures

repo_name: boyanio/go-lectures


text:
@inproceedings{saade_spectral_2015,
 abstract = {We consider the problem of partially recovering hidden binary variables from the observation of (few) censored edge weights, a problem with applications in community detection, correlation clustering and synchronization. We describe two spectral algorithms for this task based on the non-backtracking and the Bethe Hessian operators. These algorithms are shown to be asymptotically optimal for the partial recovery problem, in that they detect the hidden assignment as soon as it is information theoretically possible to do so.},
 author = {Saade, A. and Lelarge, M. and Krzakala, F. and Zdeborová, L.},
 booktitle = {2015 IEEE International Symposium on Information Theory (ISIT)},
 doi = {10.1109/ISIT.2015.7282642},
 file = {IEEE Xplore Abstract Record:/Users/florentkrzakala/Zotero/storage/BCCEVHCX/7282642.html:text/html;Submitted Version:/Users/florentkrzakala/Zotero/storage/BCYK36RR/Saade et al. - 2015 - Spectral detection in the censored block model.pdf:application/pdf},
 keywords = {Belief propagation, Bethe Hessian operators, censored block model, community detection, correlation clustering, correlation methods, Eigenvalues and eigenfunctions, few censored edge weights, Glass, Hessian matrices, hidden binary variable partial recovery, Image edge detection, Physics, spectral algorithms, spectral analysis, spectral detection, Stochastic processes, Symmetric matrices, synchronisation, synchronization},
 month = {June},
 pages = {1184--1188},
 title = {Spectral detection in the censored block model},
 year = {2015}
}

repository: krzakala/academic-kickstart

repo_name: krzakala/academic-kickstart


text:
package XOAuth

// OAuth2服务的通用鉴权接口
type OAuth interface {
	Authorize(code string) OAuthResult                                    // 根据微信返回的accessTokenCode开始鉴权并获取用户信息
	getAccessToken(code string) map[string]interface{}                    // 从平台回调拿到accessTokenCode后调用此方法可拿到accessToken
	getUserInfo(accessToken string, openId string) map[string]interface{} // 拿到accessToken和openId后获取用户信息
}

// OAuth鉴权结果
type OAuthResult struct {
	Result   bool
	UserInfo *OAuthAccountInfo
	Error    error
}

// OAuth授权获取的第三方账号信息
type OAuthAccountInfo struct {
	AccessToken string
	OpenId      string
	UnionId     string
	NickName    string
	Gender      uint
	AvatarUrl   string
}

repository: bb-orz/goinfras

repo_name: bb-orz/goinfras


text:
// Copyright 2015 Zalando SE
//
// 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.

/*
This utility can be used to verify, print, update or delete eskip
formatted routes from and to different data sources.

For command line help, enter:

	eskip -help

# Examples

Check if an eskip file has valid syntax:

	eskip check routes.eskip

Print routes stored in etcd:

	eskip print -etcd-urls https://etcd.example.org

Print routes as JSON:

	eskip print -json

Insert/update routes in etcd from an eskip file:

	eskip upsert routes.eskip

Sync routes from an eskip file to etcd:

	eskip reset routes.eskip

Delete routes from etcd:

	eskip delete -ids route1,route2,route3

Delete all routes from etcd:

	eskip print | eskip delete

Copy all routes in etcd under a different prefix:

	eskip print | eskip upsert -etcd-prefix /skipper-backup

(Where -etcd-urls is not set for write operations like upsert, reset and
delete, the default etcd cluster urls are used:
http://127.0.0.1:2379,http://127.0.0.1:4001)
*/
package main

import (
	"fmt"
	"os"
)

const (
	// short hint:
	helpHint = "To print eskip usage, enter: eskip -help"

	// flag usage strings:
	etcdUrlsUsage       = "urls of nodes in an etcd cluster"
	etcdPrefixUsage     = "path prefix for routes in etcd"
	innkeeperUrlUsage   = "url for the innkeeper service"
	oauthTokenUsage     = "oauth token used to authenticate to innkeeper"
	etcdOAuthTokenUsage = "oauth token used to authenticate to etcd"
	inlineRoutesUsage   = "inline: routes in eskip format"
	inlineIdsUsage      = "inline ids: comma separated route ids"
	insecureUsage       = "skip TLS certificate verification"
	prependFiltersUsage = "prepend filters to each patched route"
	prependFileUsage    = "prepend filters from a file to each patched route"
	appendFiltersUsage  = "append filters to each patched route"
	appendFileUsage     = "append filters from a file to each patched route"
	prettyUsage         = "prints routes in a more readable format"
	sortPredicateUsage  = "sort routes predicates"
	indentStrUsage      = "indent string used in pretty printing. Must match regexp \\s"
	jsonUsage           = "prints routes as JSON"

	// command line help (1):
	help1 = `Usage: eskip <command> [media flags] [--] [file]
Commands: check|print|upsert|reset|delete|patch
Verify, print, update or delete Skipper routes.
See more: https://github.com/zalando/skipper

Media types:

innkeeper     endpoint of an innkeeper server. See more about innkeeper:
              https://github.com/zalando/innkeeper
etcd          endpoint(s) of an etcd cluster. See more about etcd:
              https://github.com/coreos/etcd
stdin         standard input when not tty, expecting routes but ignored if a file is provided
file          a file containing routes
inline        routes as command line parameter
inline ids    a list of route ids (only for delete)
prepend       a chain of filters to be prepended to the filter chain in
              each route
prepend file  a file containing a chain of filters to be prepended to the
              filter chain in each route
append        a chain of filters to be appended to the filter chain in
              each route
append file   a file containing a chain of filters to be appended to the
              filter chain in each route

Media flags:

`

	/* position for generated flags */

	// command line help (2):
	help2 = `
Commands:

check    verifies the syntax of routes. Accepts one input medium
         of the following types: etcd (default), stdin, file, inline.
         Example:
         eskip check -etcd-urls http://etcd.example.org

print    same as check, but also prints the routes.

upsert   insert/update routes from input to output. Expects one input
         medium of the following types: stdin, file, inline.
         Automatically selects etcd as output. Example:
         eskip upsert routes.eskip

reset    same as upsert, but also deletes the routes from the output
         that are not found in the input.

delete   deletes routes from the output that are specified in the input.
         Expects one input medium of the following types: stdin, file,
         inline, inline ids. Automatically selects etcd as output.
         Example:
         eskip delete -ids route1,route2,route3

patch    takes a list of routes as input from any media except of inline
         ids, and prepends or appends a common filter chain to each
		 route. Example:
		 eskip patch -append 'filter1() -> filter2()'

version  print eskip version
`
)

// simplified check for help request:
func isHelp() bool {
	for _, s := range os.Args[1:] {
		if s == "-help" || s == "--help" {
			return true
		}
	}

	return false
}

// print command line help:
func usage() {
	fmt.Print(help1)
	flags.SetOutput(os.Stdout)
	flags.PrintDefaults()
	flags.SetOutput(nowrite)
	fmt.Print(help2)
}

repository: zalando/skipper

repo_name: zalando/skipper


text:
@article{mavrakis2014septins,
 abstract = {Animal cell cytokinesis requires a contractile ring of crosslinked actin filaments and myosin motors. How contractile rings form and are stabilized in dividing cells remains unclear. We address this problem by focusing on septins, highly conserved proteins in eukaryotes whose precise contribution to cytokinesis remains elusive. We use the cleavage of the Drosophila melanogaster embryo as a model system, where contractile actin rings drive constriction of invaginating membranes to produce an epithelium in a manner akin to cell division. In vivo functional studies show that septins are required for generating curved and tightly packed actin filament networks. In vitro reconstitution assays show that septins alone bundle actin filaments into rings, accounting for the defects in actin ring formation in septin mutants. The bundling and bending activities are conserved for human septins, and highlight unique functions of septins in the organization of contractile actomyosin rings.},
 author = {Mavrakis, Manos and Azou-Gros, Yannick and Tsai, Feng-Ching and Alvarado, José and Bertin, Aurélie and Iv, Francois and Kress, Alla and Brasselet, Sophie and Koenderink, Gijsje H and Lecuit, Thomas},
 doi = {10.1038/ncb2921},
 featured = {true},
 issn = {1465-7392},
 journal = {Nature Cell Biology},
 number = {4},
 pages = {322-334},
 title = {Septins promote F-actin ring formation by crosslinking actin filaments into curved bundles},
 type = {Journal Article},
 url = {https://www.nature.com/articles/ncb2921},
 volume = {16},
 year = {2014}
}

repository: FengChingTsai/academic-kickstart

repo_name: FengChingTsai/academic-kickstart


text:
@article{chapman_simple_2001,
  author   = {Chapman, Wendy W. and Bridewell, Will and Hanbury, Paul and Cooper, Gregory F. and Buchanan, Bruce G.},
  doi      = {10.1006/jbin.2001.1029},
  file     = {Chapman et al. - 2001 - A Simple Algorithm for Identifying Negated Finding.pdf:/home/basile/Zotero/storage/JP6GC4UM/Chapman et al. - 2001 - A Simple Algorithm for Identifying Negated Finding.pdf:application/pdf},
  issn     = {15320464},
  journal  = {Journal of Biomedical Informatics},
  language = {en},
  month    = oct,
  number   = {5},
  pages    = {301--310},
  title    = {A {Simple} {Algorithm} for {Identifying} {Negated} {Findings} and {Diseases} in {Discharge} {Summaries}},
  url      = {https://linkinghub.elsevier.com/retrieve/pii/S1532046401910299},
  urldate  = {2020-12-31},
  volume   = {34},
  year     = {2001}
}

@article{cossin:hal-02987843,
  TITLE = {{Romedi: An Open Data Source About French Drugs on the Semantic Web}},
  AUTHOR = {Cossin, S{\'e}bastien and Lebrun, Luc and Lobre, Gr{\'e}gory and Loustau, Romain and Jouhet, Vianney and Griffier, Romain and Mougin, Fleur and Diallo, Gayo and Thiessard, Frantz},
  URL = {https://hal.archives-ouvertes.fr/hal-02987843},
  JOURNAL = {{Studies in Health Technology and Informatics}},
  PUBLISHER = {{IOS Press}},
  VOLUME = {264},
  PAGES = {79-82},
  YEAR = {2019},
  MONTH = Aug,
  DOI = {10.3233/SHTI190187},
  KEYWORDS = {Controlled ; Pharmaceutical Preparations ; Semantics ; Vocabulary},
  HAL_ID = {hal-02987843},
  HAL_VERSION = {v1},
}

@inproceedings{grabar2018CAS,
  address     = {Bruxelles, France},
  author      = {Grabar, Natalia and Claveau, Vincent and Dalloux, Clément},
  booktitle   = {{LOUHI 2018 - The Ninth International Workshop on Health Text Mining and Information Analysis}},
  hal_id      = {hal-01937096},
  hal_version = {v1},
  month       = Oct,
  pages       = {1-7},
  pdf         = {https://hal.archives-ouvertes.fr/hal-01937096/file/corpus_Louhi_2018.pdf},
  series      = {Ninth International Workshop on Health Text Mining and Information Analysis (LOUHI) Proceedings of the Workshop},
  title       = {{CAS: French Corpus with Clinical Cases}},
  url         = {https://hal.archives-ouvertes.fr/hal-01937096},
  year        = {2018}
}

@inproceedings{dalloux2017ESSAI,
  address     = {Toulouse, France},
  author      = {Dalloux, Clément and Claveau, Vincent and Grabar, Natalia},
  booktitle   = {{SIIM 2017 - Symposium sur l'Ingénierie de l'Information Médicale}},
  hal_id      = {hal-01659637},
  hal_version = {v1},
  month       = Nov,
  pages       = {1-8},
  pdf         = {https://hal.archives-ouvertes.fr/hal-01659637/file/SIIM2017.pdf},
  title       = {Détection de la négation : corpus français et apprentissage supervisé},
  url         = {https://hal.archives-ouvertes.fr/hal-01659637},
  year        = {2017}
}

@phdthesis{wajsburt:tel-03624928,
  TITLE = {{Extraction and normalization of simple and structured entities in medical documents}},
  AUTHOR = {Wajsb{\"u}rt, Perceval},
  URL = {https://hal.archives-ouvertes.fr/tel-03624928},
  SCHOOL = {{Sorbonne Universit{\'e}}},
  YEAR = {2021},
  MONTH = Dec,
  KEYWORDS = {nlp ; structure ; extraction ; normalization ; clinical ; multilingual},
  TYPE = {Theses},
  PDF = {https://hal.archives-ouvertes.fr/tel-03624928/file/updated_phd_thesis_PW.pdf},
  HAL_ID = {tel-03624928},
  HAL_VERSION = {v1},
}

@inproceedings{zweigenbaum2016,
  abstract  = {Dans certains textes bruts, les marques de fin de ligne peuvent marquer ou pas la fronti{\`e}re d{'}une unit{\'e} textuelle (typiquement un paragraphe). Ce probl{\`e}me risque d{'}influencer les traitements subs{\'e}quents, mais est rarement trait{\'e} dans la litt{\'e}rature. Nous proposons une m{\'e}thode enti{\`e}rement non-supervis{\'e}e pour d{\'e}terminer si une fin de ligne doit {\^e}tre vue comme un simple espace ou comme une v{\'e}ritable fronti{\`e}re d{'}unit{\'e} textuelle, et la testons sur un corpus de comptes rendus m{\'e}dicaux. Cette m{\'e}thode obtient une F-mesure de 0,926 sur un {\'e}chantillon de 24 textes contenant des lignes repli{\'e}es. Appliqu{\'e}e sur un {\'e}chantillon plus grand de textes contenant ou pas des lignes repli{\'e}es, notre m{\'e}thode la plus prudente obtient une F-mesure de 0,898, valeur {\'e}lev{\'e}e pour une m{\'e}thode enti{\`e}rement non-supervis{\'e}e.},
  address   = {Paris, France},
  author    = {Zweigenbaum, Pierre  and
               Grouin, Cyril  and
               Lavergne, Thomas},
  booktitle = {Actes de la conf{\'e}rence conjointe JEP-TALN-RECITAL 2016. volume 2 : TALN (Posters)},
  language  = {French},
  month     = {7},
  pages     = {364--371},
  publisher = {AFCP - ATALA},
  title     = {Une cat{\'e}gorisation de fins de lignes non-supervis{\'e}e (End-of-line classification with no supervision)},
  url       = {https://aclanthology.org/2016.jeptalnrecital-poster.7},
  year      = {2016}
}

@article{kempf:hal-03519085,
  TITLE = {{Impact of two waves of Sars-Cov2 outbreak on the number, clinical presentation, care trajectories and survival of patients newly referred for a colorectal cancer: A French multicentric cohort study from a large group of University hospitals}},
  AUTHOR = {Kempf, Emmanuelle and Priou, Sonia and Lam{\'e}, Guillaume and Daniel, Christel and Bellamine, Ali and Sommacale, Daniele and Belkacemi, yazid and Bey, Romain and Galula, Gilles and Taright, Namik and Tannier, Xavier and Rance, Bastien and Flicoteaux, R{\'e}mi and Hemery, Fran{\c c}ois and Audureau, Etienne and Chatellier, Gilles and Tournigand, Christophe},
  URL = {https://hal.archives-ouvertes.fr/hal-03519085},
  JOURNAL = {{International Journal of Cancer}},
  PUBLISHER = {{Wiley}},
  VOLUME = {150},
  NUMBER = {10},
  PAGES = {1609-1618},
  YEAR = {2022},
  DOI = {10.1002/ijc.33928},
  KEYWORDS = {Delivery of Health Care ; Health Services Research ; Colorectal Neoplasms ; Quality of Health Care ; COVID-19},
  PDF = {https://hal.archives-ouvertes.fr/hal-03519085/file/IJC2022%20accepted_vHAL%20%281%29.pdf},
  HAL_ID = {hal-03519085},
  HAL_VERSION = {v1},
}

@misc{terminologie-adicap,
  TITLE = {{Thésaurus de la codification ADICAP - Index raisonné des lésions}},
  URL = {http://esante.gouv.fr/terminologie-adicap},
  VERSION = {2019-05},
  YEAR = {2019},
  MONTH = {05},
  ID = {1.2.250.1.213.2.11},
  AUTHOR = {Agence du numérique en santé},
  DETAILS = {https://smt.esante.gouv.fr/wp-json/ans/terminologies/document?terminologyId=terminologie-adicap&fileName=cgts_sem_adicap_fiche-detaillee.pdf},
}

repository: aphp/edsnlp

repo_name: aphp/edsnlp

gha_language: Python