text:
package prometheus

import (
	"context"
	"net/http"

	"github.com/prometheus/client_golang/prometheus/promhttp"

	"github.com/herzult/porte/internal/graph"
	"github.com/herzult/porte/internal/graph/proxy"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
)

// ProxyPluginConfig defines the configuration of the proxy plugin
type ProxyPluginConfig struct {
	Namespace string
	Subsystem string
}

// NewProxyPlugin returns a new proxy instance that records metrics using
// prometheus.
func NewProxyPlugin(cfg ProxyPluginConfig) (*proxy.Plugin, error) {

	graphGraphqlErrorsTotal := promauto.NewCounter(prometheus.CounterOpts{
		Namespace: cfg.Namespace,
		Subsystem: cfg.Subsystem,
		Name:      "graphql_errors_total",
	})

	graphHTTPRequestsTotal := prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: cfg.Namespace,
			Subsystem: cfg.Subsystem,
			Name:      "graph_http_requests_total",
		},
		[]string{"code", "method"},
	)

	graphHTTPRequestDuration := prometheus.NewSummaryVec(
		prometheus.SummaryOpts{
			Namespace: cfg.Namespace,
			Subsystem: cfg.Subsystem,
			Name:      "graph_http_request_duration_seconds",
		},
		[]string{"code", "method"},
	)

	graphHTTPRequestsInFlight := prometheus.NewGauge(
		prometheus.GaugeOpts{
			Namespace: cfg.Namespace,
			Subsystem: cfg.Subsystem,
			Name:      "graph_http_requests_in_flight",
		},
	)

	prometheus.MustRegister(
		graphHTTPRequestsTotal,
		graphHTTPRequestDuration,
		graphHTTPRequestsInFlight,
	)

	return &proxy.Plugin{
		InitContext: func(ctx context.Context) context.Context {
			return ctx
		},
		ReadProxyRequest: func(next proxy.ReadProxyRequest) proxy.ReadProxyRequest {
			return func(r *http.Request) (*graph.Request, error) {
				return next(r)
			}
		},
		SendGraphRequest: func(next http.RoundTripper) http.RoundTripper {
			next = proxy.SendGraphRequest(promhttp.InstrumentRoundTripperCounter(
				graphHTTPRequestsTotal,
				next,
			))

			next = proxy.SendGraphRequest(promhttp.InstrumentRoundTripperDuration(
				graphHTTPRequestDuration,
				next,
			))

			next = proxy.SendGraphRequest(promhttp.InstrumentRoundTripperInFlight(
				graphHTTPRequestsInFlight,
				next,
			))

			return next
		},
		WriteProxyResponse: func(next proxy.WriteProxyResponse) proxy.WriteProxyResponse {
			return func(ctx context.Context, w http.ResponseWriter, graphRes *graph.Response, graphErr error) {
				if graphRes != nil {
					graphGraphqlErrorsTotal.Add(float64(len(graphRes.Errors)))
				}

				next(ctx, w, graphRes, graphErr)
			}
		},
	}, nil
}

repository: Herzult/porte

repo_name: Herzult/porte


text:
@book{hastie2009elements,
  title={The elements of statistical learning},
  author={Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome and Hastie, T and Friedman, J and Tibshirani, R},
  volume={2},
  number={1},
  year={2009},
  publisher={Springer}
}
@book{crawley2012r,
  title={The R book},
  author={Crawley, Michael J},
  year={2012},
  publisher={John Wiley \& Sons}
}
@article{wickham2010layered,
  title={A layered grammar of graphics},
  author={Wickham, Hadley},
  journal={Journal of Computational and Graphical Statistics},
  volume={19},
  number={1},
  pages={3--28},
  year={2010},
  publisher={Taylor \& Francis}
}
@book{wickham2014advr,
  title={Advanced R},
  author={Wickham, Hadley},
  year={2014},
  publisher={Chapman & Hall/CRC press}
}
@article{wickham2014tidy,
  title={Tidy data},
  author={Wickham, Hadley},
  journal={Under review},
  year={2014}
}
@article{stasinopoulos2007generalized,
  title={Generalized additive models for location scale and shape (GAMLSS) in R},
  author={Stasinopoulos, D Mikis and Rigby, Robert A},
  journal={Journal of Statistical Software},
  volume={23},
  number={7},
  pages={1--46},
  year={2007}
}
@book{xie2013dynamic,
  title={Dynamic Documents with R and knitr},
  author={Xie, Yihui},
  year={2013},
  publisher={CRC Press}
}
@article{wickham2013devtools,
  title={devtools: Tools to make developing R code easier},
  author={Wickham, Hadley and Chang, Winston},
  journal={R package version},
  volume={1},
  number={1},
  year={2013}
}
@manual{shiny,
  title={Easy web applications in R.},
  author={{RStudio, Inc}},
  year={2013},
  note={URL: \url{http://www.rstudio.com/shiny/}}
}
@book{burns2011r,
  title={The R inferno},
  author={Burns, Patrick},
  year={2011},
  publisher={Lulu. com}
}

license: MIT

license_type: permissive

branch_name: refs/heads/master

extension: bib


text:
@article{frances1997covering,
  title={On covering problems of codes},
  author={Frances, Moti and Litman, Ami},
  journal={Theory of Computing Systems},
  volume={30},
  number={2},
  pages={113--119},
  year={1997},
  publisher={Springer}
}

@article{li2002closest,
  title={On the closest string and substring problems},
  author={Li, Ming and Ma, Bin and Wang, Lusheng},
  journal={Journal of the ACM (JACM)},
  volume={49},
  number={2},
  pages={157--171},
  year={2002},
  publisher={ACM New York, NY, USA}
}

repository: lucasresck/data-structures-algorithms

repo_name: lucasresck/data-structures-algorithms

branch_name: refs/heads/main


text:
SUMMARY = "Classic UNIX line editor"
HOMEPAGE = "http://www.gnu.org/software/ed/"

PR = "r0"

inherit debian-package

LICENSE = "GPLv3+"
LIC_FILES_CHKSUM = " \
    file://COPYING;md5=f27defe1e96c2e1ecd4e0c9be8967949 \
    file://ed.h;endline=20;md5=2b62ce887e37f828a04aa32f1ec23787 \
    file://main.c;endline=17;md5=002b306d8e804a6fceff144b26554253 \
"

DEBIAN_PATCH_TYPE = "dpatch"

inherit texinfo update-alternatives

do_configure() {
	${S}/configure
}

do_install() {
	oe_runmake DESTDIR="${D}" install

	# Follow debian/rules
	install -d ${D}${base_bindir}
	mv ${D}${bindir}/ed ${D}${base_bindir}/
	mv ${D}${bindir}/red ${D}${base_bindir}/

	# Remove if directory empty
	if [ ! $(ls -A ${D}${bindir}) ]; then
		rm -r ${D}${bindir}
	fi
}

# Add update-alternatives definitions to avoid confict with busybox
ALTERNATIVE_${PN} = "ed"
ALTERNATIVE_PRIORITY[ed] = "100"
ALTERNATIVE_LINK_NAME[ed] = "${base_bindir}/ed"

# Follow debian/postinst
ALTERNATIVE_${PN} += "editor"
ALTERNATIVE_PRIORITY[editor] = "-100"
ALTERNATIVE_LINK_NAME[editor] = "${bindir}/editor"
ALTERNATIVE_TARGET[editor] = "${base_bindir}/ed.${DPN}"

repository: nghiaht-tsdv/meta-debian

repo_name: nghiaht-tsdv/meta-debian

branch_name: refs/heads/jethro

gha_language: BitBake

extension: bb


text:
@article{wilson_tryp-n_2020,
	title = {Tryp-{N}: {A} {Thermostable} {Protease} for the {Production} of {N}-terminal {Argininyl} and {Lysinyl} {Peptides}},
	volume = {19},
	issn = {1535-3907},
	shorttitle = {Tryp-{N}},
	doi = {10.1021/acs.jproteome.9b00713},
	abstract = {Bottom-up proteomics is a mainstay in protein identification and analysis. These studies typically employ proteolytic treatment of biological samples to generate suitably sized peptides for tandem mass spectrometric (MS) analysis. In MS, fragmentation of peptides is largely driven by charge localization. Consequently, peptides with basic centers exclusively on their N-termini produce mainly b-ions. Thus, it was long ago realized that proteases that yield such peptides would be valuable proteomic tools for achieving simplified peptide fragmentation patterns and peptide assignment. Work by several groups has identified such proteases, however, structural analysis of these suggested that enzymatic optimization was possible. We therefore endeavored to find enzymes that could provide enhanced activity and versatility while maintaining specificity. Using these previously described proteases as informatic search templates, we discovered and then characterized a thermophilic metalloprotease with N-terminal specificity for arginine and lysine. This enzyme, dubbed Tryp-N, affords many advantages including improved thermostability, solvent and detergent tolerance, and rapid digestion time.},
	language = {eng},
	number = {4},
	journal = {Journal of Proteome Research},
	author = {Wilson, John P. and Ipsaro, Jonathan J. and Del Giudice, Samantha N. and Turna, Nikita Saha and Gauss, Carla M. and Dusenbury, Katharine H. and Marquart, Krisann and Rivera, Keith D. and Pappin, Darryl J.},
	month = apr,
	year = {2020},
	pmid = {32141294},
	keywords = {arginine, Lys-N, LysargiNase, lysine, metalloprotease, proteomics, thermostable, Tryp-N, trypsin, ulilysin},
	pages = {1459--1469}
}

repository: jonipsaro/academic-kickstart

repo_name: jonipsaro/academic-kickstart

gha_license_id: MIT


text:
package convert

import "time"

// toSecondsOrDefault converts a duration string in seconds and defaults to a
// given value if the duration is nil.
// The supported units are us, ms, s, m and h.
func toSecondsOrDefault(duration *time.Duration, defaultValue int32) int32 { //nolint: unparam
	if duration == nil {
		return defaultValue
	}

	return int32(duration.Seconds())
}

repository: VonRosenchild/compose-on-kubernetes

repo_name: VonRosenchild/compose-on-kubernetes

extension: go


text:
package cloudpool

// MachinePredicate is a predicate function that tests a Machine for a certain condition.
type MachinePredicate func(*Machine) bool

// Not is a machine predicate that always negates a given predicate.
func Not(predicate MachinePredicate) MachinePredicate {
	return func(machine *Machine) bool {
		return !predicate(machine)
	}
}

// IsMachineAllocated returns true if a machine is in one of machine
// states: `REQUESTED`, `PENDING`, or `RUNNING`.
func IsMachineAllocated(machine *Machine) bool {
	return machine.MachineState == MachineStateRequested ||
		machine.MachineState == MachineStatePending ||
		machine.MachineState == MachineStateRunning
}

// IsMachineActive is a predicate that returns true for any machine that is both allocated
// (in one of machine states: `REQUESTED`, `PENDING`, or `RUNNING`) and has an active
// membership status.
func IsMachineActive(machine *Machine) bool {
	return IsMachineAllocated(machine) && machine.MembershipStatus.Active
}

// FilterMachines filters a given list of machines, returning a list with
// only the machines that satisfy all predicates.
func FilterMachines(machines []Machine, predicates ...MachinePredicate) (filtered []Machine) {
	for _, machine := range machines {
		satisfiesAllPredicates := true
		for _, predicate := range predicates {
			if !predicate(&machine) {
				satisfiesAllPredicates = false
				break
			}
		}

		if satisfiesAllPredicates {
			filtered = append(filtered, machine)
		}
	}

	return filtered
}

repository: elastisys/kubeaware-cloudpool-proxy

repo_name: elastisys/kubeaware-cloudpool-proxy


text:
package githubql

import "time"

// Note: These custom types are meant to be used in queries, but it's not required.
// They're here for convenience and documentation. If you use the base Go types,
// things will still work.
//
// TODO: In Go 1.9, consider using type aliases instead (for extra simplicity
//       and convenience).

type (
	// Boolean represents true or false values.
	Boolean bool

	// DateTime is an ISO-8601 encoded UTC date string.
	DateTime struct{ time.Time }

	// Float represents signed double-precision fractional values as specified by IEEE 754.
	Float float64

	// GitObjectID is a Git object ID.
	GitObjectID string // TODO: Confirm.

	// GitTimestamp is an ISO-8601 encoded date string.
	// Unlike the DateTime type, GitTimestamp is not converted in UTC.
	GitTimestamp struct{ time.Time }

	// HTML is a string containing HTML code.
	HTML string

	// ID represents a unique identifier that is Base64 obfuscated. It
	// is often used to refetch an object or as key for a cache. The ID
	// type appears in a JSON response as a String; however, it is not
	// intended to be human-readable. When expected as an input type,
	// any string (such as "VXNlci0xMA==") or integer (such as 4) input
	// value will be accepted as an ID.
	ID string

	// Int represents non-fractional signed whole numeric values.
	// Int can represent values between -(2^31) and 2^31 - 1.
	Int int32

	// String represents textual data as UTF-8 character sequences.
	// This type is most often used by GraphQL to represent free-form
	// human-readable text.
	String string

	// URI is an RFC 3986, RFC 3987, and RFC 6570 (level 4) compliant URI string.
	URI string

	// X509Certificate is a valid x509 certificate string.
	X509Certificate string
)

// NewBoolean is a helper to make a new *Boolean.
func NewBoolean(v Boolean) *Boolean { return &v }

// NewDateTime is a helper to make a new *DateTime.
func NewDateTime(v DateTime) *DateTime { return &v }

// NewFloat is a helper to make a new *Float.
func NewFloat(v Float) *Float { return &v }

// NewGitObjectID is a helper to make a new *GitObjectID.
func NewGitObjectID(v GitObjectID) *GitObjectID { return &v }

// NewGitTimestamp is a helper to make a new *GitTimestamp.
func NewGitTimestamp(v GitTimestamp) *GitTimestamp { return &v }

// NewHTML is a helper to make a new *HTML.
func NewHTML(v HTML) *HTML { return &v }

// NewID is a helper to make a new *ID.
func NewID(v ID) *ID { return &v }

// NewInt is a helper to make a new *Int.
func NewInt(v Int) *Int { return &v }

// NewString is a helper to make a new *String.
func NewString(v String) *String { return &v }

// NewURI is a helper to make a new *URI.
func NewURI(v URI) *URI { return &v }

// NewX509Certificate is a helper to make a new *X509Certificate.
func NewX509Certificate(v X509Certificate) *X509Certificate { return &v }

license: Unlicense

repository: shurcooL/play

repo_name: shurcooL/play

gha_language: Go


text:
package status

import "github.com/bmf-san/bitbankgo/types"

// GetStatusResponse is a response for getting status.
type GetStatusResponse struct {
	Success int `json:"success"`
	Data    struct {
		Code     int `json:"code"`
		Statuses []struct {
			Pair      types.TypePair   `json:"Pair"`
			Status    types.TypeStatus `json:"status"`
			MinAmount string           `json:"min_amount"`
		}
	}
}

repository: suotas/bitbankgo

repo_name: suotas/bitbankgo


text:
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

file(GLOB_RECURSE onnxruntime_graph_src CONFIGURE_DEPENDS
  "${ONNXRUNTIME_INCLUDE_DIR}/core/graph/*.h"
  "${ONNXRUNTIME_ROOT}/core/graph/*.h"
  "${ONNXRUNTIME_ROOT}/core/graph/*.cc"
  )

if (onnxruntime_DISABLE_CONTRIB_OPS)
  list(REMOVE_ITEM onnxruntime_graph_src
    "${ONNXRUNTIME_ROOT}/core/graph/contrib_ops/*.h"
    "${ONNXRUNTIME_ROOT}/core/graph/contrib_ops/*.cc"
    )
endif()

if(NOT onnxruntime_USE_FEATURIZERS)
  file(GLOB_RECURSE featurizers_to_remove_graph_src
    "${ONNXRUNTIME_ROOT}/core/graph/featurizers_ops/*.h"
    "${ONNXRUNTIME_ROOT}/core/graph/featurizers_ops/*.cc"
    )
  foreach(I in ${featurizers_to_remove_graph_src})
    list(REMOVE_ITEM onnxruntime_graph_src ${I})
  endforeach()
endif()

if(NOT onnxruntime_USE_DML)
  list(REMOVE_ITEM onnxruntime_graph_src
    "${ONNXRUNTIME_ROOT}/core/graph/dml_ops/*.h"
    "${ONNXRUNTIME_ROOT}/core/graph/dml_ops/*.cc"
    )
endif()

file(GLOB_RECURSE onnxruntime_ir_defs_src CONFIGURE_DEPENDS
  "${ONNXRUNTIME_ROOT}/core/defs/*.cc"
)

if (onnxruntime_ENABLE_TRAINING)
  file(GLOB_RECURSE orttraining_graph_src CONFIGURE_DEPENDS
      "${ORTTRAINING_SOURCE_DIR}/core/graph/*.h"
      "${ORTTRAINING_SOURCE_DIR}/core/graph/*.cc"
      )
  if (NOT onnxruntime_USE_HOROVOD)
    list(REMOVE_ITEM orttraining_graph_src
        "${ORTTRAINING_SOURCE_DIR}/core/graph/horovod_adapters.h"
        "${ORTTRAINING_SOURCE_DIR}/core/graph/horovod_adapters.cc"
        )
  endif()
endif()

set(onnxruntime_graph_lib_src ${onnxruntime_graph_src} ${onnxruntime_ir_defs_src})
if (onnxruntime_ENABLE_TRAINING)
    list(APPEND onnxruntime_graph_lib_src ${orttraining_graph_src})
endif()

add_library(onnxruntime_graph ${onnxruntime_graph_lib_src})
add_dependencies(onnxruntime_graph onnx_proto)
onnxruntime_add_include_to_target(onnxruntime_graph onnxruntime_common onnx onnx_proto protobuf::libprotobuf)

if (onnxruntime_ENABLE_TRAINING)
  #TODO: the graph library should focus on ONNX IR, it shouldn't depend on math libraries like MKLML/OpenBlas
  target_include_directories(onnxruntime_graph PRIVATE ${MKLML_INCLUDE_DIR})
endif()

target_include_directories(onnxruntime_graph PRIVATE ${ONNXRUNTIME_ROOT})

if (onnxruntime_ENABLE_TRAINING)
    target_include_directories(onnxruntime_graph PRIVATE ${ORTTRAINING_ROOT})

    if (onnxruntime_USE_HOROVOD)
        target_include_directories(onnxruntime_graph PRIVATE ${HOROVOD_INCLUDE_DIRS})
    endif()
endif()

set_target_properties(onnxruntime_graph PROPERTIES FOLDER "ONNXRuntime")
set_target_properties(onnxruntime_graph PROPERTIES LINKER_LANGUAGE CXX)
install(DIRECTORY ${PROJECT_SOURCE_DIR}/../include/onnxruntime/core/graph  DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/onnxruntime/core)
source_group(TREE ${REPO_ROOT} FILES ${onnxruntime_graph_src} ${onnxruntime_ir_defs_src})
if (onnxruntime_ENABLE_TRAINING)
    source_group(TREE ${ORTTRAINING_ROOT} FILES ${orttraining_graph_src})
endif()

if (WIN32)
    set(onnxruntime_graph_static_library_flags
        -IGNORE:4221 # LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
    )

    set_target_properties(onnxruntime_graph PROPERTIES
        STATIC_LIBRARY_FLAGS "${onnxruntime_graph_static_library_flags}")

    target_compile_options(onnxruntime_graph PRIVATE
        /EHsc   # exception handling - C++ may throw, extern "C" will not
    )

    # Add Code Analysis properties to enable C++ Core checks. Have to do it via a props file include.
    set_target_properties(onnxruntime_graph PROPERTIES VS_USER_PROPS ${PROJECT_SOURCE_DIR}/EnableVisualStudioCodeAnalysis.props)
endif()

repository: microsoft/onnxruntime-openenclave

repo_name: microsoft/onnxruntime-openenclave

branch_name: refs/heads/openenclave-public

extension: cmake


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

package cmd

import (
	"fmt"
	"os"
	"strconv"

	"github.com/zerobotlabs/nestor-cli/Godeps/_workspace/src/github.com/Bowery/prompt"
	"github.com/zerobotlabs/nestor-cli/Godeps/_workspace/src/github.com/fatih/color"
	"github.com/zerobotlabs/nestor-cli/Godeps/_workspace/src/github.com/spf13/cobra"
	"github.com/zerobotlabs/nestor-cli/app"
	"github.com/zerobotlabs/nestor-cli/login"
	"github.com/zerobotlabs/nestor-cli/version"
)

// deployCmd represents the deploy command
var deployCmd = &cobra.Command{
	Use:   "deploy",
	Short: "Deploy a version of your Power to Nestor",
	Run:   runDeploy,
}

var latestDeploy bool = false

func init() {
	f := deployCmd.Flags()
	f.BoolVarP(&latestDeploy, "latest", "l", false, "Latest Version")
}

func runDeploy(cmd *cobra.Command, args []string) {
	var l *login.LoginInfo
	var a app.App

	// Check if you are logged in first
	if l = login.SavedLoginInfo(); l == nil {
		color.Red("You are not logged in. To login, type \"nestor login\"\n")
		os.Exit(1)
	}

	// Check if you have a valid nestor.json file
	nestorJsonPath, err := pathToNestorJson(args)
	if err != nil {
		color.Red("Could not find nestor.json in the path specified\n")
		os.Exit(1)
	}

	a.ManifestPath = nestorJsonPath

	err = a.ParseManifest()
	if err != nil {
		color.Red("%s\n", err.Error())
		os.Exit(1)
	}

	// Check if existing app exists and if so, then we should be making calls to the "UPDATE" function
	// We are ignoring the error for now but at some point we will have to show an error that is not annoying
	err = a.Hydrate(l)
	if err != nil {
		color.Red("Error fetching details for this power\n")
	}

	if a.Id == 0 {
		color.Red("You haven't saved your power yet. Run `nestor save` before you can deploy your power\n")
		os.Exit(1)
	}

	versions, err := version.FetchVersions(a, l)
	if err != nil {
		color.Red("Error fetching versions for your power\n")
		os.Exit(1)
	}

	if latestDeploy {
		pickedVersion := versions[0]
		if pickedVersion.CurrentlyDeployed {
			color.Green("Version %s already deployed. Nothing to do here\n", pickedVersion.Ref)
		} else {
			err = pickedVersion.Deploy(a, l)

			if err != nil {
				color.Red(err.Error())
				os.Exit(1)
			}

			color.Green("Deployed version %s successfully\n", pickedVersion.Ref)
		}
	} else {
		table := version.TableizeVersions(versions)
		fmt.Printf("\n")
		table.Render()
		fmt.Printf("\n")

		ok := false
		intIndex := 0

		for !ok {
			index, promptErr := prompt.Basic(fmt.Sprintf("Pick a version to deploy (1-%d): ", len(versions)), true)
			if promptErr != nil {
				os.Exit(1)
			}

			intIndex, err = strconv.Atoi(index)
			if err == nil && intIndex > 0 && intIndex <= len(versions) {
				ok = true
			}
		}

		pickedVersion := versions[intIndex-1]
		if pickedVersion.CurrentlyDeployed {
			color.Green("Version %s already deployed. Nothing to do here\n", pickedVersion.Ref)
		} else {
			err = pickedVersion.Deploy(a, l)

			if err != nil {
				color.Red("Error deploying %s. Please try again later or contact hello@asknestor.me\n", pickedVersion.Ref)
				os.Exit(1)
			}

			color.Green("Deployed version %s successfully\n", pickedVersion.Ref)
		}
	}
}

func init() {
	RootCmd.AddCommand(deployCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// deployCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// deployCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

}

repository: arunthampi/nestor-cli

repo_name: arunthampi/nestor-cli


text:
package xjtypes

import (
	"database/sql/driver"
	"encoding/binary"
	"errors"
	"strconv"
	"time"
)

type XjTime time.Time

const (
	timeFormart = "2006-01-02 15:04:05"
	dateFormart = "2006-01-02"
)

// GobEncode implements the gob.GobEncoder interface.
func (t XjTime) GobEncode() ([]byte, error) {
	return time.Time(t).MarshalBinary()
}

//GobDecode implements the gob.GobDecoder interface.
func (t *XjTime) GobDecode(data []byte) error {
	t1 := time.Time(*t)
	return t1.UnmarshalBinary(data)
}

func (t *XjTime) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
	*t = XjTime(now)
	return
}

func (t XjTime) MarshalJSON() ([]byte, error) {
	var tt time.Time
	tt = time.Time(t)
	if tt.IsZero() {
		b := make([]byte, 0, 2)
		b = append(b, '"')
		b = append(b, '"')
		return b, nil
	} else {
		b := make([]byte, 0, len(timeFormart)+2)
		b = append(b, '"')
		b = time.Time(t).AppendFormat(b, timeFormart)
		b = append(b, '"')
		return b, nil
	}
}

func (t XjTime) String() string {
	return time.Time(t).Format(timeFormart)
}

func (t XjTime) StringDiy(sFormat string) string {
	return time.Time(t).Format(sFormat)
}

func (t XjTime) Value() (driver.Value, error) {
	// MyTime 转换成 time.Time 类型
	tTime := time.Time(t)
	return tTime.Format("2006/01/02 15:04:05"), nil
}

func (t *XjTime) Scan(v interface{}) error {
	switch vt := v.(type) {
	case string:
		// 字符串转成 time.Time 类型
		tTime, _ := time.Parse("2006/01/02 15:04:05", vt)
		*t = XjTime(tTime)
	case time.Time:
		*t = XjTime(vt)
	default:
		return errors.New("类型处理错误")
	}
	return nil
}

type EsTime time.Time

func (t *EsTime) UnmarshalJSON(data []byte) (err error) {
	now := time.Unix(int64(binary.BigEndian.Uint32(data)/1000), 0)
	*t = EsTime(now)
	return
}

func (t EsTime) MarshalJSON() ([]byte, error) {
	if time.Time(t).IsZero() {
		return []byte("0"), nil
	} else {
		i := time.Time(t).Unix() * 1000
		str := strconv.FormatInt(i, 10)
		return []byte(str), nil
	}
}
func Int64ToBytes(i int64) []byte {
	var buf = make([]byte, 8)
	binary.BigEndian.PutUint64(buf, uint64(i))
	return buf
}

func BytesToInt64(buf []byte) int64 {
	return int64(binary.BigEndian.Uint64(buf))
}

//func (t EsTime) MarshalJSON() ([]byte, error) {
//var buf = make([]byte, len(timeFormart)+2)
//if time.Time(t).IsZero(){
//	buf = []byte(`"1970-01-01 00:00:00"`)
//}else{
//	i := time.Time(t).Unix()*1000
//	binary.BigEndian.PutUint64(buf, uint64(i))
//}
//return buf, nil
//
//	b := make([]byte, 0, len(timeFormart)+2)
//	b = append(b, '"')
//	b = time.Time(t).AppendFormat(b, timeFormart)
//	b = append(b, '"')
//	if string(b)==`"0001-01-01 00:00:00"`{
//		b = []byte(`"1970-01-01 00:00:00"`)
//	}
//	return b, nil
//}

type EsDate time.Time

func (t *EsDate) UnmarshalJSON(data []byte) (err error) {
	now := time.Unix(int64(binary.BigEndian.Uint32(data)/1000), 0)
	*t = EsDate(now)
	return
}

func (t EsDate) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(dateFormart)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, dateFormart)
	b = append(b, '"')
	if string(b) == `"0001-01-01"` {
		b = []byte(`""`)
	}
	return b, nil
}

type XjDate time.Time

// GobEncode implements the gob.GobEncoder interface.
func (t XjDate) GobEncode() ([]byte, error) {
	return time.Time(t).MarshalBinary()
}

//GobDecode implements the gob.GobDecoder interface.
func (t *XjDate) GobDecode(data []byte) error {
	t1 := time.Time(*t)
	return t1.UnmarshalBinary(data)
}

func (t *XjDate) UnmarshalJSON(data []byte) (err error) {
	now, err := time.ParseInLocation(`"`+dateFormart+`"`, string(data), time.Local)
	*t = XjDate(now)
	return
}

func (t XjDate) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(dateFormart)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, dateFormart)
	b = append(b, '"')
	return b, nil
}

func (t XjDate) String() string {
	return time.Time(t).Format(dateFormart)
}

func (t XjDate) StringDiy(sFormat string) string {
	return time.Time(t).Format(sFormat)
}

func (t XjDate) Value() (driver.Value, error) {
	// MyTime 转换成 time.Time 类型
	tTime := time.Time(t)
	return tTime.Format("2006/01/02"), nil
}

func (t *XjDate) Scan(v interface{}) error {
	switch vt := v.(type) {
	case string:
		// 字符串转成 time.Time 类型
		tTime, _ := time.Parse("2006/01/02", vt)
		*t = XjDate(tTime)
	case time.Time:
		*t = XjDate(vt)
	default:
		return errors.New("类型处理错误")
	}
	return nil
}

type Json string

func (j *Json) UnmarshalJSON(data []byte) (err error) {
	*j = Json(data)
	return
}

func (j Json) MarshalJSON() ([]byte, error) {
	b := []byte(j)
	return b, nil
}

repository: cqiyu/xjgo

repo_name: cqiyu/xjgo


text:
@inproceedings{WangzairanAneffectiveIcip2014,
 abstract = {Most of the quantization based watermarking algorithms are very sensitive to valumetric distortions, while these distortions are regarded as common processing in audio/video analysis. In recent years, watermarking methods which can resist this kind of distortions have attracted a lot of interests. But still many proposed methods can only deal with one certain kind of valumetric distortion as amplitude scaling, and fail in other kinds of valumetric distortions like constant change attack or gamma correction. In this paper, we propose a very simple method to tackle all the three kinds of valumetric distortions. A constant change invariant domain is first constructed by spread transform, in which the watermark is embedded using a certain amplitude scaling invariant based watermarking scheme. Several typical watermarking methods and attacks have been implemented in our experiments to demonstrate the effectiveness of the proposed method.},
 author = {Wang, Zairan and Dong, Jing and Wang, Wei and Tan, Tieniu},
 booktitle = {2014 IEEE International Conference on Image Processing (ICIP)},
 doi = {10.1109/ICIP.2014.7026110},
 isbn = {9781479957514},
 keywords = {QIM,amplitude scaling,valumetric distortions,watermarking},
 month = {oct},
 pages = {5487--5491},
 publisher = {IEEE},
 title = {An effective watermarking method against valumetric distortions},
 url = {http://ieeexplore.ieee.org/document/7026110/},
 year = {2014}
}


text:
require ../../include/rcar-gen2-modules-common.inc

S = "${WORKDIR}"

LICENSE = "CLOSED"
DEPENDS = "fdpm-user-module mmngr-user-module"
SRC_URI = "file://fdpm-tp-user.tar.bz2"

do_compile() {
    cd ${S}/fdpm/
    make all ARCH=arm
}

do_install() {
    # Create destination folder
    mkdir -p ${D}${RENESAS_DATADIR}/bin/

    # Copy user test program
    cp ${S}/fdpm/fdpm_tp ${D}${RENESAS_DATADIR}/bin/
}

PACKAGES = "\
    ${PN} \
"

FILES_${PN} = " \
    ${RENESAS_DATADIR}/bin/fdpm_tp \
"

RPROVIDES_${PN} += "fdpm-tp-user-module"
INHIBIT_PACKAGE_DEBUG_SPLIT = "1"

gha_language: Python


text:
@unknown{whyhpss,
author = {Drossos, Konstantinos and Magron, Paul and Mimilakis, Stylianos and Virtanen, Tuomas},
year = {2018},
month = {07},
pages = {},
title = {Harmonic-Percussive Source Separation with Deep Neural Networks and Phase Recovery}
}

@inproceedings{driedger,
author = {Driedger, Jonathan and Müller, Meinard and Disch, Sascha},
year = {2014},
month = {01},
pages = {},
title = {Extending Harmonic-Percussive Separation of Audio Signals}
}

@article{fitzgerald,
author = {Fitzgerald, Derry},
year = {2010},
month = {01},
pages = {},
title = {Harmonic/Percussive Separation using Median Filtering},
journal = {13th International Conference on Digital Audio Effects (DAFx-10)}
}

@website{librosa,
title={librosa.decompose.hpss},
url={https://librosa.github.io/librosa/generated/librosa.decompose.hpss.html},
journal={librosa.decompose.hpss - librosa 0.7.2 documentation}}

@article{spectraldesc,
author = {Canadas Quesada, Francisco and Vera-Candeas, Pedro and Ruiz Reyes, Nicolas and Carabias-Orti, Julio and Cabañas, Pablo},
year = {2014},
month = {07},
pages = {},
title = {Percussive/harmonic sound separation by non-negative matrix factorization with smoothness/sparseness constraints},
volume = {2014},
journal = {EURASIP Journal on Audio, Speech, and Music Processing},
doi = {10.1186/s13636-014-0026-5}
}

@website{misviola,
title={University of Iowa Electronic Music Studios},
url={http://theremin.music.uiowa.edu/MIS-Pitches-2012/MISViola2012.html}}

@website{freesounddrum,
title={Freesound - ``44 beat kick snare dry 120bpm stick-03.wav'' by @realdavidfloat},
url={https://freesound.org/people/@realdavidfloat/sounds/418992/}}

@website{imagenoise,
title={Noise Removal - MATLAB \& Simulink},
url={https://www.mathworks.com/help/images/noise-removal.html}}

@website{specstft,
title={Spectrogram using short-time Fourier transform - MATLAB spectrogram},
url={https://www.mathworks.com/help/signal/ref/spectrogram.html}}

@website{wienernoise,
title={The Wiener filter},
url={http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/VELDHUIZEN/node15.html}}

@website{movmedian,
title={Moving median - MATLAB movmedian},
url={https://www.mathworks.com/help/matlab/ref/movmedian.html}}

@inproceedings{realtime,
title={The influence of perception latency on the quality of musical performance during a simulated delay scenario},
author={Waldo Greeff},
year={2017}
}

@article{wang2008time,
  title={Time-frequency masking for speech separation and its potential for hearing aid design},
  author={Wang, DeLiang},
  journal={Trends in amplification},
  volume={12},
  number={4},
  pages={332--353},
  year={2008},
  publisher={SAGE Publications Sage CA: Los Angeles, CA}
}

@phdthesis{timefreq2,
author = {Pirhosseinloo, Shadi},
year = {2019},
month = {12},
pages = {},
title = {Using deep learning methods for supervised speech enhancement in noisy and reverberant environments}
}

@website{stftchunks1,
author={Hristo Zhivomirov},
title={Short-Time Fourier Transform (STFT) with Matlab -  File Exchange - MATLAB Central},
url={https://www.mathworks.com/matlabcentral/fileexchange/45577-inverse-short-time-fourier-transform-istft-with-matlab}}

@website{dsp1,
title={Stream from audio file - MATLAB},
url={https://www.mathworks.com/help/dsp/ref/dsp.audiofilereader-system-object.html}}

@website{dsp2,
title={Stream to audio file - MATLAB},
url={https://www.mathworks.com/help/dsp/ref/dsp.audiofilewriter-system-object.html}}

@website{tictoc,
title={Start stopwatch timer - MATLAB tic},
url={https://www.mathworks.com/help/matlab/ref/tic.html}}

@website{god,
title={Time-Frequency Masking for Harmonic-Percussive Source Separation
- MATLAB \& Simulink},
url={https://www.mathworks.com/help/audio/examples/time-frequency-masking-for-harmonic-percussive-source-separation.html}}

@website{cola,
title={Determine whether window-overlap combination is COLA compliant - MATLAB iscola},
url={https://www.mathworks.com/help/signal/ref/iscola.html}}

@article{whyoverlap,
author = {Heinzel, Gerhard and Rüdiger, Albrecht and Schilling, R},
year = {2002},
month = {01},
pages = {},
title = {Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new flat-top windows},
volume = {12},
journal = {Max Plank Inst}
}

@article{leakage,
title={FFT and Spectral Leakage - GaussianWaves},
url={https://www.gaussianwaves.com/2011/01/fft-and-spectral-leakage-2/}}

@incollection{timefreq,
title = "CHAPTER 7 - Frequency Domain Processing",
editor = "Nasser Kehtarnavaz",
booktitle = "Digital Signal Processing System Design (Second Edition)",
publisher = "Academic Press",
edition = "Second Edition",
address = "Burlington",
pages = "175 - 196",
year = "2008",
isbn = "978-0-12-374490-6",
doi = "https://doi.org/10.1016/B978-0-12-374490-6.00007-6",
url = "http://www.sciencedirect.com/science/article/pii/B9780123744906000076",
author = "Nasser Kehtarnavaz"
}

@misc{zafar,
  author        = {Zafar Rafii},
  title         = {Time-frequency Masking -- EECS 352: Machine Perception of Music \& Audio},
  month         = {Winter},
  year          = {2014},
  publisher={Northwestern University}}

repository: sevagh/Real-Time-HPSS

repo_name: sevagh/Real-Time-HPSS

gha_language: TeX


text:
SUMMARY = "Music Player Daemon"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=751419260aa954499f7abaabaa882bbe"
HOMEPAGE ="http://www.musicpd.org"

inherit autotools useradd systemd pkgconfig

DEPENDS += " \
    libsamplerate0 \
    curl \
    sqlite \
    tcp-wrappers \
    yajl \
    libcdio \
    libopus \
    boost \
    icu \
    dbus \
    expat \
    zlib \
"

# While this item does not require it, it depends on mpg123 which does
LICENSE_FLAGS = "commercial"

SRC_URI = " \
    http://www.musicpd.org/download/${BPN}/0.20/${BP}.tar.xz \
    file://mpd.conf.in \
"
SRC_URI[md5sum] = "a722432b53af45413d9b405b2e8e831f"
SRC_URI[sha256sum] = "503e5f9f237290f568ff7956ab2f9aed563594bf749f19b8fe994fb21434afea"

EXTRA_OECONF = "enable_bzip2=yes"
EXTRA_OECONF += "${@bb.utils.contains('DISTRO_FEATURES', 'systemd', '--with-systemdsystemunitdir=${systemd_unitdir}/system/', '--without-systemdsystemunitdir', d)}"

PACKAGECONFIG ??= "alsa ffmpeg flac id3tag mpg123 vorbis"
PACKAGECONFIG[aad] = "--enable-aac,--disable-aac,faad2"
PACKAGECONFIG[ao] = "--enable-ao,--disable-ao,libao"
PACKAGECONFIG[alsa] = "--enable-alsa,--disable-alsa,alsa-lib"
PACKAGECONFIG[audiofile] = "--enable-audiofile,--disable-audiofile,audiofile"
PACKAGECONFIG[bzip2] = "--enable-bzip2,--disable-bzip2,bzip2"
PACKAGECONFIG[cdioparanoia] = "--enable-cdio-paranoia,--disable-cdio-paranoia,libcdio-paranoia"
PACKAGECONFIG[ffmpeg] = "--enable-ffmpeg,--disable-ffmpeg,ffmpeg"
PACKAGECONFIG[flac] = "--enable-flac,--disable-flac,flac"
PACKAGECONFIG[fluidsynth] = "--enable-fluidsynth,--disable-fluidsynth,fluidsynth"
PACKAGECONFIG[id3tag] = "--enable-id3,--disable-id3,libid3tag"
PACKAGECONFIG[jack] = "--enable-jack,--disable-jack,jack"
PACKAGECONFIG[mad] = "--enable-mad,--disable-mad,libmad"
PACKAGECONFIG[mpg123] = "--enable-mpg123,--disable-mpg123,mpg123"
PACKAGECONFIG[modplug] = "--enable-modplug,--disable-modplug,libmodplug"
PACKAGECONFIG[mms] = "--enable-mms,--disable-mms,libmms"
PACKAGECONFIG[lame] = "--enable-lame-encoder,--disable-lame-encoder,lame"
PACKAGECONFIG[openal] = "--enable-openal,--disable-openal,openal-soft"
PACKAGECONFIG[pulse] = "--enable-pulse,--disable-pulse,pulseaudio"
PACKAGECONFIG[smb] = "--enable-smbclient,--disable-smbclient,samba"
PACKAGECONFIG[sndfile] = "--enable-sndfile,--disable-sndfile,libsndfile1"
PACKAGECONFIG[upnp] = "--enable-upnp,--disable-upnp,libupnp"
PACKAGECONFIG[vorbis] = "--enable-vorbis,--disable-vorbis,libvorbis libogg"
PACKAGECONFIG[wavpack] = "--enable-wavpack,--disable-wavpack,wavpack"

FILES_${PN} += "/usr/share/icons/*"

do_configure_prepend() {
    sed -i -e 's|libsystemd-daemon|libsystemd|' ${S}/configure.ac
}

do_install_append() {
    install -d ${D}/${localstatedir}/lib/mpd/music
    chmod 775 ${D}/${localstatedir}/lib/mpd/music
    install -d ${D}/${localstatedir}/lib/mpd/playlists
    chown -R mpd ${D}/${localstatedir}/lib/mpd
    chown mpd:mpd ${D}/${localstatedir}/lib/mpd/music

    install -d ${D}/${sysconfdir}
    install -m 644 ${WORKDIR}/mpd.conf.in ${D}/${sysconfdir}/mpd.conf
    sed -i \
        -e 's|%music_directory%|${localstatedir}/lib/mpd/music|' \
        -e 's|%playlist_directory%|${localstatedir}/lib/mpd/playlists|' \
        -e 's|%db_file%|${localstatedir}/lib/mpd/mpd.db|' \
        -e 's|%log_file%|${localstatedir}/log/mpd.log|' \
        -e 's|%state_file%|${localstatedir}/lib/mpd/state|' \
        ${D}/${sysconfdir}/mpd.conf

    if [ -e ${D}/${systemd_unitdir}/system/mpd.service ] ; then
        sed -i \
            's|^ExecStart=.*|ExecStart=${bindir}/mpd --no-daemon|' \
            ${D}/${systemd_unitdir}/system/mpd.service
    fi
}

RPROVIDES_${PN} += "${PN}-systemd"
RREPLACES_${PN} += "${PN}-systemd"
RCONFLICTS_${PN} += "${PN}-systemd"
SYSTEMD_SERVICE_${PN} = "mpd.socket"

USERADD_PACKAGES = "${PN}"
USERADD_PARAM_${PN} = " \
    --system --no-create-home \
    --home ${localstatedir}/lib/mpd \
    --groups audio \
    --user-group mpd"

repository: shaffenmeister/meta-cap

repo_name: shaffenmeister/meta-cap


text:
/* Copyright 2018 Bruce Liu.  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.
 */

package register

import (
	"testing"
	"fmt"
	"strings"
	etcd3 "github.com/coreos/etcd/clientv3"
	"context"
	"goservice"
)

func Test_Register(t *testing.T) {
	fmt.Println("asdasda")
	endpoints := []string{"119.23.67.84:2379", "120.79.38.97:2379"}
	Register("TestService", "192.168.0.1", 8080, endpoints, 10, 10)
	//Register()
}

func Test_GetData(t *testing.T) {
	client, err := etcd3.New(etcd3.Config{
		Endpoints: strings.Split("119.23.67.84:2379,120.79.38.97:2379", ","),
	})
	if err != nil {
		fmt.Println("Create etcdClient failed: ", err.Error())
		return
	}
	key := fmt.Sprintf("/%s/%s", service.Prefix, "TestServic2")
	// should get first, if not exist, set it
	resp, err := client.Get(context.Background(), key, etcd3.WithPrefix())
	if err != nil {
		fmt.Println("Get Data failed: ", err.Error())
		return
	}
	serviceList := service.ExtractAddress(resp)
	fmt.Println(serviceList)
}

repository: dulumao/goservice

repo_name: dulumao/goservice


text:
require gpe-ownerinfo.inc

PR = "r3"

SRC_URI += "file://compile.patch"

SRC_URI[md5sum] = "25b02a6d7fbbb2966e2481930bd55591"
SRC_URI[sha256sum] = "3072876709e8fb58eda893ec0acb50b3eb6b8a7c808f4fbd74657c139933971a"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
# This file is part of the pCloud Console Client.
#
# (c) 2021 Serghei Iakovlev <egrep@protonmail.ch>
#
# For the full copyright and license information, please view
# the LICENSE file that was distributed with this source code.

include(BuildType)

# Make sure developers do not run cmake in the main project directory,
# to keep build artifacts from becoming clutter
get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH)
get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH)

if(srcdir STREQUAL bindir)
  message(FATAL_ERROR
      "In-source builds not allowed. They are unsupportable in practice, they spill "
      "their guts into .gitignore, and they turn buildsystem bugs into damage to sources. "
      "Instead, build the project out-of source: Create a "
      "separate directory for the build *outside of the source folder*, and run "
      "cmake <path to the source dir> and build from there."
      "You may need to remove CMakeCache.txt.")
endif()

include(ProcessorCount)

ProcessorCount(N)
if(NOT N EQUAL 0)
  set(BUILD_JOBS ${N})
else()
  message(WARNING
      "There's a problem determining the processor count. Set fallback to: 2")
  set(BUILD_JOBS 2)
endif()

# Configure how 'find_*' commands choose between macOS Frameworks and
# unix-style package components.
if(APPLE)
  set(CMAKE_FIND_FRAMEWORK LAST)
endif()

# Generate a "compile_commands.json" file containing the exact compiler
# calls for all translation units of the project in machine-readable form.
# This is useful  for all sorts of tools ("clang-tidy", "cppcheck", "oclint",
# "include-what-you-use", etc).
#
# Note This option is implemented only by Makefile Generators and the Ninja.
# It is ignored on other generators.
#
# For more see:
# https://cmake.org/cmake/help/latest/variable/CMAKE_EXPORT_COMPILE_COMMANDS.html
set(CMAKE_EXPORT_COMPILE_COMMANDS 1)

repository: pclausen/pcloud-console-client

repo_name: pclausen/pcloud-console-client


text:
@article{qi2020imagebert,
  title={Imagebert: Cross-modal pre-training with large-scale weak-supervised image-text data},
  author={Qi, Di and Su, Lin and Song, Jia and Cui, Edward and Bharti, Taroon and Sacheti, Arun},
  journal={arXiv preprint arXiv:2001.07966},
  year={2020}
}

url: https://raw.githubusercontent.com/rbt-c/DL-NLP-Readings/82ca76e9184a3b00ac87129d99391477c85cfcd2/Bibtex/ImageBERT - Cross-modal Pre-training with Large-scale Weak-supervised Image-Text Data.bib

repository: rbt-c/DL-NLP-Readings

repo_name: rbt-c/DL-NLP-Readings


text:
SUMMARY = "A text hyphenation library"
HOMEPAGE = "http://hunspell.sourceforge.net/"
LICENSE = "LGPL-2.1-only | GPL-2.0-only | MPL-1.1"
LIC_FILES_CHKSUM = " \
    file://COPYING;md5=d45e3467790c1cae990cc9ca3293bc97 \
    file://COPYING.LGPL;md5=d8045f3b8f929c1cb29a1e3fd737b499 \
    file://COPYING.MPL;md5=bfe1f75d606912a4111c90743d6c7325 \
"

SRC_URI = "${SOURCEFORGE_MIRROR}/project/hunspell/Hyphen/2.8/${BPN}-${PV}.tar.gz"
SRC_URI[md5sum] = "5ade6ae2a99bc1e9e57031ca88d36dad"
SRC_URI[sha256sum] = "304636d4eccd81a14b6914d07b84c79ebb815288c76fe027b9ebff6ff24d5705"

inherit autotools pkgconfig

RDEPENDS:${PN} = "perl"

BBCLASSEXTEND = "native"

repository: schnitzeltony/meta-office

repo_name: schnitzeltony/meta-office


text:
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.

option(ENABLE_ADDRESS_SANITIZER "Enabled building with address sanitizer. Note for gcc libasan must be installed," OFF)
option(ENABLE_UNDEFINED_SANITIZER "Enabled building with undefined behavior sanitizer." OFF)
option(ENABLE_THREAD_SANITIZER "Enabled building with thread sanitizer." OFF)

# Clear "Advanced" flag for sanitizer options
mark_as_advanced(CLEAR ENABLE_ADDRESS_SANITIZER)
mark_as_advanced(CLEAR ENABLE_UNDEFINED_SANITIZER)
mark_as_advanced(CLEAR ENABLE_THREAD_SANITIZER)

if (ENABLE_ADDRESS_SANITIZER)
    if("${CMAKE_C_COMPILER_ID}" MATCHES "Clang")
        set(CMAKE_C_FLAGS "-fsanitize=address -fno-omit-frame-pointer ${CMAKE_C_FLAGS}")
        set(CMAKE_CXX_FLAGS "-fsanitize=address -fno-omit-frame-pointer ${CMAKE_CXX_FLAGS}")
    elseif ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU")
        set(CMAKE_C_FLAGS "-lasan -fsanitize=address -fno-omit-frame-pointer ${CMAKE_C_FLAGS}")
        set(CMAKE_CXX_FLAGS "-lasan -fsanitize=address -fno-omit-frame-pointer ${CMAKE_CXX_FLAGS}")
    else ()
        message(WARNING "Address sanitizer is not supported for ${CMAKE_C_COMPILER_ID}")
    endif ()

    if (ENABLE_TESTING)
        set(CMAKE_C_FLAGS "-DCPPUTEST_MEM_LEAK_DETECTION_DISABLED ${CMAKE_C_FLAGS}")
        set(CMAKE_CXX_FLAGS "-DCPPUTEST_MEM_LEAK_DETECTION_DISABLED ${CMAKE_CXX_FLAGS}")
    endif ()
endif()

if (ENABLE_UNDEFINED_SANITIZER)
    set(CMAKE_C_FLAGS "-fsanitize=undefined ${CMAKE_C_FLAGS}")
    set(CMAKE_CXX_FLAGS "-fsanitize=undefined ${CMAKE_CXX_FLAGS}")
endif()

if (ENABLE_THREAD_SANITIZER)
    set(CMAKE_C_FLAGS "-fsanitize=thread ${CMAKE_C_FLAGS}")
    set(CMAKE_CXX_FLAGS "-fsanitize=thread ${CMAKE_CXX_FLAGS}")
endif()

MACRO(celix_subproject)
    set(ARGS "${ARGN}")

    list(GET ARGS 0 OPTION_NAME)
    list(REMOVE_AT ARGS 0)

    list(GET ARGS 0 OPTION_DESCRIPTION)
    list(REMOVE_AT ARGS 0)

    list(GET ARGS 0 OPTION_DEFAULT)
    list(REMOVE_AT ARGS 0)

    set(OPTIONS )
    set(ONE_VAL_ARGS )
    set(MULTI_VAL_ARGS DEPS)
    cmake_parse_arguments(OPTION "${OPTIONS}" "${ONE_VAL_ARGS}" "${MULTI_VAL_ARGS}" ${ARGS})

    string(TOUPPER ${OPTION_NAME} UC_OPTION_NAME)
    set(NAME "BUILD_${UC_OPTION_NAME}")

    option(${NAME} "${OPTION_DESCRIPTION}" ${OPTION_DEFAULT})

    IF (${NAME})
        set(${OPTION_NAME} "ON")
        FOREACH (DEP ${OPTION_DEPS})
            string(TOUPPER ${DEP} UC_DEP)
            set(DEP_NAME "BUILD_${UC_DEP}")
            if (NOT ${DEP_NAME})
                message(FATAL_ERROR "${DEP} is required by ${OPTION_NAME}: please add -D${DEP_NAME}:BOOL=ON")
            endif ()
        ENDFOREACH (DEP)
    ENDIF (${NAME})
ENDMACRO(celix_subproject)

#[[
Custom target which list the Celix CMake targets that are still using deprecated headers.
]]
if (NOT TARGET celix-deprecated)
    add_custom_target(celix-deprecated
        COMMAND ${CMAKE_COMMAND} -E echo "Targets still using deprecated utils headers: $<JOIN:$<TARGET_PROPERTY:celix-deprecated,UTIL_TARGETS>, >"
        COMMAND ${CMAKE_COMMAND} -E echo "Targets still using deprecated framework headers: $<JOIN:$<TARGET_PROPERTY:celix-deprecated,FRAMEWORK_TARGETS>, >"
    )
    set_target_properties(celix-deprecated PROPERTIES "UTIL_TARGETS" "")
    set_target_properties(celix-deprecated PROPERTIES "FRAMEWORK_TARGETS" "")

endif ()

#[[
Add include path for the Celix utils deprecated headers to the provided target (as PRIVATE)

```CMake
celix_deprecated_utils_headers(<target_name>))
```
]]
function(celix_deprecated_utils_headers)
    list(GET ARGN 0 TARGET_NAME)
    get_target_property(UTILS_SOURCE_DIR Celix::utils "SOURCE_DIR")
    target_include_directories(${TARGET_NAME} PRIVATE ${UTILS_SOURCE_DIR}/include_deprecated)
    set_property(TARGET celix-deprecated APPEND PROPERTY "UTIL_TARGETS" "${TARGET_NAME}")
endfunction()

#[[
Add include path for the Celix framework deprecated headers to the provided target (as PRIVATE)

```CMake
celix_deprecated_framework_headers(<target_name>))
```
]]
function(celix_deprecated_framework_headers)
    list(GET ARGN 0 TARGET_NAME)
    get_target_property(FRAMEWORK_SOURCE_DIR Celix::framework "SOURCE_DIR")
    target_include_directories(${TARGET_NAME} PRIVATE ${FRAMEWORK_SOURCE_DIR}/include_deprecated)
    set_property(TARGET celix-deprecated APPEND PROPERTY "FRAMEWORK_TARGETS" "${TARGET_NAME}")
endfunction()

include(${CMAKE_CURRENT_LIST_DIR}/ApacheRat.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/CodeCoverage.cmake)

repository: apache/celix

repo_name: apache/celix

gha_language: C


text:
@article{scikit-learn,
title={Scikit-learn: Machine Learning in {P}ython},
author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
        and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
        and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
        Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
journal={Journal of Machine Learning Research},
volume={12},
pages={2825--2830},
year={2011}
}

@article{openturns,
author = {{Baudin}, M. and {Dutfoy}, A. and {Iooss}, B. and {Popelin}, A.-L.},
title = "{Open TURNS: An industrial software for uncertainty quantification in simulation}",
journal = {ArXiv e-prints},
archivePrefix = "arXiv",
eprint = {1501.05242},
primaryClass = "stat.CO",
keywords = {Statistics - Computation, Mathematics - Statistics Theory},
year = {2015},
month = {jan},
adsurl = {http://adsabs.harvard.edu/abs/2015arXiv150105242B},
adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@article{roy2017a,
author = {Roy, Pamphile Tupui and Segui, Luis Miguel and Jouhaud, Jean-Christophe and Gicquel, Laurent},
journal = {In review in: International Journal for Numerical Methods in Fluids},
title = {Resampling Strategies to Improve Surrogate Model-based Uncertainty Quantification - Application to LES of LS89},
year = {2017}
}

@conference{roy2017b,
author = {Roy, Pamphile T. and Daviller, G. and Jouhaud, J.-C. and Cuenot, B.},
title = {Uncertainty Quantification-Driven Robust Design Assessment of a Swirler’s Geometry},
year = {2017}, booktitle = {INitiative en Combustion Avancée (INCA) 2017},
organization = {SAFRAN TECH},
address = {Paris-Saclay},
url = {https://www.researchgate.net/publication/320518082_Uncertainty_Quantification-Driven_Robust_Design_Assessment_of_a_Swirler%27s_Geometry}
}

@article{roy2017c,
archivePrefix = {arXiv},
arxivId = {1705.01440},
author = {Roy, Pamphile Tupui and {El Mo{\c{c}}ayd}, Nabil and Ricci, Sophie and Jouhaud, Jean-Christophe and Goutal, Nicole and {De Lozzo}, Matthias and Rochoux, M{\'{e}}lanie C.},
doi = {10.1007/s00477-017-1470-4},
issn = {1436-3240},
journal = {Stochastic Environmental Research and Risk Assessment},
title = {Comparison of polynomial chaos and Gaussian process surrogates for uncertainty quantification and correlation estimation of spatially distributed open-channel steady flows},
url = {http://arxiv.org/abs/1705.01440 http://link.springer.com/10.1007/s00477-017-1470-4},
year = {2017}
}

repository: tupui/batman

repo_name: tupui/batman

gha_language: GLSL


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

package storage

import (
	"context"
	"sync"
	"time"

	"github.com/jinzhu/gorm"

	"github.com/erda-project/erda-infra/base/logs"
)

type ttlStore interface {
	GetSecondByKey(key string) int
	Run(ctx context.Context, interval time.Duration)
}

type mysqlStore struct {
	defaultTTLSec int
	ttlValue      map[string]int
	mysql         *gorm.DB
	Log           logs.Logger
	mu            sync.RWMutex
}

func (m *mysqlStore) GetSecondByKey(key string) int {
	m.mu.RLock()
	ttl, ok := m.ttlValue[key]
	m.mu.RUnlock()
	if ok {
		return ttl
	}
	return m.defaultTTLSec
}

func (m *mysqlStore) Run(ctx context.Context, interval time.Duration) {
	ticker := time.NewTicker(interval)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			if err := m.loadLogsTTL(); err != nil {
				m.Log.Errorf("loadLogs failed. err=%s", err)
			}
		case <-ctx.Done():
			return
		}
	}
}

type MonitorConfig struct {
	OrgName string `gorm:"column:org_name"`
	Names   string `gorm:"column:names"`
	Filters string `gorm:"column:filters"`
	Config  []byte `gorm:"column:config"`
	Key     string `gorm:"column:key"`
}

type monitorConfig struct {
	TTL string `gorm:"column:ttl" json:"ttl"`
}

func (m *mysqlStore) loadLogsTTL() error {
	var list []*MonitorConfig
	if err := m.mysql.Table("sp_monitor_config").Where("`type`='log' AND `enable`=1").Find(&list).Error; err != nil {
		m.Log.Errorf("fail to load sp_monitor_config: %s", err)
		return err
	}
	ttlmap := m.populateTTLValue(list)
	m.mu.Lock()
	m.ttlValue = ttlmap
	m.mu.Unlock()
	m.Log.Info("load logs ttl config")
	return nil
}

func (m *mysqlStore) populateTTLValue(list []*MonitorConfig) map[string]int {
	ttlMap := make(map[string]int)
	for _, item := range list {
		var mc monitorConfig
		err := json.Unmarshal(item.Config, &mc)
		if err != nil || len(mc.TTL) <= 0 {
			m.Log.Errorf("invalid monitor log config for key=%s", item.Key)
			continue
		}
		d, err := time.ParseDuration(mc.TTL)
		if err != nil || int64(d) < int64(time.Second) {
			m.Log.Errorf("invalid monitor log config for key=%s, %s", item.Key, err)
			continue
		}
		ttlMap[item.OrgName] = int(d.Seconds())
	}
	return ttlMap
}

repository: hoozecn/erda

repo_name: hoozecn/erda


text:
@article{zarzo-arias_importance_2022,
	title = {Importance of data selection and filtering in species distribution models: {A} case study on the {Cantabrian} brown bear},
	volume = {13},
	issn = {2150-8925},
	url = {https://onlinelibrary.wiley.com/doi/abs/10.1002/ecs2.4284},
	doi = {10.1002/ecs2.4284},
	number = {12},
	journal = {Ecosphere},
	author = {Zarzo-Arias, Alejandra and Penteriani, Vincenzo and Gábor, Lukáš and Šímová, Petra and Grattarola, Florencia and Moudrý, Vítězslav},
	year = {2022},
	pages = {e4284},
}

repository: bienflorencia/personal-site

repo_name: bienflorencia/personal-site


text:
/////////////////////////////////
// Empty Interface
/////////////////////////////////

// Empty Interface is a Core Concept in Go
// Any Go type satisfies the empty interface and that means it can represent any value.
// An empty interface may hold values of any type.

package main

import "fmt"

// declaring an empty interface
type emptyInterface interface {
}

// declaring a new struct type which has one field of type empty interface
type person struct {
	info interface{}
}

func main() {

	// declaring an empty interface value
	var empty interface{}

	// an empty interface may hold values of any type
	// storing an int in the empty interface
	empty = 5
	fmt.Println(empty) // => 5

	// storing a string in the empty interface
	empty = "Go"
	fmt.Println(empty) // => Go

	// storing a slice in the empty interface
	empty = []int{2, 34, 4}
	fmt.Println(empty) // => [2 34 4]

	// fmt.Println(len(empty)) -> error, and it doesn't work!

	// retrieving the dynamic value using an assertion
	fmt.Println(len(empty.([]int))) // => 3

	// declaring person value
	you := person{}

	// assigning any value to empty interface field
	you.info = "You name"
	you.info = 40
	you.info = []float64{4.5, 6., 8.1}

	fmt.Println(you.info)
}


text:
@book{o2014analysis,
  title={Analysis of boolean functions},
  author={O'Donnell, Ryan},
  year={2014},
  publisher={Cambridge University Press}
},
@article{kushilevitz1997communication,
  title={Communication complexity},
  author={Kushilevitz, Eyal},
  journal={Advances in Computers},
  volume={44},
  pages={331--360},
  year={1997},
  publisher={Elsevier}
},
@book{kullback1997information,
  title={Information theory and statistics},
  author={Kullback, Solomon},
  year={1997},
  publisher={Courier Dover Publications}
},
@inproceedings{huang2004extreme,
  title={Extreme learning machine: a new learning scheme of feedforward neural networks},
  author={Huang, Guang-Bin and Zhu, Qin-Yu and Siew, Chee-Kheong},
  booktitle={Neural Networks, 2004. Proceedings. 2004 IEEE International Joint Conference on},
  volume={2},
  pages={985--990},
  year={2004},
  organization={IEEE}
},
@article{huang2012extreme,
  title={Extreme learning machine for regression and multiclass classification},
  author={Huang, Guang-Bin and Zhou, Hongming and Ding, Xiaojian and Zhang, Rui},
  journal={Systems, Man, and Cybernetics, Part B: Cybernetics, IEEE Transactions on},
  volume={42},
  number={2},
  pages={513--529},
  year={2012},
  publisher={IEEE}
},
@article{fanaee2014event,
  title={Event labeling combining ensemble detectors and background knowledge},
  author={Fanaee-T, Hadi and Gama, Joao},
  journal={Progress in Artificial Intelligence},
  volume={2},
  number={2-3},
  pages={113--127},
  year={2014},
  publisher={Springer}
}

repository: mctsdmr/velespit

repo_name: mctsdmr/velespit


text:
package ui

import (
	"github.com/gpayer/pixelext/nodes"

	"github.com/faiface/pixel"
)

type UINode interface {
	nodes.Node
	GetOrigPos() pixel.Vec
	Size() pixel.Vec
	Alignment() nodes.Alignment
	SetAlignment(a nodes.Alignment)
	OverrideStyles(styles *nodes.Styles)
	HAlignment() nodes.HorizontalAlignment
	SetHAlignment(h nodes.HorizontalAlignment)
	VAlignment() nodes.VerticalAlignment
	SetVAlignment(v nodes.VerticalAlignment)
	IsStylesOverridden() bool
	SetStylesOverridden(overridden bool)
}

repository: gpayer/pixelext

repo_name: gpayer/pixelext


text:
vcpkg_fail_port_install(ON_TARGET "UWP")

if(VCPKG_TARGET_IS_WINDOWS)
    vcpkg_check_linkage(ONLY_STATIC_LIBRARY)
endif()

vcpkg_from_github(
    OUT_SOURCE_PATH SOURCE_PATH
    REPO stevenlovegrove/Pangolin
    REF dd801d244db3a8e27b7fe8020cd751404aa818fd #v0.6
    SHA512 8004ab6f146f319df41e4b8d4bdb6677b8faf6db725e34fea76fcbf065522fa286d334c2426dcb39faf0cfb3332946104f78393d2b2b2418fe02d91450916e78
    HEAD_REF master
    PATCHES
        fix-includepath-error.patch # include path has one more ../
        fix-cmake-version.patch
        fix-build-error-in-vs2019.patch
        fix-dependencies.patch
)

vcpkg_check_features(OUT_FEATURE_OPTIONS FEATURE_OPTIONS
    FEATURES
        test        BUILD_TESTS
        tools       BUILD_TOOLS
        examples    BUILD_EXAMPLES
        gui         BUILD_PANGOLIN_GUI
        vars        BUILD_PANGOLIN_VARS
        video       BUILD_PANGOLIN_VIDEO
        pybind11    BUILD_PANGOLIN_PYTHON
        eigen       BUILD_PANGOLIN_EIGEN
        ffmpeg      BUILD_PANGOLIN_FFMPEG
        realsense   BUILD_PANGOLIN_LIBREALSENSE2
        openni2     BUILD_PANGOLIN_OPENNI2
        uvc         BUILD_PANGOLIN_LIBUVC
        png         BUILD_PANGOLIN_LIBPNG
        jpeg        BUILD_PANGOLIN_LIBJPEG
        tiff        BUILD_PANGOLIN_LIBTIFF
        openexr     BUILD_PANGOLIN_LIBOPENEXR
        zstd        BUILD_PANGOLIN_ZSTD
        lz4         BUILD_PANGOLIN_LZ4
        module      BUILD_PYPANGOLIN_MODULE
)

file(REMOVE "${SOURCE_PATH}/CMakeModules/FindGLEW.cmake")
file(REMOVE "${SOURCE_PATH}/CMakeModules/FindFFMPEG.cmake")

string(COMPARE EQUAL "${VCPKG_CRT_LINKAGE}" "static" MSVC_USE_STATIC_CRT)

vcpkg_cmake_configure(
    SOURCE_PATH "${SOURCE_PATH}"
    OPTIONS ${FEATURE_OPTIONS}
        -DBUILD_EXTERN_GLEW=OFF
        -DBUILD_EXTERN_LIBPNG=OFF
        -DBUILD_EXTERN_LIBJPEG=OFF
        -DBUILD_PANGOLIN_PLEORA=OFF
        -DBUILD_PANGOLIN_TELICAM=OFF
        -DBUILD_PANGOLIN_DEPTHSENSE=OFF
        -DBUILD_PANGOLIN_OPENNI=OFF
        -DBUILD_PANGOLIN_UVC_MEDIAFOUNDATION=OFF
        -DBUILD_PANGOLIN_LIBREALSENSE=OFF
        -DBUILD_PANGOLIN_V4L=OFF
        -DBUILD_PANGOLIN_LIBDC1394=OFF
        -DBUILD_PANGOLIN_TOON=OFF
        -DDISPLAY_WAYLAND=OFF
        -DDISPLAY_X11=OFF
        -DBUILD_FOR_GLES_2=OFF
        -DMSVC_USE_STATIC_CRT=${MSVC_USE_STATIC_CRT}
    MAYBE_UNUSED_VARIABLES
        MSVC_USE_STATIC_CRT
        BUILD_FOR_GLES_2
)

vcpkg_cmake_install()

vcpkg_cmake_config_fixup(CONFIG_PATH lib/cmake/Pangolin)

vcpkg_copy_pdbs()

file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/debug/include")

if("tools" IN_LIST FEATURES)
    vcpkg_copy_tools(TOOL_NAMES Plotter VideoConvert VideoJsonPrint VideoJsonTransform VideoViewer AUTO_CLEAN)
endif()

if(VCPKG_LIBRARY_LINKAGE STREQUAL "static")
    file(REMOVE_RECURSE "${CURRENT_PACKAGES_DIR}/bin" "${CURRENT_PACKAGES_DIR}/debug/bin")
endif()

if(VCPKG_TARGET_IS_WINDOWS)
    # Copy missing header file
    file(COPY "${CURRENT_BUILDTREES_DIR}/${TARGET_TRIPLET}-dbg/src/include/pangolin/pangolin_export.h" DESTINATION "${CURRENT_PACKAGES_DIR}/include/pangolin")
endif()

# Put the license file where vcpkg expects it
file(COPY "${CURRENT_PORT_DIR}/usage" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}")
file(INSTALL "${SOURCE_PATH}/LICENCE" DESTINATION "${CURRENT_PACKAGES_DIR}/share/${PORT}" RENAME copyright)

gha_license_id: NOASSERTION


text:
package localFSM

import (
	"time"

	"../def"
	"../elevatorLogic"
)

func EventManager(hallReqCh <-chan def.OrderStatus, acceptOrderCh <-chan def.Button,
	statesToNetworkCh chan<- def.States, statesToBackupCh chan<- def.States, statesToOrderAssignerCh chan<- def.States,
	floorSensorCh <-chan int, buttonPressCh chan def.Button, buttonLightCh chan<- def.ButtonLight,
	motorDirCh chan<- def.MotorDirection, doorLightCh chan<- bool, id string, initialFloor int) {

	/***************Initialization**********************/
	localState.Id = id
	localState.Behaviour = def.IDLE
	localState.Direction = def.STOP
	localState.Floor = initialFloor
	/**************************************************/

	doorTimedOutCh := make(chan bool)
	doorResetCh := make(chan bool)
	go doorTimer(doorTimedOutCh, doorResetCh)

	isStuckCh := make(chan bool)
	stuckTimerCh := make(chan timerOption)
	go stuckTimer(isStuckCh, stuckTimerCh)

	// Ticker to send states at regular interval
	ticker := time.NewTicker(def.STATE_TRANSMIT_INTERVAL)

	for {
		select {
		case floor := <-floorSensorCh:
			newFloorReached(buttonLightCh, motorDirCh, doorLightCh, stuckTimerCh, isStuckCh, floor)
			if localState.Behaviour == def.DOOR_OPEN {
				doorResetCh <- true
			}

		case button := <-buttonPressCh:
			if elevatorLogic.ShouldOpenDoor(localState, button) {
				doorLightCh <- true
				localState.Behaviour = def.DOOR_OPEN
				doorResetCh <- true

			} else {
				newOrderPlaced(buttonLightCh, motorDirCh, button, stuckTimerCh)
			}

		case <-doorTimedOutCh:
			doorTimerTimedOut(motorDirCh, doorLightCh, stuckTimerCh)

		case hallReq := <-hallReqCh:
			// Update the hallrequest status with status from orderAssigner
			localState.HallRequests[hallReq.Floor][hallReq.Type] = hallReq.Status

		case order := <-acceptOrderCh:
			// Accept hall request distributed by orderAssigner
			acceptOrder(motorDirCh, stuckTimerCh, doorResetCh, doorLightCh, order)

		case <-ticker.C:
			statesToNetworkCh <- localState
			statesToBackupCh <- localState
			statesToOrderAssignerCh <- localState
		case <-isStuckCh:
			elevatorStuck()

		}

	}

}

// Treat orders at the floor it arrives at or keep going if there are no orders
func newFloorReached(buttonLightCh chan<- def.ButtonLight, motorDirCh chan<- def.MotorDirection,
	doorLightCh chan<- bool, stuckTimerCh chan<- timerOption, isStuckCh chan<- bool, floor int) {
	if localState.Behaviour != def.MOVING {
		return
	}

	localState.Floor = floor

	if !elevatorLogic.ShouldStop(localState) {
		// Elevator continues to move, so start the stuck-timer
		stuckTimerCh <- RESET
		return
	}
	motorDirCh <- def.STOP

	if localState.Stuck {
		// When the elevator reaches a new floor, it is no longer stuck
		localState.Stuck = false

		// Set to idle if there is no cab order
		if !localState.AcceptedOrders[floor][def.CAB] {
			localState.Behaviour = def.IDLE
			return
		}
	} else {
		// Disable stuck timer when idle
		stuckTimerCh <- STOP
	}

	// Treat cab order
	doorLightCh <- true
	localState.Behaviour = def.DOOR_OPEN
	light := def.ButtonLight{def.CAB, floor, false}
	buttonLightCh <- light

	localState = elevatorLogic.ClearOrderAtCurrentFloor(localState)

}

// Acknowledges the order and executes cab orders if the elevator is Idle
func newOrderPlaced(buttonLightCh chan<- def.ButtonLight, motorDirCh chan<- def.MotorDirection,
	button def.Button, stuckTimerCh chan<- timerOption) {
	acknowledgeOrder(button)
	if button.Type == def.CAB {
		light := def.ButtonLight{def.CAB, button.Floor, true}
		buttonLightCh <- light
		if localState.Behaviour == def.IDLE {
			executeOrder(motorDirCh, stuckTimerCh)
		}
	}
}

func executeOrder(motorDirCh chan<- def.MotorDirection, stuckTimerCh chan<- timerOption) {
	dir := elevatorLogic.ChooseDirection(localState)
	switch dir {
	case def.STOP:
		// No order; keep chilling
		localState.Behaviour = def.IDLE

	default:
		localState.Behaviour = def.MOVING
		localState.Direction = dir
		motorDirCh <- dir

		// Elevator about to move, so start the stuck-timer
		stuckTimerCh <- RESET
	}

}

// Clears all hallrequests so they can be reassigned, and sets status to stuck
func elevatorStuck() {
	localState.Stuck = true
	for floor := 0; floor < def.NUMB_FLOORS; floor++ {
		for button := def.HALL_UP; button <= def.HALL_DOWN; button++ {
			localState.AcceptedOrders[floor][button] = false
		}
	}
}

// Close door and turn off light, execute next order
func doorTimerTimedOut(motorDirCh chan<- def.MotorDirection, doorLightCh chan<- bool, stuckTimerCh chan<- timerOption) {
	if localState.Behaviour != def.DOOR_OPEN {
		// In case of errors
		return
	}
	doorLightCh <- false
	executeOrder(motorDirCh, stuckTimerCh)
}


text:
@article{sun2018training,
  title={Training simplification and model simplification for deep learning: A minimal effort back propagation method},
  author={Sun, Xu and Ren, Xuancheng and Ma, Shuming and Wei, Bingzhen and Li, Wei and Xu, Jingjing and Wang, Houfeng and Zhang, Yi},
  journal={IEEE Transactions on Knowledge and Data Engineering},
  year={2018},
  publisher={IEEE}
}

repository: jingjingxupku/academic-kickstart

repo_name: jingjingxupku/academic-kickstart


text:
include opie-securityplugin-notice.inc

PV = "${OPIE_CVS_PV}"

SRC_URI = "${HANDHELDS_CVS};module=opie/noncore/securityplugins/notice \
           ${HANDHELDS_CVS};module=opie/pics "

repository: BackupTheBerlios/openslug-svn

repo_name: BackupTheBerlios/openslug-svn


text:
package testresults

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"

	"github.com/evergreen-ci/timber"
	"github.com/mongodb/grip"
	"github.com/pkg/errors"
)

// Valid sort by keys.
const (
	SortByStart      = "start"
	SortByDuration   = "duration"
	SortByTestName   = "test_name"
	SortByStatus     = "status"
	SortByBaseStatus = "base_status"
)

// GetOptions specify the required and optional information to create the test
// results HTTP GET request to Cedar.
type GetOptions struct {
	Cedar timber.GetOptions

	// Request information. See Cedar's REST documentation for more
	// information:
	// `https://github.com/evergreen-ci/cedar/wiki/Rest-V1-Usage`.
	Tasks        []TaskOptions
	Filter       *FilterOptions
	FailedSample bool
	Stats        bool
}

// TaskOptions specify the information required to fetch test results by task.
type TaskOptions struct {
	TaskID    string `json:"task_id"`
	Execution int    `json:"execution"`
}

// SortBy describes the properties by which to sort a set of test results.
type SortBy struct {
	Key      string `json:"key"`
	OrderDSC bool   `json:"order_dsc"`
}

// FilterOptions represent the parameters for filtering, sorting, and
// paginating test results. These options are only supported on select routes.
type FilterOptions struct {
	TestName            string        `json:"test_name,omitempty"`
	ExcludeDisplayNames bool          `json:"exclude_display_names"`
	Statuses            []string      `json:"statuses,omitempty"`
	GroupID             string        `json:"group_id,omitempty"`
	Sort                []SortBy      `json:"sort"`
	Limit               int           `json:"limit,omitempty"`
	Page                int           `json:"page,omitempty"`
	BaseTasks           []TaskOptions `json:"base_tasks,omitempty"`
}

type requestPayload struct {
	Tasks  []TaskOptions  `json:"tasks"`
	Filter *FilterOptions `json:"filter,omitempty"`
}

// Validate ensures TestResultsGetOptions is configured correctly.
func (opts GetOptions) Validate() error {
	catcher := grip.NewBasicCatcher()

	catcher.Add(opts.Cedar.Validate())
	catcher.NewWhen(len(opts.Tasks) == 0, "must specify at least one task")
	catcher.NewWhen(opts.FailedSample && opts.Stats, "cannot request the failed sample and stats, must be one or the other")
	catcher.NewWhen((opts.FailedSample || opts.Stats) && opts.Filter != nil, "cannot specify filter options on the failed_sample and stats routes")

	return catcher.Resolve()
}

func (opts GetOptions) serialize() (string, []byte, error) {
	urlString := fmt.Sprintf("%s/rest/v1/test_results/tasks", opts.Cedar.BaseURL)
	if opts.FailedSample {
		urlString += "/failed_sample"
	}
	if opts.Stats {
		urlString += "/stats"
	}

	payload := struct {
		Tasks  []TaskOptions  `json:"tasks"`
		Filter *FilterOptions `json:"filter,omitempty"`
	}{
		Tasks:  opts.Tasks,
		Filter: opts.Filter,
	}
	data, err := json.Marshal(&payload)
	if err != nil {
		return "", nil, errors.Wrap(err, "marshalling JSON request payload")
	}

	return urlString, data, nil
}

// Get returns the test results requested via HTTP to a Cedar service along
// with the status code of the request.
func Get(ctx context.Context, opts GetOptions) ([]byte, int, error) {
	if err := opts.Validate(); err != nil {
		return nil, 0, errors.WithStack(err)
	}

	url, payload, err := opts.serialize()
	if err != nil {
		return nil, 0, errors.Wrap(err, "serializing request options")
	}

	resp, err := opts.Cedar.DoReq(ctx, url, bytes.NewReader(payload))
	if err != nil {
		return nil, 0, errors.Wrap(err, "requesting test results from cedar")
	}

	catcher := grip.NewBasicCatcher()
	data, err := io.ReadAll(resp.Body)
	catcher.Wrap(err, "reading response body")
	catcher.Wrap(resp.Body.Close(), "closing response body")

	return data, resp.StatusCode, catcher.Resolve()
}

repository: evergreen-ci/timber

repo_name: evergreen-ci/timber


text:
// This source file is part of the Packet Guardian project.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package api

import (
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/julienschmidt/httprouter"
	"github.com/lfkeitel/verbose"
	"github.com/usi-lfkeitel/packet-guardian/src/common"
	"github.com/usi-lfkeitel/packet-guardian/src/models"
)

type UserController struct {
	e *common.Environment
}

func NewUserController(e *common.Environment) *UserController {
	return &UserController{e: e}
}

func (u *UserController) UserHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	if r.Method == "POST" {
		u.saveUserHandler(w, r)
	} else if r.Method == "DELETE" {
		u.deleteUserHandler(w, r)
	}
}

func (u *UserController) saveUserHandler(w http.ResponseWriter, r *http.Request) {
	sessionUser := models.GetUserFromContext(r)
	username := strings.ToLower(r.FormValue("username"))
	if username == "" {
		common.NewAPIResponse("Username required", nil).WriteResponse(w, http.StatusBadRequest)
		return
	}

	user, err := models.GetUserByUsername(u.e, username)
	if err != nil {
		u.e.Log.WithFields(verbose.Fields{
			"error":    err,
			"package":  "controllers:api:user",
			"username": username,
		}).Error("Error getting user")
		common.NewAPIResponse("Error saving user", nil).WriteResponse(w, http.StatusInternalServerError)
		return
	}
	defer user.Release()

	canCreate := sessionUser.Can(models.CreateUser)
	canEdit := sessionUser.Can(models.EditUser)
	if !(user.IsNew() && canCreate) && !(!user.IsNew() && canEdit) {
		common.NewAPIResponse("Permission denied", nil).WriteResponse(w, http.StatusForbidden)
		return
	}

	// Password
	password := r.FormValue("password")
	if password != "" {
		if password == "-1" {
			user.RemovePassword()
		} else {
			user.NewPassword(password)
		}
	}

	// Device limit
	limitStr := r.FormValue("device_limit")
	if limitStr != "" {
		limit, err := strconv.Atoi(limitStr)
		if err != nil {
			common.NewAPIResponse("device_limit must be a number", nil).WriteResponse(w, http.StatusBadRequest)
			return
		}
		user.DeviceLimit = models.UserDeviceLimit(limit)
	}

	// Default device expiration
	expTypeStr := r.FormValue("expiration_type")
	devExpiration := r.FormValue("device_expiration")
	updateDeviceExpirations := false
	if expTypeStr != "" || devExpiration != "" {
		if expTypeStr == "" && devExpiration != "" {
			common.NewAPIResponse("Error saving user: Expiration type not given", nil).WriteResponse(w, http.StatusBadRequest)
			return
		}

		expType, err := strconv.Atoi(expTypeStr)
		if err != nil {
			common.NewAPIResponse("Expiration type must be an integer", nil).WriteResponse(w, http.StatusBadRequest)
			return
		}
		if user.DeviceExpiration.Mode != models.UserExpiration(expType) {
			user.DeviceExpiration.Mode = models.UserExpiration(expType)
			updateDeviceExpirations = true
		}
		if user.DeviceExpiration.Mode == models.UserDeviceExpirationGlobal ||
			user.DeviceExpiration.Mode == models.UserDeviceExpirationNever ||
			user.DeviceExpiration.Mode == models.UserDeviceExpirationRolling {
			user.DeviceExpiration.Value = 0
		} else if user.DeviceExpiration.Mode == models.UserDeviceExpirationSpecific {
			t, err := time.ParseInLocation(common.TimeFormat, devExpiration, time.Local)
			if err != nil {
				common.NewAPIResponse("Invalid time format", nil).WriteResponse(w, http.StatusBadRequest)
				return
			}
			if user.DeviceExpiration.Value != t.Unix() {
				user.DeviceExpiration.Value = t.Unix()
				updateDeviceExpirations = true
			}
		} else if user.DeviceExpiration.Mode == models.UserDeviceExpirationDaily {
			secs, err := common.ParseTime(devExpiration)
			if err != nil {
				common.NewAPIResponse("Invalid time format", nil).WriteResponse(w, http.StatusBadRequest)
				return
			}
			if user.DeviceExpiration.Value != secs {
				user.DeviceExpiration.Value = secs
				updateDeviceExpirations = true
			}
		} else if user.DeviceExpiration.Mode == models.UserDeviceExpirationDuration {
			d, err := time.ParseDuration(devExpiration)
			if err != nil {
				common.NewAPIResponse("Invalid duration", nil).WriteResponse(w, http.StatusBadRequest)
				return
			}
			// time.Duration's Second() returns a float that contains the nanoseconds as well
			// For sanity we don't care and don't want the nanoseconds
			dur := int64(d / time.Second)
			if user.DeviceExpiration.Value != dur {
				user.DeviceExpiration.Value = dur
				updateDeviceExpirations = true
			}
		} else {
			common.NewAPIResponse("Invalid device expiration type", nil).WriteResponse(w, http.StatusBadRequest)
			return
		}
	}

	// Valid dates
	validStart := r.FormValue("valid_start")
	validEnd := r.FormValue("valid_end")
	if validStart == "0" && validEnd == "0" {
		user.ValidForever = true
		user.ValidStart = time.Unix(0, 0)
		user.ValidEnd = user.ValidStart
	} else {
		user.ValidForever = false
		if validStart != "" {
			t, err := time.ParseInLocation(common.TimeFormat, validStart, time.Local)
			if err != nil {
				common.NewAPIResponse("Invalid time format: valid_start", nil).WriteResponse(w, http.StatusBadRequest)
				return
			}
			user.ValidStart = t
		}
		if validEnd != "" {
			t, err := time.ParseInLocation(common.TimeFormat, validEnd, time.Local)
			if err != nil {
				common.NewAPIResponse("Invalid time format: valid_end", nil).WriteResponse(w, http.StatusBadRequest)
				return
			}
			user.ValidEnd = t
		}
		if user.ValidEnd.Before(user.ValidStart) {
			common.NewAPIResponse("valid_start must be before valid_end", nil).WriteResponse(w, http.StatusBadRequest)
			return
		}
	}

	canManage := r.FormValue("can_manage")
	if canManage != "" {
		user.CanManage = (canManage == "1")
	}

	canAutoreg := r.FormValue("can_autoreg")
	if canAutoreg != "" {
		user.CanAutoreg = (canAutoreg == "1")
	}

	isNewUser := user.IsNew() // This will always be false after a call to Save()

	if err := user.Save(); err != nil {
		u.e.Log.WithFields(verbose.Fields{
			"error":   err,
			"package": "controllers:api:user",
		}).Error("Error saving user")
		common.NewAPIResponse("Error saving user", nil).WriteResponse(w, http.StatusInternalServerError)
		return
	}

	if isNewUser {
		u.e.Log.WithFields(verbose.Fields{
			"package":    "controllers:api:user",
			"action":     "create-user",
			"username":   user.Username,
			"changed-by": sessionUser.Username,
		}).Info("User created")
	} else {
		u.e.Log.WithFields(verbose.Fields{
			"package":    "controllers:api:user",
			"action":     "edit-user",
			"username":   user.Username,
			"changed-by": sessionUser.Username,
		}).Info("User edited")
	}

	if updateDeviceExpirations {
		devices, err := models.GetDevicesForUser(u.e, user)
		if err != nil {
			u.e.Log.WithFields(verbose.Fields{
				"error":   err,
				"package": "controllers:api:user",
			}).Error("Error getting devices")
			common.NewAPIResponse("User saved, but devices not updated", nil).WriteResponse(w, http.StatusInternalServerError)
			return
		}
		errOccured := false
		for _, d := range devices {
			d.Expires = user.DeviceExpiration.NextExpiration(u.e, d.DateRegistered)
			if err := d.Save(); err != nil {
				u.e.Log.WithFields(verbose.Fields{
					"error":   err,
					"package": "controllers:api:user",
					"mac":     d.MAC.String(),
				}).Error("Error saving device")
				errOccured = true
			}
		}
		if errOccured {
			common.NewAPIResponse("User saved, but some devices not updated", nil).WriteResponse(w, http.StatusInternalServerError)
			return
		}
	}

	if isNewUser {
		common.NewAPIResponse("User created successfully", nil).WriteResponse(w, http.StatusNoContent)
		return
	}
	common.NewAPIResponse("User saved successfully", nil).WriteResponse(w, http.StatusNoContent)
}

func (u *UserController) deleteUserHandler(w http.ResponseWriter, r *http.Request) {
	sessionUser := models.GetUserFromContext(r)
	if !sessionUser.Can(models.DeleteUser) {
		common.NewAPIResponse("Permission denied", nil).WriteResponse(w, http.StatusForbidden)
		return
	}

	username := r.FormValue("username")
	if username == "" {
		common.NewAPIResponse("Username required", nil).WriteResponse(w, http.StatusBadRequest)
		return
	}

	user, err := models.GetUserByUsername(u.e, username)
	if err != nil {
		u.e.Log.WithFields(verbose.Fields{
			"error":    err,
			"package":  "controllers:api:user",
			"username": username,
		}).Error("Error getting user")
		common.NewAPIResponse("Error deleting user", nil).WriteResponse(w, http.StatusInternalServerError)
		return
	}
	defer user.Release()

	if err := user.Delete(); err != nil {
		u.e.Log.WithFields(verbose.Fields{
			"error":   err,
			"package": "controllers:api:user",
		}).Error("Error deleting user")
		common.NewAPIResponse("Error deleting user", nil).WriteResponse(w, http.StatusInternalServerError)
		return
	}

	u.e.Log.WithFields(verbose.Fields{
		"package":    "controllers:api:user",
		"action":     "delete-user",
		"username":   user.Username,
		"changed-by": sessionUser.Username,
	}).Info("User deleted")
	common.NewAPIResponse("User deleted", nil).WriteResponse(w, http.StatusNoContent)
}

repository: BukhariH/packet-guardian

repo_name: BukhariH/packet-guardian


text:
require ${BPN}.inc

SRC_URI[md5sum] = "84381ba535e6d496029a750d2d51c1fb"
SRC_URI[sha256sum] = "6a89dd15e8b054d634f90a827b116cd8be9046423c0874d2ae3ed010c014cc69"

repository: paultcn/meta-aosp-hybris

repo_name: paultcn/meta-aosp-hybris


text:
@inproceedings{mayerl:btw:2023,
 author = {Maximilian Mayerl and
Michael Vötter and
Günther Specht and
Eva Zangerle},
 booktitle = {Datenbanksysteme für Business, Technologie und Web (BTW
2023), 20. Fachtagung des GI-Fachbereichs Datenbanken und Informationssysteme
(DBIS), Proceedings},
 doi = {10.18420/BTW2023-26},
 pages = {555--565},
 publisher = {Gesellschaft für Informatik e.V.},
 series = {LNI},
 title = {Pairwise Learning to Rank for Hit Song Prediction},
 volume = {P-331},
 year = {2023}
}


text:
require firmware.inc
require firmisrar.inc

ARM_INSTRUCTION_SET = "arm"

PR = "r0"

DL_URI = "http://downloadcenter.samsung.com/content/FM/200910/20091030222436890/${MACHINE}.exe"

# S = "${WORKDIR}
# fix offset !!!!! * Arris * btw. rc.local has to be full rewritten
# P_OFFSET = ""
# P_LINE = ";/mtd_rwarea/rcSGO     &"
require firmware-package.bbclass

repository: metalsky/SamyGO

repo_name: metalsky/SamyGO


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

package v2

import (
	"fmt"
	"strconv"
	"time"

	"github.com/google/uuid"
)

type CreateStory struct {
	Name                string                  `json:"name"`
	ProjectId           int64                   `json:"project_id"`
	Comments            []CreateCommentParams   `json:"comments,omitempty"`
	CompletedAtOverride *time.Time              `json:"completed_at_override,omitempty"`
	Deadline            *time.Time              `json:"deadline,omitempty"`
	Description         string                  `json:"description,omitempty"`
	EpicId              int64                   `json:"epic_id,omitempty"`
	Estimate            int64                   `json:"estimate,omitempty"`
	ExternalId          string                  `json:"external_id,omitempty"`
	FileIds             []int64                 `json:"file_ids,omitempty"`
	FollowerIds         []uuid.UUID             `json:"follower_ids,omitempty"`
	Labels              []CreateLabelParams     `json:"labels,omitempty"`
	LinkedFileIds       []int64                 `json:"linked_file_ids,omitempty"`
	OwnerIds            []uuid.UUID             `json:"owner_ids,omitempty"`
	RequestedById       *uuid.UUID              `json:"requested_by_id,omitempty"`
	StartedAtOverride   *time.Time              `json:"started_at_override,omitempty"`
	StoryLinks          []CreateStoryLinkParams `json:"story_links,omitempty"`
	StoryType           StoryType               `json:"story_type,omitempty"`
	Tasks               []CreateTaskParams      `json:"tasks,omitempty"`
	UpdatedAt           *time.Time              `json:"updated_at,omitempty"`
	WorkflowStateId     int64                   `json:"workflow_state_id,omitempty"`
}

type CreateCommentParams struct {
	AuthorId   string    `json:"author_id,omitempty"`
	CreatedAt  time.Time `json:"created_at,omitempty"`
	ExternalId string    `json:"external_id,omitempty"`
	Text       string    `json:"text,omitempty"`
	UpdatedAt  time.Time `json:"updated_at,omitempty"`
}

type CreateLabelParams struct {
	Color      string `json:"color,omitempty"`
	ExternalId string `json:"external_id,omitempty"`
	Name       string `json:"name,omitempty"`
}

type CreateStoryLinkParams struct {
	ObjectId  int64 `json:"object_id,omitempty"`
	SubjectId int64 `json:"subject_id,omitempty"`
	Verb      Verb  `json:"verb,omitempty"`
}

type CreateTaskParams struct {
	Complete    bool        `json:"complete,omitempty"`
	CreatedAt   time.Time   `json:"created_at,omitempty"`
	Description string      `json:"description,omitempty"`
	ExternalId  string      `json:"external_id,omitempty"`
	OwnerIds    []uuid.UUID `json:"owner_ids,omitempty"`
	UpdatedAt   time.Time   `json:"updated_at,omitempty"`
}

type StoryType string

const (
	StoryTypeBug     = StoryType("bug")
	StoryTypeFeature = StoryType("feature")
	StoryTypeChore   = StoryType("chore")
)

type Verb string

const (
	VerbBlocks     = Verb("blocks")
	VerbDuplicates = Verb("duplicates")
	VerbRelatesTo  = Verb("relates to")
)

// https://clubhouse.io/api/rest/v2/#Story
type Story struct {
	AppUrl   string   `json:"app_url"`
	Archived bool     `json:"archived"`
	Blocked  bool     `json:"blocked"`
	Blocker  bool     `json:"blocker"`
	Branches []Branch `json:"branches"`
	// TODO: Add remaining fields
}

// https://clubhouse.io/api/rest/v2/#Branch
type Branch struct {
	CreatedAt       time.Time     `json:"created_at"`
	Deleted         bool          `json:"deleted"`
	EntityType      string        `json:"entity_type"`
	Id              *int64        `json:"id"`
	MergedBranchIds []int64       `json:"merged_branch_ids"`
	Name            string        `json:"name"`
	Persistent      bool          `json:"persistent"`
	PullRequests    []PullRequest `json:"pull_requests"`
	RepositoryId    *int64        `json:"repository_id"`
	UpdatedAt       time.Time     `json:"updated_at"`
	Url             string        `json:"url"`
}

// https://clubhouse.io/api/rest/v2/#PullRequest
type PullRequest struct {
	BranchId       *int64    `json:"branch_id"`
	Closed         bool      `json:"closed"`
	CreatedAt      time.Time `json:"created_at"`
	EntityType     string    `json:"entity_type"`
	Id             *int64    `json:"id"`
	NumAdded       int64     `json:"num_added"`
	NumCommits     int64     `json:"num_commits"`
	NumModified    int64     `json:"num_modified"`
	NumRemoved     int64     `json:"num_removed"`
	Number         int64     `json:"number"`
	TargetBranchId int64     `json:"target_branch_id"`
	Title          string    `json:"title"`
	UpdatedAt      time.Time `json:"updated_at"`
	Url            string    `json:"url"`
}

// https://clubhouse.io/api/rest/v2/#StorySlim
type StorySlim struct {
	AppUrl   string `json:"app_url"`
	Archived bool   `json:"archived"`
	Blocked  bool   `json:"blocked"`
	Blocker  bool   `json:"blocker"`
	Id       int64  `json:"id"`
	Name     string `json:"name"`
	// TODO: Add remaining fields
}

func (c *Client) Stories() *Stories {
	return &Stories{c: c}
}

type Stories struct {
	c *Client
}

func (s *Stories) Create(story *CreateStory) (*Story, error) {
	res := &Story{}
	err := s.c.post("stories", story, res)
	if err != nil {
		return nil, fmt.Errorf("error creating story: %s", err.Error())
	}
	return res, nil
}

func (s *Stories) List(projectId int64) ([]*StorySlim, error) {
	var res []*StorySlim
	err := s.c.get("projects/"+strconv.FormatInt(projectId, 10)+"/stories", nil, &res)
	if err != nil {
		return nil, fmt.Errorf("error listing stories: %s", err.Error())
	}
	return res, nil
}

repository: taisph/ch

repo_name: taisph/ch


text:
// Copyright (c) 2016 Bob Ziuchkovski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package hosted

import (
	"fmt"
	"reflect"
	"testing"

	"github.com/remerge/cue"
	"github.com/remerge/cue/internal/cuetest"
)

const opbeatJSON = `
{
  "culprit": "github.com/remerge/cue/frame3.function3",
  "exception": {
    "module": "github.com/remerge/cue/frame3",
    "type": "errors.errorString",
    "value": "error message"
  },
  "extra": {
    "extra": "extra value",
    "k1": "some value",
    "k2": 2,
    "k3": 3.5,
    "k4": true
  },
  "level": "error",
  "logger": "test context",
  "machine": {
    "hostname": "pegasus.bobbyz.org"
  },
  "message": "error event: error message",
  "stacktrace": {
    "frames": [
      {
        "filename": "/path/github.com/remerge/cue/frame1/file1.go",
        "function": "github.com/remerge/cue/frame1.function1",
        "lineno": 1
      },
      {
        "filename": "/path/github.com/remerge/cue/frame2/file2.go",
        "function": "github.com/remerge/cue/frame2.function2",
        "lineno": 2
      },
      {
        "filename": "/path/github.com/remerge/cue/frame3/file3.go",
        "function": "github.com/remerge/cue/frame3.function3",
        "lineno": 3
      }
    ]
  },
  "timestamp": "2006-01-02T22:04:00.000Z"
}
`

const opbeatNoFramesJSON = `
{
  "exception": {
    "type": "errors.errorString",
    "value": "error message"
  },
  "extra": {
    "extra": "extra value",
    "k1": "some value",
    "k2": 2,
    "k3": 3.5,
    "k4": true
  },
  "level": "error",
  "logger": "test context",
  "machine": {
    "hostname": "pegasus.bobbyz.org"
  },
  "message": "error event: error message",
  "timestamp": "2006-01-02T22:04:00.000Z"
}
`

func TestOpbeatNilCollector(t *testing.T) {
	c := Opbeat{}.New()
	if c != nil {
		t.Errorf("Expected a nil collector when the token is missing, but got %s instead", c)
	}
}

func TestOpbeat(t *testing.T) {
	checkOpbeatEvent(t, cuetest.ErrorEvent, opbeatJSON)
}

func TestOpbeatNoFrames(t *testing.T) {
	checkOpbeatEvent(t, cuetest.ErrorEventNoFrames, opbeatNoFramesJSON)
}

func TestOpbeatString(t *testing.T) {
	_ = fmt.Sprint(getOpbeatCollector())
}

func TestOpbeatLevels(t *testing.T) {
	m := map[cue.Level]string{
		cue.DEBUG: "debug",
		cue.INFO:  "info",
		cue.WARN:  "warning",
		cue.ERROR: "error",
		cue.FATAL: "fatal",
	}
	for k, v := range m {
		if opbeatLevel(k) != v {
			t.Errorf("Expected cue level %q to map to opbeat level %q but it didn't", k, v)
		}
	}
}

func checkOpbeatEvent(t *testing.T, event *cue.Event, expected string) {
	req, err := getOpbeatCollector().formatRequest(event)
	if err != nil {
		t.Errorf("Encountered unexpected error formatting http request: %s", err)
	}
	requestJSON := cuetest.ParseRequestJSON(req)
	expectedJSON := cuetest.ParseStringJSON(expected)

	if cuetest.NestedFetch(requestJSON, "machine", "hostname") == "!(MISSING)" {
		t.Error("Hostname is missing from request")
	}
	if cuetest.NestedFetch(requestJSON, "timestamp") == "!(MISSING)" {
		t.Error("Timestamp is missing from request")
	}

	cuetest.NestedDelete(requestJSON, "machine", "hostname")
	cuetest.NestedDelete(expectedJSON, "machine", "hostname")
	cuetest.NestedDelete(requestJSON, "timestamp")
	cuetest.NestedDelete(expectedJSON, "timestamp")
	cuetest.NestedCompare(t, requestJSON, expectedJSON)
}

func getOpbeatCollector() *opbeatCollector {
	c := Opbeat{
		Token:          "test",
		AppID:          "app",
		OrganizationID: "org",
		ExtraContext:   cue.NewContext("extra").WithValue("extra", "extra value"),
	}.New()
	oc, ok := c.(*opbeatCollector)
	if !ok {
		panic(fmt.Sprintf("Expected to see a *opbeatCollector but got %s instead", reflect.TypeOf(c)))
	}
	return oc
}

repository: remerge/cue

repo_name: remerge/cue


text:
// Copyright 2017 Granitic. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project.

package invoker

import (
	"github.com/vlorc/gioc/types"
	"reflect"
)

func (wi *WithInvoker) Apply(args ...interface{}) ([]reflect.Value, error) {
	return wi.invoker.ApplyWith(wi.provider(), args...)
}

func (wi *WithInvoker) ApplyWith(_ types.Provider, args ...interface{}) ([]reflect.Value, error) {
	return wi.Apply(args...)
}

repository: vlorc/gioc

repo_name: vlorc/gioc


text:
package utils

import "net"

func LookupIP() string {
	addrs, err := net.InterfaceAddrs()

	if err != nil {
		return ""
	}

	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			ip := ipnet.IP.To4()
			if ip != nil {
				return ip.String()
			}
		}
	}
	return ""
}

func Hashing() int64 {
	ip := LookupIP()
	if ip == "" {
		return 0
	}
	return 0
}

repository: niwho/utils

repo_name: niwho/utils