text:
package deck

import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestSmallDeckToString(t *testing.T) {
	deck, _ := New(Empty)
	deck.Cards = append(deck.Cards, NewCard(ACE, HEART), NewCard(KING, HEART))
	result := fmt.Sprintf("%s", deck)
	assert.Equal(t, "A♥\nK♥\n", result, "These should be equal")
}

func TestDeckToString(t *testing.T) {
	deck, _ := New(Unshuffled)
	result := fmt.Sprintf("%s", deck)
	assert.Equal(t, "A♣\n2♣\n3♣\n4♣\n5♣\n6♣\n7♣\n8♣\n9♣\nT♣\nJ♣\nQ♣\nK♣\n"+
		"A♦\n2♦\n3♦\n4♦\n5♦\n6♦\n7♦\n8♦\n9♦\nT♦\nJ♦\nQ♦\nK♦\n"+
		"A♥\n2♥\n3♥\n4♥\n5♥\n6♥\n7♥\n8♥\n9♥\nT♥\nJ♥\nQ♥\nK♥\n"+
		"A♠\n2♠\n3♠\n4♠\n5♠\n6♠\n7♠\n8♠\n9♠\nT♠\nJ♠\nQ♠\nK♠\n", result, "These should be equal")
}

func TestDeckFromSignature(t *testing.T) {
	deck, _ := New(FromSignature("02c290"), Unshuffled)
	result := fmt.Sprintf("%s", deck)
	assert.Equal(t, "A♥\nK♥\nT♣\n", result, "These should be equal")
}

func TestDeckSignature(t *testing.T) {
	deck, _ := New(Empty)
	deck.Cards = append(deck.Cards, NewCard(ACE, HEART), NewCard(KING, HEART), NewCard(TEN, CLUB))
	result := deck.GetSignature()
	assert.Equal(t, "02c290", result, "These should be equal")
}

func TestCompleteDeckSignature(t *testing.T) {
	deck, _ := New(Unshuffled)
	result := deck.GetSignature()
	assert.Equal(t, "00102030405060708090a0b0c001112131415161718191a1b1c102122232425262728292a2b2c203132333435363738393a3b3c3", result, "These should be equal")
}

func TestNewTinyDeck(t *testing.T) {
	deck, _ := New(Unshuffled, Suits(SPADE))
	assert.Equal(t, 13, deck.NumberOfCards())
}

func TestNewSmallDeck(t *testing.T) {
	deck, _ := New(Unshuffled, Suits(SPADE, HEART))
	assert.Equal(t, 26, deck.NumberOfCards())
}

func TestDeal(t *testing.T) {
	deck, _ := New(Unshuffled, Suits(SPADE), Faces(FACES...))
	assert.Equal(t, deck.NumberOfCards(), 13)
	hand1, _ := New(Empty)
	hand2, _ := New(Empty)
	deck.Deal(5, hand1, hand2)
	assert.Equal(t, deck.NumberOfCards(), 3)
	assert.Equal(t, hand1.NumberOfCards(), 5)
	assert.Equal(t, hand2.NumberOfCards(), 5)
	assert.Equal(t, hand1.String(), "A♠\n3♠\n5♠\n7♠\n9♠\n")
	assert.Equal(t, hand2.String(), "2♠\n4♠\n6♠\n8♠\nT♠\n")
}

func TestShuffle(t *testing.T) {
	expected, _ := New(Unshuffled)
	deck, _ := New(Unshuffled)
	deck.Shuffle()
	assert.NotEqual(t, expected.GetSignature(), deck.GetSignature())
}

func TestShufflePerm(t *testing.T) {
	expected, _ := New(Unshuffled)
	deck, _ := New(Unshuffled)
	deck.ShufflePerm()
	assert.NotEqual(t, expected.GetSignature(), deck.GetSignature())
}

func TestWithCards(t *testing.T) {
	cards := []Card{
		NewCard(ACE, HEART),
		NewCard(ACE, SPADE),
		NewCard(ACE, DIAMOND),
		NewCard(ACE, CLUB),
	}
	deck, _ := New(WithCards(cards...), Unshuffled)
	assert.Equal(t, deck.NumberOfCards(), 4)
	assert.Equal(t, deck.Cards[0].String(), "A♥")
	assert.Equal(t, deck.Cards[1].String(), "A♠")
	assert.Equal(t, deck.Cards[2].String(), "A♦")
	assert.Equal(t, deck.Cards[3].String(), "A♣")
}

func BenchmarkTinyDeckShuffle(b *testing.B) {
	b.ReportAllocs()
	for n := 0; n < b.N; n++ {
		deck, _ := New(Unshuffled, Suits(SPADE))
		deck.Shuffle()
	}
}

func BenchmarkSmallDeckShuffle(b *testing.B) {
	b.ReportAllocs()
	for n := 0; n < b.N; n++ {
		deck, _ := New(Unshuffled, Faces(FACES...), Suits(SPADE, HEART))
		deck.Shuffle()
	}
}

func BenchmarkMediumDeckShuffle(b *testing.B) {
	b.ReportAllocs()
	for n := 0; n < b.N; n++ {
		deck, _ := New(Unshuffled, Faces(FACES...), Suits(SPADE, HEART, DIAMOND))
		deck.Shuffle()
	}
}

func BenchmarkDeckShuffle(b *testing.B) {
	b.ReportAllocs()
	for n := 0; n < b.N; n++ {
		deck, _ := New(Unshuffled, Faces(FACES...), Suits(SUITS...))
		deck.Shuffle()
	}
}
func BenchmarkLargeDeckShuffle(b *testing.B) {
	b.ReportAllocs()
	for n := 0; n < b.N; n++ {
		deck, _ := New(Unshuffled, Decks(10), Faces(FACES...), Suits(SUITS...))
		deck.Shuffle()
	}
}

// func BenchmarkLargeDeckShuffleAlt(b *testing.B) {
// 	b.ReportAllocs()
// 	deck, _ := New(Unshuffled, Decks(10), Faces(FACES...), Suits(SUITS...))
// 	for n := 0; n < b.N; n++ {
// 		deck.ShufflePerm()
// 	}
// }

func TestShoeToString(t *testing.T) {

	shoe, _ := New(Unshuffled, Decks(1))
	result := fmt.Sprintf("%s", shoe)
	assert.Equal(t, "A♣\n2♣\n3♣\n4♣\n5♣\n6♣\n7♣\n8♣\n9♣\nT♣\nJ♣\nQ♣\nK♣\nA♦\n2♦\n3♦\n4♦\n5♦\n6♦\n7♦\n8♦\n9♦\nT♦\nJ♦\nQ♦\nK♦\nA♥\n2♥\n3♥\n4♥\n5♥\n6♥\n7♥\n8♥\n9♥\nT♥\nJ♥\nQ♥\nK♥\nA♠\n2♠\n3♠\n4♠\n5♠\n6♠\n7♠\n8♠\n9♠\nT♠\nJ♠\nQ♠\nK♠\n", result, "These should be equal")
}

func TestNewSpecificShoe(t *testing.T) {
	shoe, _ := New(Unshuffled, Decks(2), Faces(ACE), Suits(HEART))
	result := fmt.Sprintf("%s", shoe)
	assert.Equal(t, "A♥\nA♥\n", result, "These should be equal")
}

func TestEmptyShoe(t *testing.T) {
	shoe, _ := New(Decks(0))
	result := shoe.NumberOfDecks
	assert.Equal(t, 0, result, "These should be equal")
}

repository: adamclerk/deck

repo_name: adamclerk/deck


text:
@article{doi:10.1002/open.201800275,
author = {Symons, Benjamin C. B. and Williamson, Dominic J. and Brooks, Campbell M. and Wilson, Alex L. and Popelier, Paul L. A.},
title = {Does the Intra-Atomic Deformation Energy of Interacting Quantum Atoms Represent Steric Energy?},
journal = {ChemistryOpen},
volume = {8},
number = {5},
pages = {560-570},
keywords = {quantum chemical topology (QCT), steric effects, van der Waals complexes, interacting quantum atoms (IQA), short-range repulsion potential},
doi = {10.1002/open.201800275},
url = {https://onlinelibrary.wiley.com/doi/abs/10.1002/open.201800275},
eprint = {https://onlinelibrary.wiley.com/doi/pdf/10.1002/open.201800275},
abstract = {Abstract We show that the mutual, through-space compression of atomic volume experienced by approaching topological atoms causes an exponential increase in the intra-atomic energy of those atoms, regardless of approach orientation. This insight was obtained using the modern energy partitioning method called interacting quantum atoms (IQA). This behaviour is consistent for all atoms except hydrogen, which can behave differently depending on its environment. Whilst all atoms experience charge transfer when they interact, the intra-atomic energy of the hydrogen atom is more vulnerable to these changes than larger atoms. The difference in behaviour is found to be due to hydrogen's lack of a core of electrons, which, in heavier atoms, consistently provide repulsion when compressed. As such, hydrogen atoms do not always provide steric hindrance. In accounting for hydrogen's unusual behaviour and demonstrating the exponential character of the intra-atomic energy in all other atoms, we provide evidence for IQA's intra-atomic energy as a quantitative description of steric energy.},
year = {2019}
}

license: MIT

license_type: permissive

branch_name: refs/heads/master

extension: bib


text:
@inproceedings{nikkarinen+al.acl-findings21,
  title = {Modeling the Unigram Distribution},
  venue = {Findings of ACL},
  year = {2021},
  slides = {https://drive.google.com/file/d/1o4UC9daJou2p95uNUkomEx2aCKMmSPxO/view?usp=sharing},
  video = {https://www.youtube.com/watch?v=xhzWoWyytvg},
  code = {https://github.com/irenenikk/modelling-unigram},
  arXiv = {https://arxiv.org/abs/2106.02289},
  author = {Nikkarinen$^*$, Irene and
	Pimentel$^*$, Tiago and
	Blasi, Dami{\'a}n and
	Cotterell, Ryan},
  booktitle = {Findings of the Association for Computational Linguistics: ACL-IJCNLP 2021},
  month = {August},
  publisher = {Association for Computational Linguistics},
  pages = {3721--3729},
  abstract = {The unigram distribution is the non-contextual probability of finding a specific word form in a corpus. While of central importance to the study of language, it is commonly approximated by each word's sample frequency in the corpus. This approach, being highly dependent on sample size, assigns zero probability to any out-of-vocabulary (oov) word form. As a result, it produces negatively biased probabilities for any oov word form, while positively biased probabilities to in-corpus words. In this work, we argue in favor of properly modeling the unigram distribution -- claiming it should be a central task in natural language processing. With this in mind, we present a novel model for estimating it in a language (a neuralization of Goldwater et al.'s (2011) model) and show it produces much better estimates across a diverse set of 7 languages than the naïve use of neural character-level language models.},
  url = {https://arxiv.org/abs/2106.02289},
}

repository: rycolab/website

repo_name: rycolab/website


text:
package form

//ReleaseTemplate is the go html/template used to render the form.
//Can publish HTML, though current workflow is to send the rendered HTML payload
//  to the athenapdf microservice for signing/distribution.
const ReleaseTemplate string = `<form class="form-horizontal">
<fieldset>

<legend>PDS SOFTWARE RELEASE FORM</legend>

  Release Date:

      <input id="prependedtext" name="prependedtext" class="form-control" placeholder="{{ .Date }}" type="text">

  Product:

      <input id="prependedtext" name="prependedtext" class="form-control" placeholder="{{ .Product }}" type="text">

Included Changes:

    {{ range $key, $value := .Changes }}

Change Item {{ inc $key }}: {{ $value.Title }}

PR:[{{ $value.ID }}] Commit:[{{ $value.CommitSHA }}]

Written By:

{{ $value.Developer }}

Summary of changes:

Description of Issue:

{{ $value.SummaryOfChangesNeeded }}

Description of Solution:

{{ $value.SummaryOfChangesImplemented }}

    {{ if $value.IssueID }}
    Issue ID:{{ $value.IssueID }}
    {{ end }}
    {{ if $value.ApprovedBy }}
    Approved by: {{ $value.ApprovedBy }}
    {{ end }}

  {{ end }}

  Back-Out Procedure:

      <input id="prependedtext" name="prependedtext" class="form-control" placeholder="{{ .BackOutProc }}" type="text">

  Impacts PCI Compliance:

      <input id="prependedtext" name="prependedtext" class="form-control" placeholder="{{ .PCIImpact }}" type="text">

  OWASP Impact:

      <input id="prependedtext" name="prependedtext" class="form-control" placeholder="{{ .OWASPImpact }}" type="text">

</fieldset>
</form>
`

repository: shonore/releaseforms

repo_name: shonore/releaseforms

extension: go


text:
@InProceedings{gaillard14,
  author = {Gaillard, Pierre and Stoltz, Gilles and {van Erven}, Tim},
  title = {A second-order bound with excess losses},
  pages = {176-196},
  abstract = {We study online aggregation of the predictions of experts, and first show new second-order regret bounds in the standard setting, which are obtained via a version of the Prod algorithm (and also a version of the polynomially weighted average algorithm) with multiple learning rates. These bounds are in terms of excess losses, the differences between the instantaneous losses suffered by the algorithm and the ones of a given expert. We then demonstrate the interest of these bounds in the context of experts that report their confidences as a number in the interval $[0,1]$ using a generic reduction to the standard setting. We conclude by two other applications in the standard setting, which improve the known bounds in case of small excess losses and show a bounded regret against i.i.d.\ sequences of losses.},
}

repository: mreid/papersite

repo_name: mreid/papersite

gha_license_id: MIT

gha_language: TeX


text:
package quiz

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"strconv"
	"time"

	"github.com/jba/chinese/study"
	"golang.org/x/net/context"
	"google.golang.org/appengine"
	"google.golang.org/appengine/datastore"
)

func init() {
	http.HandleFunc("/", handler)
	rand.Seed(time.Now().UnixNano())
}

func handler(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	switch r.URL.Path {
	case "/flashcards":
		handleStudy(appengine.NewContext(r), w, "flashcards", q.Get("n"), q.Get("corpus"))
	case "/quiz":
		handleStudy(appengine.NewContext(r), w, "quiz", q.Get("n"), q.Get("corpus"))
	case "/upload/items":
		handleUploadItems(w, r, q.Get("corpus"))
	case "/upload/words":
		handleUploadWords(w, r, q.Get("corpus"))
	case "/show":
		handleShow(w, r, q.Get("corpus"))
	case "/clear":
		handleDeleteCorpus(w, r, q.Get("corpus"))
	default:
		http.Error(w, "unknown path", http.StatusNotFound)
	}
}

func handleStudy(ctx context.Context, w http.ResponseWriter, kind, sn, corpusName string) {
	n, ok := parseInt(w, sn, 10)
	if !ok {
		return
	}
	if corpusName == "" {
		http.Error(w, "need corpus", http.StatusBadRequest)
		return
	}
	corpus, err := loadCorpus(ctx, corpusName)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	entries := study.BuildEntries(corpus.Items, corpus.Words, n)
	bytes, err := json.MarshalIndent(entries, "", "")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if _, err := w.Write(bytes); err != nil {
		log.Println(err)
	}

}

func parseInt(w http.ResponseWriter, sn string, defaultValue int) (int, bool) {
	n := defaultValue
	if sn != "" {
		var err error
		n, err = strconv.Atoi(sn)
		if err != nil {
			http.Error(w, fmt.Sprintf("bad number: %v", err), http.StatusBadRequest)
			return 0, false
		}
	}
	return n, true
}

func runQuiz(w http.ResponseWriter, sn string) {
	http.Error(w, "not implemented", http.StatusNotImplemented)
}

func handleUploadItems(w http.ResponseWriter, r *http.Request, corpus string) {
	if corpus == "" {
		http.Error(w, "need corpus", http.StatusBadRequest)
		return
	}
	body, ok := readBody(w, r)
	if !ok {
		return
	}
	items, err := study.ParseItems(body)
	if err != nil {
		http.Error(w, fmt.Sprintf("parsing items: %v", err), http.StatusBadRequest)
		return
	}

	if err := saveItems(appengine.NewContext(r), items, corpus); err != nil {
		http.Error(w, fmt.Sprintf("saving items: %v", err), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "Got %d items.\n", len(items))
}

func handleUploadWords(w http.ResponseWriter, r *http.Request, corpus string) {
	if corpus == "" {
		http.Error(w, "need corpus", http.StatusBadRequest)
		return
	}
	body, ok := readBody(w, r)
	if !ok {
		return
	}
	words, err := study.ParseWords(body)
	if err != nil {
		http.Error(w, fmt.Sprintf("parsing words: %v", err), http.StatusBadRequest)
		return
	}

	if err := saveWords(appengine.NewContext(r), words, corpus); err != nil {
		http.Error(w, fmt.Sprintf("saving words: %v", err), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "Got %d words.\n", len(words))
}

func readBody(w http.ResponseWriter, r *http.Request) (string, bool) {
	bytes, err := ioutil.ReadAll(r.Body)
	r.Body.Close()
	if err != nil {
		http.Error(w, fmt.Sprintf("bad body: %v", err), http.StatusBadRequest)
		return "", false
	}
	return string(bytes), true
}

var showCorpusTemplate = template.Must(template.New("").Parse(`

{{.Name}}

Items

	  {{range .Items}}

{{.English}}	{{.Pinyin}}	{{.Characters}}

	  {{else}}
		 Nothing there.
	  {{end}}

Words

	  {{range .Words}}

{{.English}}	{{.Pinyin}}	{{.PartOfSpeech}}	{{.Characters}}

	  {{else}}
		 Nothing there.
	  {{end}}

`))

func handleShow(w http.ResponseWriter, r *http.Request, corpus string) {
	if corpus == "" {
		http.Error(w, "need corpus", http.StatusBadRequest)
		return
	}
	items, err := loadItems(appengine.NewContext(r), corpus)
	if err != nil {
		http.Error(w, fmt.Sprintf("loading items: %v", err), http.StatusInternalServerError)
		return
	}
	words, err := loadWords(appengine.NewContext(r), corpus)
	if err != nil {
		http.Error(w, fmt.Sprintf("loading words: %v", err), http.StatusInternalServerError)
		return
	}
	corp := Corpus{
		Name:  corpus,
		Items: items,
		Words: words,
	}
	var buf bytes.Buffer
	if err := showCorpusTemplate.Execute(&buf, corp); err != nil {
		http.Error(w, fmt.Sprintf("executing template: %v", err), http.StatusInternalServerError)
		return
	}
	if _, err := buf.WriteTo(w); err != nil {
		log.Println(err)
	}
}

func handleDeleteThing(w http.ResponseWriter, r *http.Request, corpus, key string) {
	if corpus == "" {
		http.Error(w, "need corpus", http.StatusBadRequest)
		return
	}
	if key == "" {
		http.Error(w, "need key", http.StatusBadRequest)
		return
	}
	ctx := appengine.NewContext(r)
	err := datastore.Delete(ctx, datastore.NewKey(ctx, "Item", key, 0, corpusKey(ctx, corpus)))
	if err != nil {
		errorf(w, http.StatusInternalServerError, "deleting item: %v", err)
		return
	}
	err = datastore.Delete(ctx, datastore.NewKey(ctx, "Word", key, 0, corpusKey(ctx, corpus)))
	if err != nil {
		errorf(w, http.StatusInternalServerError, "deleting word: %v", err)
		return
	}
}

func handleDeleteCorpus(w http.ResponseWriter, r *http.Request, corpus string) {
	if corpus == "" {
		errorf(w, http.StatusBadRequest, "need corpus")
		return
	}
	ctx := appengine.NewContext(r)
	q := datastore.NewQuery("Item").Ancestor(corpusKey(ctx, corpus)).KeysOnly()
	keys, err := q.GetAll(ctx, nil)
	if err != nil {
		http.Error(w, fmt.Sprintf("reading keys: %v", err), http.StatusInternalServerError)
		return
	}
	if err := datastore.DeleteMulti(ctx, keys); err != nil {
		errorf(w, http.StatusInternalServerError, "deleting: %v", err)
		return
	}
	fmt.Fprintf(w, "Deleted %d keys.\n", len(keys))
}

func errorf(w http.ResponseWriter, status int, format string, args ...interface{}) {
	msg := fmt.Sprintf(format, args...)
	http.Error(w, msg, status)
	log.Print(msg)
}

////////////////////////////////////////////////////////////////
// Internals.

type Corpus struct {
	Name  string
	Items []*study.Item
	Words []*study.Word
}

func corpusKey(ctx context.Context, corpus string) *datastore.Key {
	return datastore.NewKey(ctx, "Corpus", corpus, 0, nil)
}

func saveItems(ctx context.Context, items []*study.Item, corpus string) error {
	for _, it := range items {
		key := datastore.NewKey(ctx, "Item", it.English, 0, corpusKey(ctx, corpus))
		_, err := datastore.Put(ctx, key, it)
		if err != nil {
			return err
		}
	}
	return nil
}

func loadItems(ctx context.Context, corpus string) ([]*study.Item, error) {
	q := datastore.NewQuery("Item").Ancestor(corpusKey(ctx, corpus))
	var items []*study.Item
	if _, err := q.GetAll(ctx, &items); err != nil {
		return nil, err
	}
	return items, nil
}

func saveWords(ctx context.Context, words []*study.Word, corpus string) error {
	for _, w := range words {
		key := datastore.NewKey(ctx, "Word", w.English, 0, corpusKey(ctx, corpus))
		_, err := datastore.Put(ctx, key, w)
		if err != nil {
			return err
		}
	}
	return nil
}

func loadWords(ctx context.Context, corpus string) ([]*study.Word, error) {
	q := datastore.NewQuery("Word").Ancestor(corpusKey(ctx, corpus))
	var words []*study.Word
	if _, err := q.GetAll(ctx, &words); err != nil {
		return nil, err
	}
	return words, nil
}

func loadCorpus(ctx context.Context, name string) (*Corpus, error) {
	items, err := loadItems(ctx, name)
	if err != nil {
		return nil, err
	}
	words, err := loadWords(ctx, name)
	if err != nil {
		return nil, err
	}
	return &Corpus{
		Name:  name,
		Items: items,
		Words: words,
	}, nil
}

repository: jba/chinese

repo_name: jba/chinese


text:
package testdata

func a() {
	type language int

	const (
		golang language = iota
		swift
		objectivec
		ruby
		typescript
	)
}

repository: bannzai/switchecker

repo_name: bannzai/switchecker

gha_language: Go


text:
inherit noto-fonts
inherit noto-cjk
inherit noto-cjk-styles

SRC_URI = "${NOTO_SRC_URI_PREFIX}/NotoSerifKR.zip"
SRC_URI[sha256sum] = "a64cbea1a4f8099120b190859d44d0438958861e8c2c6d0afe31a28b120ed7bc"
SRC_URI[sha256sum] = "3c0d276fb05aaefbbca808b4f8c7b1520b4b4e7c0be46296d6e8a5e42f559f5c"

repository: ssfivy/meta-noto

repo_name: ssfivy/meta-noto

gha_language: BitBake

extension: bb


text:
@misc{cURL,
note = {cURL, 2013. cURL. [Online] Available at:\url{http://curl.haxx.se/}, [Accessed 7 December 2013]}
}
@misc{PHP,
note = {W3Techs - World Wide Web Technology Surveys, 2013. Most popular server-side programming languages. [Online] Available at:\url{http://w3techs.com/}, [Accessed 7 December 2013]}
}

Authorship or Source, Year. Title of web document or web page. [type of medium] (date of update if available) Available at: include web site address/URL (Uniform Resource Locator) [Accessed date]. - See more at: http://libweb.anglia.ac.uk/referencing/harvard.htm#sthash.EsE1MEz5.dpuf


text:
package main

import (
	"database/sql"
	"log"

	"github.com/gin-gonic/gin"
	"github.com/kilibits/orion-dev-rest/models"
	_ "github.com/mattn/go-sqlite3"
	gorp "gopkg.in/gorp.v1"
)

var dbMap *gorp.DbMap

func dbInit() *gorp.DbMap {
	db, err := sql.Open("sqlite3", "scraperwiki.sqlite")
	if err != nil {
		log.Fatalf("Error Opening Database -> %v", err.Error())
	}

	dbMap = &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}

	return dbMap
}

func getAllProfiles(c *gin.Context) {

	var profiles []models.Profile
	_, err := dbMap.Select(&profiles, "SELECT * FROM profile")

	if err != nil {
		log.Fatalf("Select statement failed -> %v", err.Error())
	}
	c.JSON(200, profiles)
}

func getProfile(c *gin.Context) {

	var profile models.Profile
	id := c.Params.ByName("profile_id")
	_, err := dbMap.Select(&profile, "SELECT * FROM profile WHERE id = ?", id)

	if err != nil {
		log.Fatalf("Select statement failed -> %v", err.Error())
	}

	c.JSON(200, profile)
}

func getByParty(c *gin.Context) {
	var profiles []models.Profile
	id := c.Params.ByName("party")
	_, err := dbMap.Select(&profiles, "SELECT * FROM profile WHERE group = ?", id)

	if err != nil {
		log.Fatalf("Select statement failed -> %v", err.Error())
	}

	c.JSON(200, profiles)
}

func getByConstituency(c *gin.Context) {
	var profiles []models.Profile
	id := c.Params.ByName("area")
	_, err := dbMap.Select(&profiles, "SELECT * FROM profile WHERE area = ?", id)

	if err != nil {
		log.Fatalf("Select statement failed -> %v", err.Error())
	}
	c.JSON(200, profiles)
}

func getEducationHistory(c *gin.Context) {
	var edu []models.EducationHistory
	id := c.Params.ByName("id")
	_, err := dbMap.Select(&edu, "SELECT institution, level, award, [from], [to] FROM profile JOIN education_history ON profile.id = education_history.mp_id WHERE profile.name id = '%?%'", id)

	if err != nil {
		log.Fatalf("Select statement failed -> %v", err.Error())
	}

	c.JSON(200, edu)
}

func main() {
	dbMap = dbInit()
	app := gin.Default()
	app.GET("/profiles", getAllProfiles)
	app.GET("/profiles/:profile_id", getProfile)
	app.GET("/education/:id", getEducationHistory)
	//app.GET("/profileImages", downloadImages)
	app.Run(":9000")
}

repository: kilibits/orion-dev-rest

repo_name: kilibits/orion-dev-rest


text:
package configresource

import (
	"regexp"
	"strconv"
	"strings"

	"github.com/douyu/jupiter/pkg/xlog"
)

type (
	// ResourceItem ..
	ResourceItem struct {
		Name    string `json:"name"`
		Version uint   `json:"version"`
	}
)

// GetAllConfigResource ..
func GetAllConfigResource(content string) (res []string) {
	reg := regexp.MustCompile(`{{[\w\-_]*@[0-9]+}}`)
	return reg.FindAllString(content, -1)
}

//ParseResourceFromConfig 从配置内容中解析出依赖的资源及其版本
func ParseResourceFromConfig(content string) (resourceItems []ResourceItem) {
	resources := GetAllConfigResource(content)
	for _, res := range resources {
		res = strings.Trim(strings.Trim(res, "{{"), "}}")
		splices := strings.Split(res, "@")
		if len(splices) != 2 {
			continue
		}

		version, err := strconv.Atoi(splices[1])
		if err != nil {
			xlog.Error("ParseResourceFromConfig", xlog.String("error", "parse version id failed:"+err.Error()))
			continue
		}

		resourceItems = append(resourceItems, ResourceItem{
			Name:    splices[0],
			Version: uint(version),
		})
	}

	return
}

repository: douyu/juno

repo_name: douyu/juno

gha_language: JavaScript


text:
find_path(LUAJIT_INCLUDE_DIR luajit.h
  HINTS
    ENV LUAJIT_DIR
  PATH_SUFFIXES
    include/luajit-2.0 include/luajit2.0 include/luajit include
  PATHS
    ~/Library/Frameworks
    /Library/Frameworks
    /usr/local
    /usr
    /sw
    /opt/local
    /opt/csw
    /opt
)

find_library(LUAJIT_LIBRARY
  NAMES luajit-51 luajit-5.1 luajit
  HINTS
    ENV LUAJIT_DIR
  PATH_SUFFIXES lib
  PATHS
    ~/Library/Frameworks
    /Library/Frameworks
    /usr/local
    /usr/
    /sw
    /opt/local
    /opt/csw
    /opt
)

if(LUAJIT_LIBRARY)
  # include the math library for Unix
  if(UNIX AND NOT APPLE AND NOT BEOS)
    find_library(LUAJIT_MATH_LIBRARY m)
    set( LUAJIT_LIBRARY "${LUAJIT_LIBRARY};${LUAJIT_MATH_LIBRARY}" CACHE STRING "Lua Libraries")
  # For Windows and Mac, don't need to explicitly include the math library
  else()
    set( LUAJIT_LIBRARY "${LUAJIT_LIBRARY}" CACHE STRING "Lua Libraries")
  endif()
endif()

include(FindPackageHandleStandardArgs)
# handle the QUIETLY and REQUIRED arguments and set LUA_FOUND to TRUE if
# all listed variables are TRUE
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LuaJIT
  REQUIRED_VARS LUAJIT_LIBRARY LUAJIT_INCLUDE_DIR
  VERSION_VAR LUAJIT_VERSION_STRING)

mark_as_advanced(
  LUAJIT_INCLUDE_DIR LUAJIT_LIBRARIES LUAJIT_LIBRARY LUAJIT_MATH_LIBRARY)

repository: sourrust/laco

repo_name: sourrust/laco

extension: cmake


text:
SET(PB_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/../third_party/protobuf/include)
SET(PB_LIB_DIR ${PROJECT_SOURCE_DIR}/../third_party/protobuf/lib)
SET(SLOG_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/../slog)
SET(SLOG_LIB_DIR ${PROJECT_SOURCE_DIR}/../slog)
# SET(LOG4CXX_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/../third_party/log4cxx/include)
# SET(LOG4CXX_LIB_DIR ${PROJECT_SOURCE_DIR}/../third_party/log4cxx/lib)

#设置自己mac os的openssl的路径
if(APPLE)
    SET(OPENSSL_INCLUDE_DIR /usr/local/Cellar/openssl@1.1/1.1.1k/include)
    SET(OPENSSL_LIB_DIR /usr/local/Cellar/openssl@1.1/1.1.1k/lib)
		SET(UUID_LIB_DIR /usr/local/lib)
endif()

ADD_DEFINITIONS( -g -W -Wall -D_REENTRANT -D_FILE_OFFSET_BITS=64 -DAC_HAS_INFO
-DAC_HAS_WARNING -DAC_HAS_ERROR -DAC_HAS_CRITICAL -DTIXML_USE_STL
-DAC_HAS_DEBUG -DLINUX_DAEMON -std=c++11 -Wno-deprecated)

INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/../base ${PROJECT_SOURCE_DIR}/../base/security ${PROJECT_SOURCE_DIR}/../base/jsoncpp ${PB_INCLUDE_DIR} ${PROJECT_SOURCE_DIR}/../base/pb/protocol ${OPENSSL_INCLUDE_DIR} ${SLOG_INCLUDE_DIR})
LINK_DIRECTORIES(${PROJECT_SOURCE_DIR}/../base ${PB_LIB_DIR} ${SLOG_LIB_DIR} ${OPENSSL_LIB_DIR} ${UUID_LIB_DIR})

repository: xiaominfc/TeamTalk

repo_name: xiaominfc/TeamTalk


text:
SUMMARY = "A chorus audio effect plugin based on DSP code by Togu Audio Line (TAL)"
HOMEPAGE = "https://github.com/SpotlightKid/ykchorus"
LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://LICENSE;md5=02ad2afd072e9ce4a370bedb49e2b075"

inherit pkgconfig gtk-icon-cache lv2-turtle-helper pack_audio_plugins

DEPENDS += " \
    liblo \
    jack \
    virtual/libgl \
"

SRC_URI = "gitsm://github.com/SpotlightKid/ykchorus.git;branch=master;protocol=https"
SRCREV = "6722568d5551b0f847083269cfbdfaa0f76b906f"
PV = "0.2.3"
S = "${WORKDIR}/git"

EXTRA_OEMAKE += " \
    PREFIX=${prefix} \
    NOOPT=true \
    SKIP_STRIPPING=true \
"

do_ttl_sed() {
    sed -i 's|${EXE_WRAPPER} "${GEN}" "./\x24{FILE}"|echo "`realpath  "./$FILE"`" >> ${LV2_PLUGIN_INFO_FILE}|g' ${S}/dpf/utils/generate-ttl.sh
}

do_install() {
    oe_runmake DESTDIR=${D} PREFIX=${prefix} LIBDIR=${libdir} install
}

repository: schnitzeltony/meta-musicians

repo_name: schnitzeltony/meta-musicians


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

#include <gmock/gmock.h>
#include <libsnapshot/snapshot_writer.h>

namespace android::snapshot {

class MockSnapshotWriter : public ISnapshotWriter {
  public:
    using FileDescriptor = ISnapshotWriter::FileDescriptor;

    explicit MockSnapshotWriter(const CowOptions& options) : ISnapshotWriter(options) {}
    MockSnapshotWriter() : ISnapshotWriter({}) {}

    MOCK_METHOD(bool, Finalize, (), (override));

    // Return number of bytes the cow image occupies on disk.
    MOCK_METHOD(uint64_t, GetCowSize, (), (override));

    // Returns true if AddCopy() operations are supported.
    MOCK_METHOD(bool, SupportsCopyOperation, (), (const override));

    MOCK_METHOD(bool, EmitCopy, (uint64_t, uint64_t), (override));
    MOCK_METHOD(bool, EmitRawBlocks, (uint64_t, const void*, size_t), (override));
    MOCK_METHOD(bool, EmitXorBlocks, (uint32_t, const void*, size_t, uint32_t, uint16_t),
                (override));
    MOCK_METHOD(bool, EmitZeroBlocks, (uint64_t, uint64_t), (override));
    MOCK_METHOD(bool, EmitLabel, (uint64_t), (override));
    MOCK_METHOD(bool, EmitSequenceData, (size_t, const uint32_t*), (override));

    // Open the writer in write mode (no append).
    MOCK_METHOD(bool, Initialize, (), (override));
    MOCK_METHOD(bool, VerifyMergeOps, (), (override, const, noexcept));

    // Open the writer in append mode, with the last label to resume
    // from. See CowWriter::InitializeAppend.
    MOCK_METHOD(bool, InitializeAppend, (uint64_t label), (override));

    MOCK_METHOD(std::unique_ptr<FileDescriptor>, OpenReader, (), (override));
};
}  // namespace android::snapshot

gha_license_id: NOASSERTION

extension: h


text:
# -----------------------------------------------------------------------------------
#
# Finds the LEMON library
#
# -----------------------------------------------------------------------------------
#
# Variables used by this module, they can change the default behaviour.
# Those variables need to be either set before calling find_package
# or exported as environment variables before running CMake:
#
# LEMON_INCLUDEDIR - Set custom include path, useful when the headers are
#                        outside system paths
# LEMON_LIBRARYDIR - Set custom include path, useful when the library is
#                        outside system paths
#
# -----------------------------------------------------------------------------------
#
# Variables defined by this module:
#
# LEMON_FOUND        - True if LEMON was found
# LEMON_INCLUDE_DIRS - Path to LEMON include directory
# LEMON_LIBRARIES    - The LEMON libraries
#
# -----------------------------------------------------------------------------------
#
# Example usage:
#
#  set(LEMON_INCLUDEDIR "/opt/dev/lemon/include")
#
#  find_package(LEMON REQUIRED)
#
#  include_directories("${LEMON_INCLUDE_DIRS}")
#  add_executable(foo foo.cc)
#
# -----------------------------------------------------------------------------------

SET(LEMON_INCLUDEDIR  "" CACHE PATH "LEMON include directory")

foreach(opt LEMON_INCLUDEDIR LEMON_LIBRARYDIR)
	if(${opt} AND DEFINED ENV{${opt}} AND NOT ${opt} STREQUAL "$ENV{${opt}}")
		message(WARNING "Conflicting ${opt} values: ignoring environment variable and using CMake cache entry.")
	elseif(DEFINED ENV{${opt}} AND NOT ${opt})
		set(${opt} "$ENV{${opt}}")
	endif()
endforeach()

FIND_PATH(LEMON_INCLUDE_DIR
	lemon/core.h
	PATHS ${LEMON_INCLUDEDIR}/include ${CMAKE_SOURCE_DIR}/deps/lemon/include
	"C:/Program Files/LEMON/include"
)

FIND_LIBRARY(LEMON_LIBRARY
	NAMES lemon emon
	PATHS ${LEMON_LIBRARYDIR}/lib ${CMAKE_SOURCE_DIR}/deps/lemon/lib
	"C:/Program Files/LEMON/lib"
)

#####################3

INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LEMON DEFAULT_MSG LEMON_LIBRARY LEMON_INCLUDE_DIR)

IF(LEMON_FOUND)
	SET(LEMON_INCLUDE_DIRS ${LEMON_INCLUDE_DIR})
	SET(LEMON_LIBRARIES ${LEMON_LIBRARY})
ENDIF(LEMON_FOUND)

MARK_AS_ADVANCED(LEMON_LIBRARY LEMON_INCLUDE_DIR)

repository: leolvt/sppm

repo_name: leolvt/sppm


text:
// simple forensic image file use stlib Golang
// test gif, png, jpg

package main

import (
	"fmt"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"os"
)

func main() {
	if len(os.Args) == 0 {
		fmt.Printf("Use: %v fileUnknown fileUnknown fileUnknown ...\n", os.Args[0])
	} else {
		for _, file := range os.Args[1:] {
			f, err := os.Open(file)
			if err != nil {
				fmt.Fprintf(os.Stderr, "file: %v\n", err)
				f.Close()
				continue
			}

			_, kind, err := image.Decode(f)
			if err != nil {
				fmt.Fprintf(os.Stderr, "%v: %v\n", f.Name(), err)
				f.Close()
				continue
			}
			fmt.Fprintln(os.Stdout, f.Name(), "Format =", kind)

			f.Close()
		}
	}
}

repository: kaisaryousuf/goHackTools

repo_name: kaisaryousuf/goHackTools


text:
package coinbase

import corecb "github.com/hacash/core/coinbase"

// Bitcoin mortgage loan: calculate the quantity that can be borrowed
// Totallendingpercentage total percentage lent
// Return lendable quantity and prepaid interest
func CalculationOfInterestBitcoinMortgageLoanAmount(totalLendingPercentage float64) (float64, float64) {
	return corecb.CalculationOfInterestBitcoinMortgageLoanAmount(totalLendingPercentage)
}

repository: hacash/mint

repo_name: hacash/mint


text:
FIND_PATH( GLEE_INCLUDE_DIRS GLee.h /usr/include /usr/local/include /usr/include/GL $ENV{INCLUDE} )
FIND_LIBRARY( GLEE_LIBRARIES NAMES GLee glee PATHS /usr/lib /usr/local/lib )

IF(GLEE_INCLUDE_DIRS)
	MESSAGE(STATUS "Found GLEE include dir: ${GLEE_INCLUDE_DIRS}")
ELSE(GLEE_INCLUDE_DIRS)
	MESSAGE(STATUS "Could NOT find GLEE headers.")
ENDIF(GLEE_INCLUDE_DIRS)

IF(GLEE_LIBRARIES)
	MESSAGE(STATUS "Found GLEE library: ${GLEE_LIBRARIES}")
ELSE(GLEE_LIBRARIES)
	MESSAGE(STATUS "Could NOT find GLEE library.")
ENDIF(GLEE_LIBRARIES)

IF(GLEE_INCLUDE_DIRS AND GLEE_LIBRARIES)
	SET(GLEE_FOUND "YES")
ELSE(GLEE_INCLUDE_DIRS AND GLEE_LIBRARIES)
	SET(GLEE_FOUND "NO")
	IF(GLEE_FIND_REQUIRED)
		MESSAGE(FATAL_ERROR "Could not find GLEE. Please install GLEE")
	ENDIF(GLEE_FIND_REQUIRED)
ENDIF(GLEE_INCLUDE_DIRS AND GLEE_LIBRARIES)

repository: Kazade/Spindash

repo_name: Kazade/Spindash


text:
package requirements

import (
	"fmt"

	log "github.com/newrelic/newrelic-diagnostics-cli/logger"
	"github.com/newrelic/newrelic-diagnostics-cli/tasks"
)

const processorRegLoc = `SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE`

type DotnetRequirementsProcessorType struct {
	getProcessorArch tasks.GetProcessorArchFunc
}

func (p DotnetRequirementsProcessorType) Identifier() tasks.Identifier {
	return tasks.IdentifierFromString("DotNet/Requirements/ProcessorType")
}

func (p DotnetRequirementsProcessorType) Explain() string {
	return "Check processor architecture compatibility with New Relic .NET agent"
}

func (p DotnetRequirementsProcessorType) Dependencies() []string {
	return []string{
		"DotNet/Agent/Installed",
	}
}

func (p DotnetRequirementsProcessorType) Execute(options tasks.Options, upstream map[string]tasks.Result) tasks.Result {

	var result tasks.Result
	// abort if it isn't installed
	if upstream["DotNet/Agent/Installed"].Status != tasks.Success {
		if upstream["DotNet/Agent/Installed"].Summary == tasks.NoAgentDetectedSummary {
			return tasks.Result{
				Status:  tasks.None,
				Summary: tasks.NoAgentUpstreamSummary + "DotNet/Agent/Installed",
			}
		}
		return tasks.Result{
			Status:  tasks.None,
			Summary: tasks.UpstreamFailedSummary + "DotNet/Agent/Installed",
		}
	}

	procType, err := p.getProcessorArch()

	if err != nil {
		log.Debug("Error while getting Processor type", err.Error())

		result.Status = tasks.Error
		result.Summary = "Error while getting Processor type, see debug logs for more details."
		return result

	}

	if procType == "x86" {
		result.Status = tasks.Success
		result.Summary = "Processor detected as x86"
		return result

	}

	if procType == "AMD64" {
		result.Status = tasks.Success
		result.Summary = "Processor detected as x64"
		return result

	}

	result.Status = tasks.Failure
	result.Summary = fmt.Sprintf("Processor detected as %v. .Net Framework Agent only supports x86 and x64 processors", procType)
	result.URL = "https://docs.newrelic.com/docs/agents/net-agent/getting-started/compatibility-requirements-net-framework-agent#architecture"
	return result

}

repository: carlossscastro/newrelic-diagnostics-cli

repo_name: carlossscastro/newrelic-diagnostics-cli

branch_name: refs/heads/main


text:
require recipes-bsp/pa-lld/pa-lld.inc

PR = "${INC_PR}.4"

do_compile() {
    :
}

do_install() {
    local pa_fw_dir

    case "${LIBPA}" in
        "libpa")
            pa_fw_dir="${S}/fw/v0"
            ;;
        "libpa2")
            pa_fw_dir="${S}/fw/v1"
            ;;
        *)
            echo "Error: ${LIBPA} does not have a fw directory!"
            return 1
    esac

    install -d "${D}${base_libdir}/firmware"
    for fw in $(find "${pa_fw_dir}" -name '*.bin')
    do
        install -m 0644 "${fw}" "${D}${base_libdir}/firmware"
    done
}

FILES_${PN} = "${base_libdir}/firmware"

repository: rcn-ee/meta-processor-sdk

repo_name: rcn-ee/meta-processor-sdk


text:
/*
 * NRF NFManagement Service
 *
 * NRF NFManagement Service
 *
 * API version: 1.0.1
 * Generated by: OpenAPI Generator (https://openapi-generator.tech)
 */

package models

type Nullnftype string

// List of nullnftype
const (
	Nullnftype_NRF      Nullnftype = "NRF"
	Nullnftype_UDM      Nullnftype = "UDM"
	Nullnftype_AMF      Nullnftype = "AMF"
	Nullnftype_SMF      Nullnftype = "SMF"
	Nullnftype_AUSF     Nullnftype = "AUSF"
	Nullnftype_NEF      Nullnftype = "NEF"
	Nullnftype_PCF      Nullnftype = "PCF"
	Nullnftype_SMSF     Nullnftype = "SMSF"
	Nullnftype_NSSF     Nullnftype = "NSSF"
	Nullnftype_UDR      Nullnftype = "UDR"
	Nullnftype_LMF      Nullnftype = "LMF"
	Nullnftype_GMLC     Nullnftype = "GMLC"
	Nullnftype__5_G_EIR Nullnftype = "5G_EIR"
	Nullnftype_SEPP     Nullnftype = "SEPP"
	Nullnftype_UPF      Nullnftype = "UPF"
	Nullnftype_N3_IWF   Nullnftype = "N3IWF"
	Nullnftype_AF       Nullnftype = "AF"
	Nullnftype_UDSF     Nullnftype = "UDSF"
	Nullnftype_BSF      Nullnftype = "BSF"
	Nullnftype_CHF      Nullnftype = "CHF"
	Nullnftype_NWDAF    Nullnftype = "NWDAF"
)

repository: matsumu-y/openapi

repo_name: matsumu-y/openapi


text:
@inproceedings{jung2001camera,
  title={Camera trajectory estimation using inertial sensor measurements and structure from motion results},
  author={Jung, S-H and Taylor, Camillo J},
  booktitle={Computer Vision and Pattern Recognition, 2001. CVPR 2001. Proceedings of the 2001 IEEE Computer Society Conference on},
  volume={2},
  pages={II--II},
  year={2001},
  organization={IEEE}
}

@article{nutzi2011fusion,
  title={Fusion of IMU and vision for absolute scale estimation in monocular SLAM},
  author={N{\"u}tzi, Gabriel and Weiss, Stephan and Scaramuzza, Davide and Siegwart, Roland},
  journal={Journal of intelligent \& robotic systems},
  volume={61},
  number={1-4},
  pages={287--299},
  year={2011},
  publisher={Springer}
}

@article{zhang,
  title={A flexible new technique for camera calibration},
  author={Zhang, Zhengyou},
  journal={IEEE Transactions on pattern analysis and machine intelligence},
  volume={22},
  year={2000}
}

@article{hietanen2016comparison,
  title={A comparison of feature detectors and descriptors for object class matching},
  author={Hietanen, Antti and Lankinen, Jukka and K{\"a}m{\"a}r{\"a}inen, Joni-Kristian and Buch, Anders Glent and Kr{\"u}ger, Norbert},
  journal={Neurocomputing},
  volume={184},
  pages={3--12},
  year={2016},
  publisher={Elsevier}
}

@article{lowe2004distinctive,
  title={Distinctive image features from scale-invariant keypoints},
  author={Lowe, David G},
  journal={International journal of computer vision},
  volume={60},
  number={2},
  pages={91--110},
  year={2004},
  publisher={Springer}
}

@article{tomasi1991detection,
  title={Detection and tracking of point features},
  author={Tomasi, Carlo and Kanade, Takeo},
  year={1991},
  publisher={School of Computer Science, Carnegie Mellon Univ. Pittsburgh}
}

@article{nister2004efficient,
  title={An efficient solution to the five-point relative pose problem},
  author={Nist{\'e}r, David},
  journal={IEEE transactions on pattern analysis and machine intelligence},
  volume={26},
  number={6},
  pages={756--770},
  year={2004},
  publisher={IEEE}
}

@article{longuet1981computer,
  title={A computer algorithm for reconstructing a scene from two projections},
  author={Longuet-Higgins, H Christopher},
  journal={Nature},
  volume={293},
  number={5828},
  pages={133},
  year={1981},
  publisher={Nature Publishing Group}
}

@misc{chli2017,
  author        = {Margarita Chli, Martin Rufli, Roland Siegwart},
  title         = {Lecture notes in Autonomous Mobile Robots},
  year          = {2017},
  note   = "URL: \url{https://www.ethz.ch/content/dam/ethz/special-interest/mavt/robotics-n-intelligent-systems/asl-dam/documents/lectures/autonomous_mobile_robots/spring-2017/2017%20-%20SLAM%20I%20-%20after%20lecture.pdf}.
            Last visited on 11/18/2018",
  publisher={ETH Zurich}
}

@misc{cyrillslam,
  author        = {Cyrill Stachniss},
  title         = {Lecture notes in Robot Mapping},
  year          = {2013},
  note   = "URL: \url{http://ais.informatik.uni-freiburg.de/teaching/ws12/mapping/pdf/slam04-ekf-slam.pdf}.
            Last visited on 11/18/2018",
  publisher={Uni Freiburg}
}

@inproceedings{klein2007parallel,
  title={Parallel tracking and mapping for small AR workspaces},
  author={Klein, Georg and Murray, David},
  booktitle={Mixed and Augmented Reality, 2007. ISMAR 2007. 6th IEEE and ACM International Symposium on},
  pages={225--234},
  year={2007},
  organization={IEEE}
}

@misc{ptamcode,
  author        = {Klein, Georg and Murray, David},
  title         = {Source Code of PTAM (Parallel Tracking and Mapping)},
  note   = "URL: \url{http://www.robots.ox.ac.uk/~gk/PTAM/}.
            Last visited on 11/18/2018",
  publisher={ETH Zurich}
}

@inproceedings{davison2003real,
  title={Real-time simultaneous localisation and mapping with a single camera},
  author={Davison, Andrew J},
  pages={1403},
  year={2003},
  organization={IEEE}
}

@article{davison2007monoslam,
  title={MonoSLAM: Real-time single camera SLAM},
  author={Davison, Andrew J and Reid, Ian D and Molton, Nicholas D and Stasse, Olivier},
  journal={IEEE Transactions on Pattern Analysis \& Machine Intelligence},
  number={6},
  pages={1052--1067},
  year={2007},
  publisher={IEEE}
}

@misc{ByBo2015,
  author        = {Byron Boots},
  title         = {Statistical Techniques in Robotics},
  year          = {2015},
  note   = "URL: \url{https://www.cc.gatech.edu/~bboots3/STR-Spring2015/Lectures/Lecture12/Lecture12_notes.pdf}.
            Last visited on 11/18/2018"
}

@article{scaramuzza2011visual,
  title={Visual odometry [tutorial]},
  author={Scaramuzza, Davide and Fraundorfer, Friedrich},
  journal={IEEE robotics \& automation magazine},
  volume={18},
  number={4},
  pages={80--92},
  year={2011},
  publisher={IEEE}
}

@article{fraundorfer2012visual,
  title={Visual odometry: Part ii: Matching, robustness, optimization, and applications},
  author={Fraundorfer, Friedrich and Scaramuzza, Davide},
  journal={IEEE Robotics \& Automation Magazine},
  volume={19},
  number={2},
  pages={78--90},
  year={2012},
  publisher={IEEE}
}

@article{taketomi2017visual,
  title={Visual SLAM algorithms: a survey from 2010 to 2016},
  author={Taketomi, Takafumi and Uchiyama, Hideaki and Ikeda, Sei},
  journal={IPSJ Transactions on Computer Vision and Applications},
  volume={9},
  number={1},
  pages={16},
  year={2017},
  publisher={SpringerOpen}
}

@article{cadena2016past,
  title={Past, present, and future of simultaneous localization and mapping: Toward the robust-perception age},
  author={Cadena, Cesar and Carlone, Luca and Carrillo, Henry and Latif, Yasir and Scaramuzza, Davide and Neira, Jos{\'e} and Reid, Ian and Leonard, John J},
  journal={IEEE Transactions on Robotics},
  volume={32},
  number={6},
  pages={1309--1332},
  year={2016},
  publisher={IEEE}
}

@article{bresson2017simultaneous,
  title={Simultaneous localization and mapping: A survey of current trends in autonomous driving},
  author={Bresson, Guillaume and Alsayed, Zayed and Yu, Li and Glaser, S{\'e}bastien},
  journal={IEEE Transactions on Intelligent Vehicles},
  volume={20},
  pages={1--1},
  year={2017}
}

@article{strasdatavisual,
  title={Visual SLAM: Why Filter?},
  author={Strasdata, Hauke and Montielb, JMM and Davisona, Andrew J}
}

@article{bouguet2004camera,
  title={Camera calibration toolbox for matlab},
  author={Bouguet, J-Y},
  journal={http://www. vision. caltech. edu/bouguetj/calib\_doc/index. html},
  year={2004}
}

@inproceedings{heikkila1997four,
  title={A four-step camera calibration procedure with implicit image correction},
  author={Heikkila, Janne and Silven, Olli},
  booktitle={Computer Vision and Pattern Recognition, 1997. Proceedings., 1997 IEEE Computer Society Conference on},
  pages={1106--1112},
  year={1997},
  organization={IEEE}
}

@misc{camMATLAB,
  author        = {MATLAB},
  title         = {What is Camera Calibration},
  note   = "URL: \url{https://www.mathworks.com/help/vision/ug/camera-calibration.html}.
            Last visited on 11/18/2018",
  publisher={MATLAB}
}

@misc{imgFormBoomgaard,
  author        = {Rein van den Boomgaard},
  title         = {Lecture Notes Image Processing and Computer Vision},
  note   = "URL: \url{https://staff.fnwi.uva.nl/r.vandenboomgaard/IPCV20162017/LectureNotes/IP/Images/ImageFormation.html}.
            Last visited on 11/18/2018",
  publisher={Rein van den Boomgaard}
}

@misc{StarElec,
  author        = {Starlino Electronics},
  title         = {IMU Guide},
  note   = "URL: \url{http://www.starlino.com/imu_guide.html}.
            Last visited on 11/18/2018",
publisher={Starlino Electronics}
}


text:
SUMMARY = "fwupd demo firmware data"
DESCRIPTION = "This demonstrates how to package firmware so that it \
can be delivered via the normal system update. It uses \
the firmware for the Logitech Unifying Receiver as example \
and thus can be used to update real devices. \
However, the vendor only granted permission to distribute the \
.cab file to the Linux Vendor Firmware Service and thus \
this example can only be used in local builds where the result \
does not get re-distributed."
HOMEPAGE = "https://github.com/hughsie/fwupd/tree/master/plugins/unifying"
LICENSE = "CLOSED"
DEPENDS = "gcab-native"

inherit allarch

# We include firmware for two different device flavors and two versions.
# This allows testing both updates and downgrades.
SRC_URI = " \
    file://metadata.xml \
    file://demo.conf \
    https://fwupd.org/downloads/6e5ab5961ec4c577bff198ebb465106e979cf686-Logitech-Unifying-RQR12.05_B0028.cab;name=RQR12.05 \
    https://fwupd.org/downloads/938fec082652c603a1cdafde7cd25d76baadc70d-Logitech-Unifying-RQR12.07_B0029.cab;name=RQR12.07 \
    https://fwupd.org/downloads/82b90b2614a9a4d0aced1ab8a4a99e228c95585c-Logitech-Unifying-RQ024.03_B0027.cab;name=RQR24.03 \
    https://fwupd.org/downloads/4511b9b0d123bdbe8a2007233318ab215a59dfe6-Logitech-Unifying-RQR24.05_B0029.cab;name=RQR24.05 \
"
SRC_URI[RQR12.05.sha256sum] = "f38cd350c8557db834f6208a006040c66772e514808fcbd5daf27397eafb4f78"
SRC_URI[RQR12.07.sha256sum] = "6c2d1b06d4cdafc0f5f9c03f06e0fe094209b277a38ed4011f2af533e7c047f8"
SRC_URI[RQR24.03.sha256sum] = "e55f7f6a9524652a17c7763e817dac05944957cef45ff1b54f964b693c5f17fb"
SRC_URI[RQR24.05.sha256sum] = "1313be32515f52df37c641a928f232f921e641472e8d08c78a0e9cef8e73c2d8"

python do_compile () {
    import glob
    import hashlib
    import subprocess
    import tempfile

    workdir = d.getVar('WORKDIR')

    # Remove GPG signature. We trust that the content gets delivered unmodified
    # and having the signature would force us to install GnuPG, because fwupd
    # always invokes it when it sees a signature.
    metadata = open(os.path.join(workdir, 'metadata.xml')).read()
    for cab in glob.glob(os.path.join(workdir, '*.cab')):
        with tempfile.TemporaryDirectory() as tmpdir:
            subprocess.check_output(['gcab', '--extract', cab],
                                    cwd=tmpdir, stderr=subprocess.STDOUT)
            signatures = glob.glob(os.path.join(tmpdir, '*.asc'))
            stripped = cab + '.stripped'
            if os.path.exists(stripped):
                os.unlink(stripped)
            if signatures:
                for i in signatures:
                    os.unlink(i)
                subprocess.check_output(['gcab', '--create', stripped] + os.listdir(tmpdir),
                                        cwd=tmpdir, stderr=subprocess.STDOUT)
                # We consider hash collisions unlikely and just search/replace
                # the hash string in the entire XML document after modifying the cab.
                oldhash = hashlib.sha1(open(cab, 'rb').read()).hexdigest()
                newhash = hashlib.sha1(open(stripped, 'rb').read()).hexdigest()
                metadata = metadata.replace(oldhash, newhash)
            else:
                os.link(cab, stripped)
    open(os.path.join(workdir, 'metadata.xml.stripped'), 'w').write(metadata)
}

do_install () {
    install -d ${D}${sysconfdir}/fwupd/remotes.d
    install ${WORKDIR}/demo.conf ${D}${sysconfdir}/fwupd/remotes.d/
    install -d ${D}${datadir}/fwupd/remotes.d/demo/firmware
    for i in ${WORKDIR}/*.cab.stripped; do
        install $i ${D}${datadir}/fwupd/remotes.d/demo/firmware/`basename $i .stripped`
    done
    install -d ${D}${datadir}/fwupd/remotes.d/demo/
    gzip -c ${WORKDIR}/metadata.xml.stripped >${D}${datadir}/fwupd/remotes.d/demo/demo.xml.gz
}

FILES_${PN} += " \
    ${datadir}/fwupd/ \
"

repository: intel/intel-iot-refkit

repo_name: intel/intel-iot-refkit

gha_language: Python


text:
package sharded

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/minio/minio-go"
	"gopkg.in/yaml.v2"

	"github.com/percona/percona-backup-mongodb/pbm"
)

type backupDelete struct {
	name string
	ts   time.Time
}

func (c *Cluster) BackupDelete(storage string) {
	c.pitrOn()
	defer c.pitrOff()

	checkData := c.DataChecker()

	backups := make([]backupDelete, 5)
	for i := 0; i < len(backups); i++ {
		ts := time.Now()
		time.Sleep(1 * time.Second)
		c.printBcpList()
		bcpName := c.LogicalBackup()
		backups[i] = backupDelete{
			name: bcpName,
			ts:   ts,
		}
		c.BackupWaitDone(bcpName)

		time.Sleep(time.Minute)
	}

	c.printBcpList()

	log.Println("delete backup", backups[4].name)
	_, err := c.pbm.RunCmd("pbm", "delete-backup", "-f", backups[4].name)
	if err != nil {
		log.Fatalf("ERROR: delete backup %s: %v", backups[4].name, err)
	}
	log.Println("wait for delete")
	err = c.mongopbm.WaitConcurentOp(&pbm.LockHeader{Type: pbm.CmdDeleteBackup}, time.Minute*5)
	if err != nil {
		log.Fatalf("waiting for the delete: %v", err)
	}

	c.printBcpList()

	log.Printf("delete backups older than %s / %s \n", backups[3].name, backups[3].ts.Format("2006-01-02T15:04:05"))
	_, err = c.pbm.RunCmd("pbm", "delete-backup", "-f", "--older-than", backups[3].ts.Format("2006-01-02T15:04:05"))
	if err != nil {
		log.Fatalf("ERROR: delete backups older than %s: %v", backups[3].name, err)
	}
	log.Println("wait for delete")
	err = c.mongopbm.WaitConcurentOp(&pbm.LockHeader{Type: pbm.CmdDeleteBackup}, time.Minute*5)
	if err != nil {
		log.Fatalf("waiting for the delete: %v", err)
	}
	time.Sleep(time.Second * 5)
	c.pitrOff()

	c.printBcpList()

	left := map[string]struct{}{
		backups[0].name: {}, // is a base for the pitr timeline, shouldn't be deleted
		backups[3].name: {},
	}
	log.Println("should be only backups", left)
	checkArtefacts(storage, left)

	blist, err := c.mongopbm.BackupsList(0)
	if err != nil {
		log.Fatalln("ERROR: get backups list", err)
	}

	if len(blist) != len(left) {
		log.Fatalf("ERROR: backups list mismatch, expect: %v, have: %v", left, blist)
	}
	for _, b := range blist {
		if _, ok := left[b.Name]; !ok {
			log.Fatalf("ERROR: backup %s should be deleted", b.Name)
		}
	}

	list, err := c.pbm.List()
	if err != nil {
		log.Fatalf("ERROR: get backups/pitr list: %v", err)
	}

	if len(list.Snapshots) == 0 {
		log.Println("ERROR: empty spanpshots list")
		c.printBcpList()
		os.Exit(1)
	}

	tsp := time.Unix(list.Snapshots[len(list.Snapshots)-1].RestoreTS, 0).Add(time.Second * 10)

	log.Printf("delete pitr older than %s \n", tsp.Format("2006-01-02T15:04:05"))
	_, err = c.pbm.RunCmd("pbm", "delete-pitr", "-f", "--older-than", tsp.Format("2006-01-02T15:04:05"))
	if err != nil {
		log.Fatalf("ERROR: delete pitr older than %s: %v", tsp.Format("2006-01-02T15:04:05"), err)
	}
	log.Println("wait for delete-pitr")
	err = c.mongopbm.WaitConcurentOp(&pbm.LockHeader{Type: pbm.CmdDeletePITR}, time.Minute*5)
	if err != nil {
		log.Fatalf("ERROR: waiting for the delete-pitr: %v", err)
	}

	list, err = c.pbm.List()
	if err != nil {
		log.Fatalf("ERROR: get backups/pitr list: %v", err)
	}

	if len(list.PITR.Ranges) == 0 {
		log.Fatalf("ERROR: empty pitr list, expected range after the last backup")
	}
	if len(list.Snapshots) == 0 {
		log.Fatalf("ERROR: empty spanpshots list")
	}

	if list.PITR.Ranges[0].Range.Start-1 != uint32(list.Snapshots[len(list.Snapshots)-1].RestoreTS) {
		log.Printf("ERROR: expected range starts the next second after the backup complete time, %v | %v",
			list.PITR.Ranges[0].Range.Start+1, uint32(list.Snapshots[len(list.Snapshots)-1].RestoreTS))
		c.printBcpList()
		os.Exit(1)
	}

	log.Println("delete pitr all")
	_, err = c.pbm.RunCmd("pbm", "delete-pitr", "-f", "--all")
	if err != nil {
		log.Fatalf("ERROR: delete all pitr: %v", err)
	}
	log.Println("wait for delete-pitr all")
	err = c.mongopbm.WaitConcurentOp(&pbm.LockHeader{Type: pbm.CmdDeletePITR}, time.Minute*5)
	if err != nil {
		log.Fatalf("ERROR: waiting for the delete-pitr: %v", err)
	}

	list, err = c.pbm.List()
	if err != nil {
		log.Fatalf("ERROR: get backups/pitr list: %v", err)
	}

	if len(list.PITR.Ranges) != 0 {
		log.Println("ERROR: expected empty pitr list but got:")
		c.printBcpList()
		os.Exit(1)
	}

	log.Println("trying to restore from", backups[3])
	c.DeleteBallast()
	c.LogicalRestore(backups[3].name)
	checkData()
}

const awsurl = "s3.amazonaws.com"

// checkArtefacts checks if all backups artifacts removed
// except for the shouldStay
func checkArtefacts(conf string, shouldStay map[string]struct{}) {
	log.Println("check all artifacts deleted excepts backup's", shouldStay)
	buf, err := os.ReadFile(conf)
	if err != nil {
		log.Fatalln("ERROR: unable to read config file:", err)
	}

	var cfg pbm.Config
	err = yaml.UnmarshalStrict(buf, &cfg)
	if err != nil {
		log.Fatalln("ERROR: unmarshal yaml:", err)
	}

	stg := cfg.Storage

	endopintURL := awsurl
	if stg.S3.EndpointURL != "" {
		eu, err := url.Parse(stg.S3.EndpointURL)
		if err != nil {
			log.Fatalln("ERROR: parse EndpointURL:", err)
		}
		endopintURL = eu.Host
	}

	mc, err := minio.NewWithRegion(endopintURL,
		stg.S3.Credentials.AccessKeyID, stg.S3.Credentials.SecretAccessKey, false, stg.S3.Region)
	if err != nil {
		log.Fatalln("ERROR: NewWithRegion:", err)
	}

	for object := range mc.ListObjects(stg.S3.Bucket, stg.S3.Prefix, true, nil) {
		if strings.Contains(object.Key, pbm.StorInitFile) || strings.Contains(object.Key, "/pbmPitr/") {
			continue
		}
		if object.Err != nil {
			fmt.Println("ERROR: ListObjects: ", object.Err)
			continue
		}

		var ok bool
		for b := range shouldStay {
			if strings.Contains(object.Key, b) {
				ok = true
				break
			}
		}
		if !ok {
			log.Fatalln("ERROR: failed to delete lefover", object.Key)
		}
	}
}

func (c *Cluster) BackupNotDeleteRunning() {
	bcpName := c.LogicalBackup()
	c.printBcpList()
	log.Println("deleting backup", bcpName)
	o, err := c.pbm.RunCmd("pbm", "delete-backup", "-f", bcpName)
	if err == nil || !strings.Contains(err.Error(), "unable to delete backup in running state") {
		list, lerr := c.pbm.RunCmd("pbm", "list")
		log.Fatalf("ERROR: running backup '%s' shouldn't be deleted.\n"+
			"Output: %s\nStderr:%v\nBackups list:\n%v\n%v",
			bcpName, o, err, list, lerr)
	}
	c.BackupWaitDone(bcpName)
	time.Sleep(time.Second * 2)
}

func (c *Cluster) printBcpList() {
	listo, _ := c.pbm.RunCmd("pbm", "list", "--full")
	fmt.Printf("backup list:\n%s\n", listo)
}

repository: percona/percona-backup-mongodb

repo_name: percona/percona-backup-mongodb


text:
package main

import (
	"fmt"
	"github.com/jackmanlabs/bucket/jlog"
	"github.com/jackmanlabs/errors"
	"go/ast"
	"go/build"
	"go/parser"
	"go/token"
	"log"
	"regexp"
	"strings"
	"unicode"
)

func findDefinition(referringPackage, typeName string) (*DefinitionIntermediate, error) {

	pkgInfo := pkgInfos[referringPackage]
	typeName = strings.TrimPrefix(typeName, "*")
	importPaths := possibleImportPaths(pkgInfo, typeName)

	if len(importPaths) == 0 {
		log.Print("ERROR: Import paths not available for this type: ", typeName)
		jlog.Log(pkgInfo)
	}

	if len(importPaths) > 1 {
		log.Printf("WARNING: Multiple package candidates found for type (%s):", typeName)
		jlog.Log(importPaths)
	}

	if strings.Contains(typeName, ".") {
		index := strings.Index(typeName, ".") + 1
		typeName = typeName[index:]
	}

	for _, importPath := range importPaths {

		if importPath == "" {
			log.Print("Import path is blank!")
		}

		bpkg, err := build.Import(importPath, srcPath, 0)
		if err != nil {
			return nil, errors.Stack(err)
		}

		fset := token.NewFileSet()
		pkgs, err := parser.ParseDir(fset, bpkg.Dir, nil, parser.AllErrors|parser.ParseComments)
		if err != nil {
			return nil, errors.Stack(err)
		}

		for _, pkg := range pkgs {
			definitionVisitor := &DefinitionVisitor{
				Fset:     fset,
				TypeName: typeName,
			}

			ast.Walk(definitionVisitor, pkg)

			if definitionVisitor.Definition != nil {
				definition := definitionVisitor.Definition
				definition.PackageName = pkg.Name
				definition.PackagePath = importPath

				// If this definition is an enum (underlying type is primitive), then we assume it's an enum type that needs enum values.
				if isPrimitive, _, _ := IsPrimitive(definition.UnderlyingType); isPrimitive {
					values, err := findEnumValues(definition.PackagePath, definition.Name)
					if err != nil {
						return nil, errors.Stack(err)
					}
					definition.Enums = values
				}

				return definition, nil
			}
		}
	}

	return nil, nil
}

type DefinitionVisitor struct {
	Fset       *token.FileSet
	TypeName   string
	Definition *DefinitionIntermediate
}

func (this *DefinitionVisitor) Visit(node ast.Node) (w ast.Visitor) {
	/*
		Name          string
		PackageName   string
		PackagePath   string
		Members       []MemberIntermediate
		IsStruct      bool
		EmbeddedTypes []string
	*/

	if this.Fset == nil {
		log.Println("fset is nil.")
		return nil
	}

	switch t := node.(type) {

	case *ast.TypeSpec:
		if t.Name.String() == this.TypeName {
			this.Definition = &DefinitionIntermediate{
				Name:           t.Name.String(),
				Comment:        t.Comment.Text(),
				Documentation:  t.Doc.Text(),
				UnderlyingType: resolveTypeExpression(t.Type),
				Members:        make(map[string]SchemerDefiner),
			}
		} else {
			return nil
		}
	case *ast.Field:

		controlsDoc := parseOpenApiControls(t.Doc.Text())
		controlsComment := parseOpenApiControls(t.Comment.Text())

		controls := OpenApiControls{
			Ignore:     controlsDoc.Ignore || controlsComment.Ignore,
			Deprecated: controlsDoc.Deprecated || controlsComment.Deprecated,
		}

		if controls.Ignore {
			return nil
		}

		if this.Definition == nil {
			// Ignore fields that don't belong to our definition.
			return nil
		}

		if len(t.Names) > 1 {
			// On our test code base, this was never printed.
			log.Print("WARNING: Multiple names discovered.")
		}

		// Handle embedded structs.
		if len(t.Names) == 0 {
			//ast.Fprint(os.Stdout, this.Fset, t, nil)

			if this.Definition.EmbeddedTypes == nil {
				this.Definition.EmbeddedTypes = make([]string, 0)
			}
			embedded := resolveTypeExpression(t.Type)
			this.Definition.EmbeddedTypes = append(this.Definition.EmbeddedTypes, embedded)
			return nil
		}

		name := t.Names[0].String()

		// Ignore fields that are not exported.
		name_ := []rune(name)
		if unicode.IsLower(name_[0]) {
			return nil
		}

		var (
			jsonName      string
			jsonOmitEmpty bool
			validations   ValidationMap
		)

		if t.Tag != nil {
			jsonName, jsonOmitEmpty = parseJsonInfo(t.Tag.Value)
			if jsonName == "-" {
				return nil
			}

			validations = parseValidateTag(t.Tag.Value)
		} else {
			validations = make(ValidationMap)
		}

		var desc string = parseMemberDescription(t.Doc.Text())
		if desc == "" {
			desc = parseMemberDescription(t.Comment.Text())
		}

		goType := resolveTypeExpression(t.Type)

		var member SchemerDefiner

		if isMap, k, v := IsMap(goType); isMap {
			keyType := &MemberIntermediate{
				Type:        k,
				Name:        name,
				Validations: validations,
			}

			valueType := &MemberIntermediate{
				Type:        v,
				Name:        name,
				Validations: validations,
			}

			member = &MapIntermediate{
				Name:          name,
				Type:          goType,
				JsonName:      jsonName,
				JsonOmitEmpty: jsonOmitEmpty,
				ValueType:     valueType,
				KeyType:       keyType,
				Description:   desc,
				Validations:   validations,
				Deprecated:    controls.Deprecated,
			}

		} else if isSlice, v := IsSlice(goType); isSlice {
			valueType := &MemberIntermediate{
				Type:        v,
				Name:        name,
				Validations: validations,
			}

			member = &SliceIntermediate{
				Name:          name,
				Type:          goType,
				JsonName:      jsonName,
				JsonOmitEmpty: jsonOmitEmpty,
				ValueType:     valueType,
				Description:   desc,
				Validations:   validations,
				Deprecated:    controls.Deprecated,
			}
		} else {
			member = &MemberIntermediate{
				Type:          goType,
				Name:          name,
				JsonName:      jsonName,
				JsonOmitEmpty: jsonOmitEmpty,
				Description:   desc,
				Validations:   validations,
				Deprecated:    controls.Deprecated,
			}
		}

		this.Definition.Members[name] = member

		return nil

	case *ast.FuncDecl:
		// Ignore function declarations.
		return nil
	case *ast.ImportSpec:
		// Ignore import declarations.
		return nil
	case nil:
	default:
		//log.Printf("unexpected type %T\n", t) // %T prints whatever type t has
	}

	return this
}

func resolveTypeExpression(expr ast.Expr) string {

	switch t := expr.(type) {
	case *ast.StarExpr:
		return "*" + resolveTypeExpression(t.X)
	case *ast.ArrayType:
		return "[]" + resolveTypeExpression(t.Elt)
	case *ast.Ident:
		return t.Name
	case *ast.SelectorExpr:
		return resolveTypeExpression(t.X) + "." + t.Sel.Name
	case *ast.MapType:
		return fmt.Sprintf("map[%s]%s", resolveTypeExpression(t.Key), resolveTypeExpression(t.Value))
	case *ast.InterfaceType:
		return "interface{}"
	case *ast.StructType:
		return "struct"
	default:
		return fmt.Sprintf("Unknown<%T>", t)
	}

}

func parseJsonInfo(s string) (string, bool) {
	rxJson := regexp.MustCompile(`json:"([^"]+)"`)

	if !rxJson.MatchString(s) {
		return "", false
	}

	matches := rxJson.FindStringSubmatch(s)
	words := strings.Split(matches[1], ",")

	name := words[0]
	if len(words) == 1 {
		return name, false
	}

	for _, word := range words[1:] {
		if word == "omitempty" {
			return name, true
		}
	}

	return name, false
}

func parseMemberDescription(s string) string {

	if s == "" {
		return ""
	}

	rxDesc := regexp.MustCompile(`@(?i:desc)\s+"?([^"]+)"?`)

	if !rxDesc.MatchString(s) {
		return ""
	}

	matches := rxDesc.FindStringSubmatch(s)

	return matches[1]
}

func parseValidateTag(s string) map[string]string {
	rxValidate := regexp.MustCompile(`validate:"([^"]+)"`)

	validations := make(map[string]string)

	if !rxValidate.MatchString(s) {
		return validations
	}

	matches := rxValidate.FindStringSubmatch(s)

	expressions := strings.Split(matches[1], ",")
	for _, expression := range expressions {

		parts := strings.Split(expression, "=")
		k := parts[0]
		v := ""

		if len(parts) > 1 {
			v = parts[1]
		}

		validations[k] = v

	}

	return validations

}

type OpenApiControls struct {
	Ignore     bool
	Deprecated bool
}

func parseOpenApiControls(s string) OpenApiControls {

	var controls OpenApiControls

	rxIgnore := regexp.MustCompile(`@(?i:ignore)`)
	rxDeprecated := regexp.MustCompile(`@(?i:deprecated)`)

	if rxIgnore.MatchString(s) {
		controls.Ignore = true
	}

	if rxDeprecated.MatchString(s) {
		controls.Deprecated = true
	}

	return controls
}

repository: emssoftware/swaggogen

repo_name: emssoftware/swaggogen


text:
@inproceedings{alt-etal-2019-fine,
    title = "Fine-tuning Pre-Trained Transformer Language Models to Distantly Supervised Relation Extraction",
    author = {Alt, Christoph  and
      H{\"u}bner, Marc  and
      Hennig, Leonhard},
    booktitle = "Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics",
    month = jul,
    year = "2019",
    address = "Florence, Italy",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/P19-1134",
    pages = "1388--1398",
}

branch_name: refs/heads/src


text:
package cmd

import (
	"errors"
	"fmt"
	"log"
	"math/big"
	"strconv"

	"github.com/Dev43/payment-channel/channel"

	"github.com/spf13/cobra"
)

// Nonce flag
var Nonce string

func init() {
	// open
	channelCmd.AddCommand(openCmd)

	// sign
	signCmd.Flags().StringVarP(&Nonce, "nonce", "n", "0", "Nonce to use")
	signCmd.MarkFlagRequired("nonce")
	channelCmd.AddCommand(signCmd)

	// verify
	channelCmd.AddCommand(verifyCmd)

	// close
	channelCmd.AddCommand(closeCmd)

	// close
	channelCmd.AddCommand(challengeCmd)

	// finalize
	channelCmd.AddCommand(finalizeCmd)

	// rootCmd
	rootCmd.AddCommand(channelCmd)

}

var channelCmd = &cobra.Command{
	Use:   "channel",
	Short: "Channel functions",
	Long:  `All channel functions`,
	PersistentPostRun: func(cmd *cobra.Command, args []string) {
		c, err := channel.NewChannel()
		if err != nil {
			log.Fatal(err)
		}
		c.Info()
		c.Balance()
	},
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("You need to give me arguments")
	},
}

var openCmd = &cobra.Command{
	Use:   "open [value]",
	Short: "Open a payment channel between Alice and Bob",
	Args:  cobra.MinimumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		value, ok := new(big.Int).SetString(args[0], 10)
		if !ok {
			log.Fatal(errors.New("Could not set the string inputted to a big.Int"))
		}
		c, err := channel.NewChannel()
		if err != nil {
			log.Fatal(err)
		}
		err = c.Open(value)
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println("Payment channel successfully opened")
	},
}

var signCmd = &cobra.Command{
	Use:   "sign [value]",
	Short: "Signs messages with a specific value attached to it",
	Args:  cobra.MinimumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		// the first argument is the amount to sign
		// can change the nonce if needed
		value, ok := new(big.Int).SetString(args[0], 10)
		if !ok {
			log.Fatal(errors.New("Could not set the string inputted to a big.Int"))
		}
		nonce, ok := new(big.Int).SetString(Nonce, 10)
		if !ok {
			log.Fatal(errors.New("Could not set the string inputted to a big.Int"))
		}
		c, err := channel.NewChannel()
		if err != nil {
			log.Fatal(err)
		}
		err = c.ValidateNonce(nonce)
		if err != nil {
			log.Fatal(err)
		}
		err = c.CreateSignatures(value, nonce)
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println("Signatures verified")
	},
}

// TO DO, ask the user which signature to verify
var verifyCmd = &cobra.Command{
	Use:   "verify",
	Short: "verifies the messages that are stored",
	Run: func(cmd *cobra.Command, args []string) {
		c, err := channel.NewChannel()
		if err != nil {
			log.Fatal(err)
		}
		err = c.VerifyMessages()
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println("Signatures verified!")
	},
}

var closeCmd = &cobra.Command{
	Use:   "close [signature index]",
	Short: "closes the payment channel",
	Run: func(cmd *cobra.Command, args []string) {
		// the first argument is the amount to sign
		// can change the nonce if needed
		c, err := channel.NewChannel()
		if err != nil {
			log.Fatal(err)
		}
		if len(args) > 0 {
			index, err := strconv.ParseInt(args[0], 10, 32)
			if err != nil {
				log.Fatal(err)
			}
			err = c.Close(int(index))
			if err != nil {
				log.Fatal(err)
			}
		} else {
			err = c.Close(-1)
			if err != nil {
				log.Fatal(err)
			}
		}

		fmt.Println("Channel successfully closed")
	},
}

var challengeCmd = &cobra.Command{
	Use:       "challenge [from]",
	Short:     "challenges the payment channel",
	Long:      "challenges the payment channel, from can either be alice or bob",
	ValidArgs: []string{"alice", "bob"},
	Args:      cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		// the first argument is the amount to sign
		// can change the nonce if needed
		c, err := channel.NewChannel()
		if err != nil {
			log.Fatal(err)
		}
		err = c.Challenge(args[0])
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println("Channel successfully challenged")
	},
}

var finalizeCmd = &cobra.Command{
	Use:   "finalize",
	Short: "finalizes the payment channel",
	Run: func(cmd *cobra.Command, args []string) {
		// the first argument is the amount to sign
		// can change the nonce if needed
		c, err := channel.NewChannel()
		if err != nil {
			log.Fatal(err)
		}
		err = c.Finalize()
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println("Channel successfully finalized")
	},
}


text:
DESCRIPTION = "Linux kernel for the R-Car Generation 3 based board"

require include/avb-control.inc
require include/iccom-control.inc
require recipes-kernel/linux/linux-yocto.inc
require include/cas-control.inc
require include/adsp-control.inc

FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}/:"
COMPATIBLE_MACHINE = "salvator-x|h3ulcb|m3ulcb|m3nulcb|ebisu"

RENESAS_BSP_URL = " \
    git://github.com/renesas-rcar/linux-bsp.git"
BRANCH = "v4.14.75-ltsi/rcar-3.9.9"
SRCREV = "4d2a32e5d314e2c77346f13e8736e97ca3e1b90b"

SRC_URI = "${RENESAS_BSP_URL};protocol=git;nocheckout=1;branch=${BRANCH}"

LINUX_VERSION ?= "4.14.75"
PV = "${LINUX_VERSION}+git${SRCPV}"
PR = "r1"

# For generating defconfig
KCONFIG_MODE = "--alldefconfig"
KBUILD_DEFCONFIG = "defconfig"

SRC_URI_append = " \
    file://touch.cfg \
    ${@oe.utils.conditional("USE_AVB", "1", " file://usb-video-class.cfg", "", d)} \
"

# Add python3 support to fix Perf build failure
# Add patch to build perf with new libbfd
SRC_URI_append = " \
    file://0001-perf-tools-Add-Python-3-support.patch \
    file://Make-perf-able-to-build-with-latest-libbfd.patch \
"

# Fix patch for Weston 8.0.0 issue
SRC_URI_append = " \
    file://0001-drm-rcar-du-Set-primary-plane-zpos-immutably-at-init.patch \
"

# Enable RPMSG_VIRTIO depend on ICCOM
SUPPORT_ICCOM = " \
    file://0001-rpmsg-Add-message-to-be-able-to-configure-RPMSG_VIRT.patch \
    file://iccom.cfg \
"

SRC_URI_append = " \
    ${@oe.utils.conditional("USE_ICCOM", "1", "${SUPPORT_ICCOM}", "", d)} \
"

# Add SCHED_DEBUG config fragment to support CAS
SRC_URI_append = " \
    ${@oe.utils.conditional("USE_CAS", "1", " file://capacity_aware_migration_strategy.cfg", "",d)} \
"

# Add ADSP ALSA driver
SUPPORT_ADSP_ASOC = " \
    file://0001-ADSP-add-document-for-compatible-string-renesas-rcar.patch \
    file://0002-ADSP-add-ADSP-sound-driver-source.patch \
    file://0003-ADSP-add-build-for-ADSP-sound-driver.patch \
    file://0004-ADSP-integrate-ADSP-sound-for-H3-M3-M3N-board.patch \
    file://0005-ADSP-integrate-ADSP-sound-for-E3-board.patch \
    file://0006-ADSP-remove-HDMI-support-from-rcar-sound.patch \
    file://adsp.cfg \
"

SRC_URI_append = " \
    ${@oe.utils.conditional("USE_ADSP", "1", "${SUPPORT_ADSP_ASOC}", "", d)} \
"

# Install USB3.0 firmware to rootfs
USB3_FIRMWARE_V2 = "https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/plain/r8a779x_usb3_v2.dlmem;md5sum=645db7e9056029efa15f158e51cc8a11"
USB3_FIRMWARE_V3 = "https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/plain/r8a779x_usb3_v3.dlmem;md5sum=687d5d42f38f9850f8d5a6071dca3109"

SRC_URI_append = " \
    ${USB3_FIRMWARE_V2} \
    ${USB3_FIRMWARE_V3} \
    ${@bb.utils.contains('MACHINE_FEATURES','usb3','file://usb3.cfg','',d)} \
"

# W/A Fix build issue with Linux v4.14
SRC_URI_append = " \
    file://0001-arm64-bpf-correct-broken-uapi-for-BPF_PROG_TYPE_PERF.patch \
"

do_download_firmware () {
    install -m 755 ${WORKDIR}/r8a779x_usb3_v*.dlmem ${STAGING_KERNEL_DIR}/firmware
}

addtask do_download_firmware after do_configure before do_compile


text:
package log

import (
	"fmt"
	"time"
)

type LogLevel string

const (
	LInfo    LogLevel = "INFO"
	LDebug   LogLevel = "DEBUG"
	LWarning LogLevel = "WARNING"
	LError   LogLevel = "ERROR"
)

var (
	green   = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
	white   = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
	yellow  = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
	red     = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
	blue    = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
	magenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
	cyan    = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
	reset   = string([]byte{27, 91, 48, 109})
)

func colorForLevel(level LogLevel) string {
	switch level {
	case LError:
		return red
	case LWarning:
		return yellow
	case LInfo:
		return cyan
	case LDebug:
		return magenta
	default:
		return white
	}
}

func doLog(level LogLevel, format string, args ...interface{}) {
	fmt.Printf("%v |%s %s %s| %s\n",
		time.Now().Format("2006/01/02 - 15:04:05"),
		colorForLevel(level), level, reset,
		fmt.Sprintf(format, args...))
}

func Error(format string, args ...interface{}) {
	doLog(LError, format, args...)
}

func Warning(format string, args ...interface{}) {
	doLog(LWarning, format, args...)
}

func Info(format string, args ...interface{}) {
	doLog(LInfo, format, args...)
}

func Debug(format string, args ...interface{}) {
	doLog(LDebug, format, args...)
}

repository: gfronza/porthos-go

repo_name: gfronza/porthos-go


text:
package kernal

import (
	"context"
	"encoding/json"
	"github.com/coreos/etcd/clientv3"
	"time"
)

const (
	config_prefix      = "/config/"
	global_config_name = "__global__"
)

type global_config struct {
	Env        string
	Log_path   string
	Jaeger_url string
}

func _watch_config(sname string, c interface{}, init_chann *chan int) {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{ETCD_SERVER},
		DialTimeout: 2 * time.Second,
	})
	ErrorPanic(err)
	defer cli.Close()

	ctx := context.TODO()

	// 先获取一次解析配置
	resp, err := cli.Get(ctx, config_prefix+sname)
	if err != nil {
		panic(err)
	}
	for _, ev := range resp.Kvs {
		// Debug(ctx, "%s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
		// Debug(ctx, "ev.Value: %s", ev.Value)
		/*err = */
		json.Unmarshal(ev.Value, c)
		/*if err != nil {
			Error(ctx, "[_watch_config] err: %+v", err)
		}*/
		*init_chann <- 0
	}

	// 监控key的变化
	wcli := clientv3.NewWatcher(cli)

	rch := wcli.Watch(ctx, config_prefix+sname, clientv3.WithPrefix())

	for wresp := range rch {
		for _, ev := range wresp.Events {
			// Debug(ctx, "%s %q : %q", ev.Type, ev.Kv.Key, ev.Kv.Value)
			/*err = */
			json.Unmarshal(ev.Kv.Value, c)
			/*if err != nil {
				Error(ctx, "[_watch_config] err: %+v", err)
			}*/
		}
	}
}

func WatchConfig(sname string, c interface{}) {
	init_chan := make(chan int)
	go _watch_config(sname, c, &init_chan)

	<-init_chan
}

repository: loveCupid/dipamkara

repo_name: loveCupid/dipamkara


text:
inherit esw deploy

ESW_COMPONENT_SRC = "/lib/sw_services/xilnvm/examples/"

DEPENDS += "xilnvm"

do_configure:prepend() {
    (
    cd ${S}
    lopper ${DTS_FILE} -- baremetallinker_xlnx.py ${ESW_MACHINE} ${S}/${ESW_COMPONENT_SRC}
    install -m 0755 *.cmake ${S}/${ESW_COMPONENT_SRC}/
    )
}

ESW_CUSTOM_LINKER_FILE ?= "None"
EXTRA_OECMAKE = "-DCUSTOM_LINKER_FILE=${@d.getVar('ESW_CUSTOM_LINKER_FILE')}"

do_install() {
    install -d ${D}/${base_libdir}/firmware
    install -m 0755  ${B}/*.elf ${D}/${base_libdir}/firmware
}

do_deploy() {
    install -d ${DEPLOYDIR}/${BPN}/
    install -Dm 0644 ${WORKDIR}/package/${base_libdir}/firmware/*.elf ${DEPLOYDIR}/${BPN}/
}
addtask deploy before do_build after do_package

FILES:${PN} = "${base_libdir}/firmware/*.elf"

repository: Xilinx/meta-xilinx

repo_name: Xilinx/meta-xilinx

gha_language: C


text:
@inproceedings{varfolomeev2017qm-mm87098566,
 author = {Коц, Е. Д. and Хренова, М. Г. and Лущекина, С. В. and Варфоломеев, С. Д. and Немухин, А. В.},
 booktitle = {IIX Международный конгресс \flqqБиотехнологии: состояние и перспективы развития\frqq Москва, 20-22 февраля 2017},
 language = {russian},
 publisher = {Москва},
 title = {QM-MM описание каталитических циклов в ферментативном катализе},
 year = {2017}
}

repository: polyakoviv/LCC

repo_name: polyakoviv/LCC


text:
package main

import (
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	rj "github.com/bottlenose-inc/rapidjson" // faster json handling
)

// SendErrorResponse sends a response with the provided error message and status code.
func SendErrorResponse(w http.ResponseWriter, message string, status int) {
	errorsCounter.Inc()
	errorJson := rj.NewDoc()
	defer errorJson.Free()
	errorCt := errorJson.GetContainerNewObj()
	errorCt.AddValue("error", message)

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	_, err := w.Write(errorJson.Bytes())
	if err != nil {
		logger.Error("Error writing response: "+err.Error(), map[string]string{"error": errorJson.String()})
	}
}

// GetRequests is a generic function that parses properly formatted requests to an augmentation.
// It ensures the correct Content-Type header is provided and ensures the request is properly
// formatted. Requests are also truncated to BODY_LIMIT_BYTES to avoid huge requests causing problems.
func GetRequests(w http.ResponseWriter, r *http.Request) (*rj.Doc, error) {
	var emptyMap *rj.Doc

	// Send error response if incorrect Content-Type is provided
	if r.Header.Get("Content-Type") != "application/json" {
		invalidRequestsCounter.Inc()
		logger.Warning("Client request did not set Content-Type header to application/json", map[string]string{"Content-Type": r.Header.Get("Content-Type")})
		SendErrorResponse(w, "Content-Type must be set to application/json", http.StatusBadRequest)
		return emptyMap, errors.New("Content-Type must be set to application/json")
	}

	// Read body up to size of BODY_LIMIT_BYTES
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, BODY_LIMIT_BYTES))
	if err != nil {
		logger.Error("Error reading request body: " + err.Error())
		SendErrorResponse(w, "Error reading request body", http.StatusInternalServerError)
		return emptyMap, err
	}
	if err := r.Body.Close(); err != nil {
		logger.Error("Error closing body: " + err.Error())
		SendErrorResponse(w, "Error reading request body", http.StatusInternalServerError)
		return emptyMap, err
	}

	// Parse request JSON
	requestJson, err := rj.NewParsedJson(body)
	if err != nil {
		invalidRequestsCounter.Inc()
		logger.Warning("Client request was invalid JSON: "+err.Error(), map[string]string{"body": string(body)})
		SendErrorResponse(w, "Unable to parse request - invalid JSON detected", http.StatusBadRequest)
		requestJson.Free()
		return emptyMap, err
	}

	return requestJson, err
}

// HandlerWrapper is "wrapped" around all handlers to allow generation of
// common metrics we want for every valid api call.
func HandlerWrapper(handler http.HandlerFunc) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		http.HandlerFunc(handler).ServeHTTP(w, r)
		totalRequestsCounter.Inc()
		requestDurationCounter.Add(time.Since(start).Seconds() / 1000)
	})
}

// NotFound sends a 404 response.
func NotFound(w http.ResponseWriter, r *http.Request) {
	invalidRequestsCounter.Inc()
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusNotFound)
	_, err := w.Write(notFound)
	if err != nil {
		// Should not run into this error...
		logger.Error("Error encoding 404 response: " + err.Error())
	}
}

// Usage sends the usage information response.
func Usage(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_, err := w.Write(usage)
	if err != nil {
		// Should not run into this error...
		logger.Error("Error encoding usage response: " + err.Error())
	}
}

// detect language
func LanguageDetectorHandler(w http.ResponseWriter, r *http.Request) {
	requestJson, err := GetRequests(w, r)
	if err != nil {
		incUnsuccessfulCounter()
		return
	}
	defer requestJson.Free()
	requestCt := requestJson.GetContainer()
	if requestCt.GetType() == rj.TypeNull {
		return
	}
	requestsCt, err := requestCt.GetMember("request")
	if err != nil {
		invalidRequestsCounter.Inc()
		logger.Warning("Client request was invalid JSON: " + err.Error())
		SendErrorResponse(w, "Unable to parse request - invalid JSON detected", http.StatusBadRequest)
		return
	}
	requests, _, err := requestsCt.GetArray()

	respCode := http.StatusOK
	responses := rj.NewDoc()
	defer responses.Free()
	responsesCt := responses.GetContainerNewObj()
	responsesArray := responses.NewContainerArray()
	responsesCt.AddMember("response", responsesArray)
	responsesArray, _ = responsesCt.GetMember("response")
	for _, request := range requests {
		response := responses.NewContainerObj()
		text, err := request.GetMember("text")

		if err != nil {
			incUnsuccessfulCounter()
			response.AddValue("error", "Missing text key")
			respCode = http.StatusBadRequest
			err = responsesArray.ArrayAppendContainer(response)
			if err != nil {
				SendErrorResponse(w, err.Error(), http.StatusInternalServerError)
				return
			}
			continue
		}

		textStr, err := text.GetString()
		textStr = StripExtras(textStr)

		code := Detect_language(textStr)
		name, found := KnownLanguages[code]

		if !found {
			name = "Unknown"
			respCode = http.StatusNonAuthoritativeInfo
			logger.Warning("Unknown response language code: " + code)
		}

		response.AddValue("iso6391code", code)
		response.AddValue("name", name)

		incLanguageCount(name)

		// Append newly generated response to responses
		err = responsesArray.ArrayAppendContainer(response)
		if err != nil {
			incUnsuccessfulCounter()
			SendErrorResponse(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// Call logProcessed for every object that gets processed
		incSuccessfulCounter()
		logProcessed()
	}

	// Send response
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(respCode)
	_, err = w.Write(responses.Bytes())
	if err != nil {
		// Should not run into this error...
		logger.Error("Error encoding error response: "+err.Error(), map[string]string{"response": responses.String()})
	}
}

func HasPrefix(word string, prefixes []string) bool {
	for _, prefix := range prefixes {
		if strings.HasPrefix(word, prefix) {
			return true
		}
	}
	return false
}

// remove mentions and links from text, as these can skew detection
func StripExtras(text string) string {
	var result string

	prefixes := []string{"@", "http"}

	for _, word := range strings.Fields(text) {
		if !HasPrefix(word, prefixes) {
			result = result + word + " "
		}
	}

	return result
}

repository: bottlenose-inc/language-detector

repo_name: bottlenose-inc/language-detector


text:
#include "Connect4GameMove.h"

Connect4GameMove::Connect4GameMove(int move) :
	mMove(move)
{
}

Connect4GameMove::~Connect4GameMove()
{
}

int Connect4GameMove::GetMove() const
{
	return mMove;
}

ostream& Connect4GameMove::ToString(ostream & ostr) const
{
	ostr << mMove;
	return ostr;
}

bool operator==(const Connect4GameMove & lhs, const Connect4GameMove & rhs)
{
	return lhs.mMove == rhs.mMove;
}

repository: YeranLee/mcts-cpp

repo_name: YeranLee/mcts-cpp

extension: cpp


text:
@book{cn1,
  title={{编译原理}},
  author={{Alfred V. Aho and Monica S.Lam and Ravi Sethi and Jeffrey D. Ullman}},
  publisher={{机械工业出版社}},
  year={2009}
}

@misc{cn2,
  title={入门masm32编写简单汇编程序并做具体分析},
  author={{codesfirst}},
  howpublished="\url{https://blog.csdn.net/codes_first/article/details/78279641}"
}
@misc{cn3,
  title={C语言},
  author={ 百度百科},
  howpublished="\url{https://baike.baidu.com/item/c%E8%AF%AD%E8%A8%80}"
}
@misc{cn4,
  title={How does a compiler convert high level programming languages into assembly?},
  author={ Jan Christian Meyer},
  howpublished="\url{http://www.quora.com/Computer-Science/How-does-a-compiler-convert-high-level-programming-languages-into-assembly}"
}


text:
SECTION = "devel/chicken"
DESCRIPTION = "SRFI 12 Condition Utilities"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://condition-utils.meta;md5=373003b7aed90f4e744a02ae916992ad"
DEPENDS_append_class-cross = " chicken-egg-setup-helper-cross chicken-egg-check-errors-cross"
DEPENDS_append_class-crosssdk = " chicken-egg-setup-helper-crosssdk chicken-egg-check-errors-crosssdk"
DEPENDS_append_class-nativesdk = " nativesdk-chicken-egg-setup-helper nativesdk-chicken-egg-check-errors chicken-egg-setup-helper-crosssdk chicken-egg-check-errors-crosssdk"
DEPENDS = " chicken-egg-setup-helper chicken-egg-check-errors chicken-egg-setup-helper-cross chicken-egg-check-errors-cross chicken-egg-condition-utils-cross"
RDEPENDS_${PN} = " chicken-egg-setup-helper chicken-egg-check-errors"

SRC_URI = "http://code.call-cc.org/egg-tarballs/4/condition-utils/condition-utils-${PV}.tar.gz"

SRC_URI[md5sum] = "d04197f1dbf38a25aa2f31ff6d5cb1a6"
SRC_URI[sha256sum] = "bb3ee11d59f209cbc83e6869c4b4bba58ec4fca68cd69ff6c67f4770d5b94513"

S = "${WORKDIR}/condition-utils-${PV}"

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: OSSystems/meta-chicken

repo_name: OSSystems/meta-chicken


text:
if (COSA_IS_TOOLCHAIN_PROCESSED)
    return()
endif ()
set(COSA_IS_TOOLCHAIN_PROCESSED True)
set(CMAKE_SYSTEM_NAME Cosa)

# Cosa requires C++11 standard
set(CMAKE_CXX_STANDARD 11)

# Set compilers
set(CMAKE_C_COMPILER avr-gcc)
set(CMAKE_ASM_COMPILER avr-gcc)
set(CMAKE_CXX_COMPILER avr-g++)

# Include Cosa.cmake in module path
if (EXISTS ${CMAKE_CURRENT_LIST_DIR}/Platform/Cosa.cmake)
    message(STATUS "Setting module path with Cosa.cmake")
    set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_LIST_DIR})
endif ()

# Include system paths
if (UNIX)
    message(STATUS "Including Unix paths")
    include(Platform/UnixPaths)
    if (APPLE)
        message(STATUS "Including Darwin paths")
        list(APPEND CMAKE_SYSTEM_PREFIX_PATH ~/Applications
                /Applications
                /Developer/Applications
                /sw         # Fink
                /opt/local) # MacPorts
    endif ()
elseif (WIN32)
    message(STATUS "Including Windows paths")
    include(Platform/WindowsPaths)
endif ()

# Set platform path to Cosa and arduino-cmake
get_filename_component(COSA_TOOLCHAIN_ROOT_PATH ${CMAKE_CURRENT_LIST_DIR} DIRECTORY)
set(COSA_SDK_PATH ${COSA_TOOLCHAIN_ROOT_PATH}/cosa)
set(ARDUINO_CMAKE_PATH ${COSA_TOOLCHAIN_ROOT_PATH}/arduino-cmake/cmake)
message(STATUS "`cosa`          location: ${COSA_SDK_PATH}")
message(STATUS "`arduino-cmake` location: ${ARDUINO_CMAKE_PATH}")

repository: waterloop/wcosa

repo_name: waterloop/wcosa


text:
package server

import (
	"net/http"
	// "strconv"
	// "encoding/json"

	"github.com/sirupsen/logrus"
	"github.com/gin-gonic/gin"
	"github.com/coderun-top/coderun/src/model"
	"github.com/coderun-top/coderun/src/router/middleware/session"
	"github.com/coderun-top/coderun/src/store"
)

// func PostConf(c *gin.Context) {
// 	in := &model.Config{}
// 	err := c.Bind(in)
// 	if err != nil {
// 		c.String(http.StatusBadRequest, err.Error())
// 		return
// 	}
//
// 	confb := []byte(in.Data)
// 	sha := shasum(confb)
// 	config := &model.Config{
// 		Data:  in.Data,
// 		Hash:   sha,
// 	}
// 	err = store.FromContext(c).ConfigCreate(config)
// 	if err != nil {
// 		c.String(500, err.Error())
// 		return
// 	}
//
// 	c.JSON(200, config)
// }

func GetPipelines(c *gin.Context) {
	repo := session.Repo(c)
	conf, err := store.FromContext(c).ConfigRepoFind(repo)
	if err != nil {
		c.String(404, "Cannot find pipelines. %s", err)
		return
	}
	c.JSON(200, conf)
}

func PutPipeline(c *gin.Context) {
	in := &model.Config{}

	err := c.Bind(in)
	if err != nil {
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	repo, err := store.GetRepo(c, in.RepoID)
	if err != nil {
		logrus.Errorf("Cannot find repo by repoID: %s, %s", in.RepoID, err)
		c.String(http.StatusBadRequest, err.Error())
		return
	}

	if in.File == 1 {
		_, err = yamlParseLinter(in.Data, repo.IsTrusted)
		if err != nil {
			c.String(400, "yaml parse error: %s", err.Error())
			return
		}
	}

	confb := []byte(in.Data)
	sha := shasum(confb)
	config := &model.Config{
		ID:                  in.ID,
		RepoID:              in.RepoID,
		Data:                in.Data,
		Hash:                sha,
		FilePath:            in.FilePath,
		File:                in.File,
		AgentPublic:         in.AgentPublic,
		AgentFilter:         in.AgentFilter,
		ConfigType:          in.ConfigType,
		StepBuild:           in.StepBuild,
		StepUnitTest:        in.StepUnitTest,
		StepIntegrationTest: in.StepIntegrationTest,
		StepDeploy:          in.StepDeploy,
	}

	err = store.FromContext(c).ConfigUpdate(config)
	if err != nil {
		c.String(500, err.Error())
		return
	}

	c.JSON(200, config)
}

// func DeleteConf(c *gin.Context) {
// 	repo := session.Repo(c)
// 	conf, err := store.FromContext(c).ConfigRepoFind(repo)
// 	if err != nil {
// 		c.String(404, "Cannot find conf. %s", err)
// 		return
// 	}
// 	c.JSON(200, conf)
// }

repository: coderun-top/coderun

repo_name: coderun-top/coderun


text:
@misc{teuber2020incremental,
  title={An Incremental Abstraction Scheme for Solving Hard SMT-Instances over Bit-Vectors},
  author={Samuel Teuber and Marko Kleine Büning and Carsten Sinz},
  year={2020},
  eprint={2008.10061},
  archivePrefix={arXiv},
  primaryClass={cs.LO}
}

repository: samysweb/www-teuberdev

repo_name: samysweb/www-teuberdev


text:
//
// Texture.hpp for  in /home/trambe_m/tek2/cpp/cpp_indie_studio
//
// Made by Manuel Trambert
// Login   <trambe_m@epitech.net>
//
// Started on  Fri Jun  3 15:15:28 2016 Manuel Trambert
// Last update Sun Jun  5 16:39:37 2016 benjamin rascol
//

#ifndef __TEXTURE_HPP__
#define __TEXTURE_HPP__

#include <irrlicht.h>
#include <utility>
#include "CFGParser.hpp"

namespace bm
{
  enum  TEXTURE_NAME {
    BLOOD,
    PLAYER1,
    PLAYER2,
    PLAYER3,
    PLAYER4,
    HUD_RANGE,
    HUD_BOMB,
    HUD_SPEED,
    BREAKABLE,
    UNBREAKABLE,
    GROUND,
    BONUSRANGE,
    BONUSMAXBOMB,
    BONUSSPEED,
    BOMB,
    ROBOT_TEXT,
    MARVIN_TEXT,
    POTATOR_TEXT,
    SQUELETTE_TEXT,
    VICTORY,
    DEFEAT,
    PAUSE,
  };

  enum  MESH_NAME {
    NINJA,
    BOMBMESH,
    ROBOT,
    MARVIN,
    POTATOR,
    SQUELETTE,
  };

  const std::unordered_map<int, std::string> TAB_CONFIG_TEXTURE = {
    {BLOOD, "Blood"},
    {PLAYER1, "Player1"},
    {PLAYER2, "Player2"},
    {PLAYER3, "Player3"},
    {PLAYER4, "Player4"},
    {HUD_RANGE, "HUD_BonusRange"},
    {HUD_BOMB, "HUD_BonusBomb"},
    {HUD_SPEED, "HUD_BonusSpeed"},
    {BREAKABLE, "Breakable"},
    {UNBREAKABLE, "Unbreakable"},
    {GROUND, "Ground"},
    {BONUSRANGE, "BonusRange"},
    {BONUSMAXBOMB, "BonusNbBomb"},
    {BONUSSPEED, "BonusMoveSpeed"},
    {BOMB, "Bomb"},
    {ROBOT_TEXT, "Robot"},
    {MARVIN_TEXT, "Marvin"},
    {POTATOR_TEXT, "Potator"},
    {SQUELETTE_TEXT, "Squelette"},
    {VICTORY, "Victory"},
    {DEFEAT, "Defeat"},
    {PAUSE, "Pause"},
  };

  const std::unordered_map<int, std::string> TAB_CONFIG_MESH = {
    {NINJA, "Ninja"},
    {BOMBMESH, "Bomb"},
    {ROBOT, "Robot"},
    {MARVIN, "Marvin"},
    {POTATOR, "Potator"},
    {SQUELETTE, "Squelette"},
  };

  class Texture
  {
  public:
    Texture();
    ~Texture();
    std::unordered_map<std::string, std::string>	getTabPathTexture() const;
    std::unordered_map<std::string, std::string>	getTabPathMesh() const;
    irr::video::ITexture				*getTexture(const enum TEXTURE_NAME) const;
    irr::scene::IAnimatedMesh				*getMesh(const enum MESH_NAME) const;
    void						setDriver(irr::video::IVideoDriver *);
    void						setScene(irr::scene::ISceneManager*);
    void						loadTexture();
    void						loadMesh();

  private:
    irr::scene::ISceneManager					*_sceneManager;
    const std::string					_PATH_FILE_TEXTURE = "config/texture.cfg";
    const std::string					_PATH_FILE_MESH = "config/mesh.cfg";
    std::unordered_map<std::string, std::string>	        _TAB_PATH_TEXTURE;
    std::unordered_map<std::string, std::string>	        _TAB_PATH_MESH;
    irr::video::IVideoDriver					*_driver;
    std::unordered_map<int, irr::video::ITexture*>		_TAB_TEXTURE;
    std::unordered_map<int, irr::scene::IAnimatedMesh*>		_TAB_MESH;
  };
};

#endif /* !TEXTURE_HPP_ */

extension: hpp