text
stringlengths
11
4.05M
package di import ( "reflect" ) // newProviderGroup creates new group from provided key. func newProviderGroup(k id) *providerGroup { id := id{ Type: reflect.SliceOf(k.Type), // creates []<type> group } return &providerGroup{ id: id, pl: parameterList{}, } } // providerGroup type providerGroup struct { i...
package chain import ( "os" "time" "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/kv/codec" "github.com/iotaledger/wasp/packages/kv/collections" "github.com/iotaledger/wasp/packages/vm/core/eventlog" "github.com/iotaledger/wasp/tools/wasp-cli/log" ) func logCmd(args []str...
package server import ( "io" "net/http" "strconv" "github.com/empirefox/esecend/cerr" "github.com/empirefox/esecend/delivery" "github.com/empirefox/esecend/front" "github.com/gin-gonic/gin" ) func (s *Server) GetDelivery(c *gin.Context) { orderId, _ := strconv.ParseUint(c.Param("order_id"), 10, 64) if order...
package main import ( "fmt" "sort" "strconv" "strings" "time" ) func loadData(input string) []string { lines := []string{} for _, line := range strings.Split(input, "\n") { line = strings.TrimSpace(line) if line == "" { continue } lines = append(lines, line) } return lines } type action int cons...
package models import ( "sync" ) // SynchronizedMap is a map structure that can be shared // across go routines and threads. Both keys and values // are strings. type SynchronizedMap struct { data map[string]string mutex *sync.RWMutex } // NewSynchronizedMap creates a new empty SynchronizedMap func NewSynchroniz...
package main import ( "github.com/reiver/go-oi" "github.com/reiver/go-telnet" ) type client struct{ DSL []string } func (c client) CallTELNET(ctx telnet.Context, w telnet.Writer, r telnet.Reader) { for _, dsl := range c.DSL { oi.LongWrite(w, []byte(dsl)) } }
package main import ( "net/http" "fmt" ) func main() { http.HandleFunc("/",index) http.HandleFunc("/set",set) http.HandleFunc("/get",get) http.HandleFunc("/del",del) http.Handle("/favicon.ico",http.NotFoundHandler()) http.ListenAndServe(":8080",nil) } func index(w http.ResponseWriter,r *http.Request){ w....
package commandjsonio import ( "bytes" "context" "encoding/json" "time" ) // DefaultRunCommandJSONTimeout define default timeout duration for RunCommandJSON. const DefaultRunCommandJSONTimeout = time.Second * 10 // RunCommandJSON run given command and send JSON encoded inputRef into STDIN of command. // Output o...
package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { fm := make(map[int]*TreeNode) visited := make(map[int]bool) var dfs func(node *TreeNode) dfs = func(node *TreeNode) { if node.Left != nil { fm[node.Left.Val] = node ...
/* * Minio Cloud Storage, (C) 2016 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable la...
package app import ( "fmt" "github.com/gin-gonic/gin" "github.com/ikasamt/zapp/zapp" "google.golang.org/appengine" "google.golang.org/appengine/log" "google.golang.org/appengine/mail" ) func passwordResetSentHandler(c *gin.Context) {} func passwordResetCreateHandler(c *gin.Context) { ctx := appengine.NewCont...
package main import ( "fmt" ) type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func pathSum(root *TreeNode, sum int) [][]int { var ret [][]int var current []int if root == nil { return ret } tmp = root for tmp { } } func main() { }
package _501_Find_Mode_in_Binary_Search_Tree /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func findMode(root *TreeNode) []int { var ( ret = []int{} maxFreq int m = make(map[int]int) s = []*TreeNode{} ...
package log import ( "net/http" "time" ) // LoggingInterceptor is an HTTP logger which logs in similar format as NGINX type LoggingInterceptor struct { Timer Outputer } func (interceptor LoggingInterceptor) Handler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Reques...
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
package main import ( "bufio" "fmt" "os" "strconv" reversi "github.com/myoan/go-reversi" ) func readPosition() *reversi.Position { stdin := bufio.NewScanner(os.Stdin) fmt.Printf("X: ") stdin.Scan() xStr := stdin.Text() fmt.Printf("Y: ") stdin.Scan() yStr := stdin.Text() x, _ := strconv.Atoi(xStr) y, _ ...
package mdadm import ( "encoding/json" "fmt" "io/ioutil" "log" "os" "path/filepath" "strconv" "strings" ) // MdadmDeviceStruct struct type MdadmDeviceStruct struct { Name string } // RaidStats struct type RaidStats struct { Capability int64 // capability Dev string DiscardAlignment int...
// Esto es un comentario de línea, termina hasta el final de la línea // Los comentarios en línea se utilzan para documentar el código /* Esto es un comentario de bloque. Permite tener un comentario a través de varias líneas. */ /* Los comentarios de bloque se utilizan para comentar el código. Puede servir para...
package authentication import ( "fmt" "math/rand" "time" jwt "github.com/dgrijalva/jwt-go" "golang.org/x/crypto/bcrypt" ) /* //GenerateToken will create a JWT Token func GenerateToken(siteid string) (string, error) { mySigningKey := []byte(MyVenueJwtSecret) token := jwt.New(jwt.SigningMethodHS256) claims :...
package main import ( "fmt" "log" "net/url" "github.com/OctopusDeploy/go-octopusdeploy/octopusdeploy" ) func main() { apiURL, err := url.Parse("https://YourURL") if err != nil { log.Println(err) } APIKey := "API-YourAPIKey" spaceName := "Default" tagsetName := "MyTagset" // Get reference to space sp...
package hill import ( "errors" "github.com/mkamadeus/cipher/common/stringutils" ) func Encrypt(plain string, key string) (string, error) { plain = stringutils.Normalize(plain) key = stringutils.Normalize(key) if !isQuadratic(len(key)) { return "", errors.New("Key len are not quadratic") } keyMatrix := Buil...
package main func html() string { file := ` <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="bootstrap.min.css"> <link rel="stylesheet" href="home.css"> <script type="text/javascript" src="storage.json"></script> </head> <bo...
package router import ( "github.com/shimastripe/gouserapi/controllers" "github.com/gin-gonic/gin" ) func Initialize(r *gin.Engine) { api := r.Group("api") { //USER API api.GET("/users", controllers.GetUsers) api.GET("/users/:id", controllers.GetUser) api.POST("/users", controllers.CreateUser) api.PUT("...
package data import ( "encoding/json" "fmt" "testing" ) const jsonDoc = ` { "localhost": { "tag": "dev_latest", "vhost": "localhost.com" }, "development": { "tag": "dev_latest", "vhost": "dev.com" }, "other": 123, "release": { "DB": { "host": "localhost", "port": "5432" ...
package aws import ( "github.com/aws/aws-sdk-go/aws/endpoints" configv1 "github.com/openshift/api/config/v1" ) const ( // VolumeTypeGp2 is the type of EBS volume for General Purpose SSD gp2. VolumeTypeGp2 = "gp2" // VolumeTypeGp3 is the type of EBS volume for General Purpose SSD gp3. VolumeTypeGp3 = "gp3" ) /...
package glman import ( "tetra/internal/gl" ) var ( dynArray12 *Res // 4x3 float dynArray20 *Res // 4x5 float dynArray30 *Res // 9x3 float ) func bindDynArray12() { if dynArray12 == nil { dynArray12 = GenBuffer("*painter.dynArray12") } gl.BindBuffer(gl.ARRAY_BUFFER, dynArray12.ID()) DbgCheckError() gl.Buff...
package database import ( "testing" ) func TestMssqlVersion(t *testing.T) { version, err := MssqlVersion("127.0.0.1", 1433, "sandbox", "sandbox", "P@ssword") if err != nil { t.Error("failed") } else { t.Log(version) } }
package sql_test import ( "testing" "github.com/nim4/DBShield/dbshield/sql" ) func TestPattern(t *testing.T) { p := sql.Pattern("select * from X;") if len(p) < 4 { t.Error("Unexpected Pattern") } }
// Copyright 2015-2018 trivago N.V. // // 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 ...
package gatewaytest import ( "flag" "net" "testing" "time" "google.golang.org/grpc" "github.com/youtube/vitess/go/vt/discovery" "github.com/youtube/vitess/go/vt/tabletserver/grpcqueryservice" "github.com/youtube/vitess/go/vt/tabletserver/tabletconntest" "github.com/youtube/vitess/go/vt/vtgate/gateway" // ...
package trie import ( "bytes" "math/bits" "reflect" "sort" "github.com/openacid/errors" "github.com/openacid/low/bitmap" "github.com/openacid/low/bitstr" "github.com/openacid/low/bmtree" "github.com/openacid/low/sigbits" "github.com/openacid/must" "github.com/openacid/slim/encode" ) // subset of keys: key...
package pkgs import ( "fmt" "go/build" "io/fs" "os" "path/filepath" "strings" "sync" "github.com/charlievieth/buildutil" "github.com/charlievieth/fastwalk" ) // TODO: // 1. support modules with golang.org/x/mod/modfile // 2. parse the repos vendor/modules separately the // any vendor/modules dir/file ...
package main func convert(s string, numRows int) string { row := min6(len(s), numRows) table := make([]string, row) dir := 1 curIndex := 0 var res string if numRows == 1 { return s } for _, v := range s { table[curIndex] += string(v) if curIndex >= row-1 { dir = -1 } else if curIndex == 0 { dir =...
package main //import package import ( "fmt" "strconv" "net" "net/rpc" "net/http" "net/rpc/jsonrpc" "crypto/rand" "time" "encoding/json" "io/ioutil" ) //struct definitions type StockRequest struct { StockMap map[string]float64 } type StockResponse struct { TradeID string Symbol []string Pri...
package main import ( "bufio" "fmt" "io" "log" "os" "strconv" ) // Mass is the weight of something. type Mass int64 // FuelRequired compute the amount of fuel required to carry the given mass. // // It returns the Mass of the fuel required. func FuelRequired(m Mass) Mass { return m/3 - 2 } // TotalFuelRequir...
package dcmdata import ( "testing" "github.com/grayzone/godcm/ofstd" ) func TestNewDcmObject(t *testing.T) { cases := []struct { in_tag DcmTag in_length uint32 want *DcmObject }{ {DcmTag{}, 1, &DcmObject{length: 1, fTransferState: ERW_init, fTransferredBytes: 0, errorFlag: ofstd.EC_Normal}}, } ...
package captcha import ( "github.com/google/uuid" "github.com/mojocn/base64Captcha" "image/color" ) var store = base64Captcha.DefaultMemStore // 配置JsonBody json请求正文。 type configJsonBody struct { Id string CaptchaType string VerifyValue string DriverAudio *base64Captcha.DriverAudio DriverString *base64Captch...
package models import "gopkg.in/mgo.v2/bson" // Represents a movie, we uses bson keyword to tell the mgo driver how to name // the properties in mongodb document type Category struct { ID bson.ObjectId `bson:"_id" json:"id"` Category string `bson:"" json:"category"` Description string `bs...
package reda import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document05600101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:reda.056.001.01 Document"` Message *StandingSettlementInstructionV01 `xml:"StgSttlmInstr"` } func (d *Docum...
/* * Copyright 2018, CS Systemes d'Information, http://www.c-s.fr * * 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 requir...
package mysql import ( "database/sql" "github.com/Tanibox/tania-core/src/tasks/query" "github.com/gofrs/uuid" ) type ReservoirQueryMysql struct { DB *sql.DB } func NewReservoirQueryMysql(db *sql.DB) query.ReservoirQuery { return ReservoirQueryMysql{DB: db} } func (s ReservoirQueryMysql) FindReservoirByID(uid ...
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agre...
package muxxxer import ( "net/http" "regexp" "strings" ) type dispatcher struct { f func(http.ResponseWriter, *http.Request) } func (d *dispatcher) ServeHTTP(rw http.ResponseWriter, r *http.Request) { d.f(rw, r) } // Route is a Regular Expression for testing whether the current request's Url matches the Route....
package main import ( "encoding/json" "fmt" "github.com/labstack/echo" "github.com/unrolled/render" "html/template" "io/ioutil" "net/http" ) type Carousel struct { Shows []struct { Link string Image string } } type Media struct { Type string Metadata []struct { Url string Width int Heig...
package repository import ( "go-gin-start/app/ent" "go-gin-start/app/ent/user" "go-gin-start/app/util" ) type User struct{} /** * Get One Demo **/ func (User) GetOne(id int) (*ent.User, error) { // get entUser, err := util.DBC.User. Query(). Where(user.IDEQ(id)). First(util.Ctx) // err if err != nil ...
package graphql import ( "testing" ) func TestIsEqualType_SameReferenceAreEqual(t *testing.T) { if !isEqualType(String, String) { t.Fatalf("Expected same reference to be equal") } } func TestIsEqualType_IntAndFloatAreNotEqual(t *testing.T) { if isEqualType(Int, Float) { t.Fatalf("Expected GraphQLInt and Grap...
package main import ( "fmt" "sync" "time" ) var count = 0 var wg sync.WaitGroup var mutex sync.Mutex func test() { // 加锁 mutex.Lock() count++ fmt.Println("the count is : ", count) time.Sleep(time.Millisecond) wg.Done() // 解锁 mutex.Unlock() } func main() { for i := 0; i < 20; i++ { wg.Add(1) go test(...
package main import ( "flag" "fmt" "log" "math" "os" "os/exec" "path/filepath" "time" "github.com/cheggaaa/pb/v3" "github.com/dustin/go-humanize" homedir "github.com/mitchellh/go-homedir" "github.com/prologic/bitcask" ) var ( subdivisions = flag.Int("subdivisions", 10, "Slices per axis") tolerance =...
// Copyright 2022 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package _143_Reorder_List /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reorderList(head *ListNode) { reorderListWithStack(head) } func reorderListWithStack(head *ListNode) { var ( s = []int{} tmp = head flag bool ) if head == nil ...
/* * @lc app=leetcode.cn id=1886 lang=golang * * [1886] 判断矩阵经轮转后是否一致 */ // @lc code=start // package leetcode func rotate(mat [][]int) [][]int { n := len(mat) ret := make([][]int, n) for i := 0; i < n; i++ { ret[i] = make([]int, n) } for i := 0; i < n; i++ { for j := 0; j < n; j++ { ret[j][n-1-i] = ma...
package oidc_test import ( "bytes" "context" "io" "net/http" "net/url" "testing" "github.com/golang/mock/gomock" "github.com/ory/fosite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/valyala/fasthttp" "github.com/authelia/authelia/v4/internal/configuration/schema"...
/* Simple Cron. Every job runs in goroutine. */ // Patterns: // 12 - at 12 // 1,2,3 - at 1 or 2 or 3 // * - every hour/min // */15 - every 15 hours/min /* WEEKDAYS: Sunday = 0 Monday = 1 Tuesday Wednesday Thursday Friday Saturday MONTHS January = 0 February = 1 March April May June July August September October No...
package main import ( "bufio" "fmt" "io/ioutil" "log" "os" "os/exec" "runtime" "strings" "time" // TODO: trade log for logrus // log "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" ) const ( binName = "tree-spotter" namespace = "jan" helmFolder = "helm" dockerfile = "Dockerfile" ) type docker st...
// Copyright 2015 Walter Schulze // // 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...
package main import ( "bytes" "fmt" "github.com/go-playground/log/v8" ) // CustomHandler is your custom handler type CustomHandler struct { // whatever properties you need } // Log accepts log entries to be processed func (c *CustomHandler) Log(e log.Entry) { // below prints to os.Stderr but could marshal to ...
package appealUse import entity "github.com/Surafeljava/Court-Case-Management-System/Entity" type AppealRepositroy interface { Appeal(oppNum string) (*entity.Case, *entity.Opponent, *entity.Witness, *entity.Decision, []error) RelationForAppeal(oppNum string) (*entity.Relation, []error) CaseForAppeal(caseNum string...
package main import ( "fmt" "github.com/xackery/gosample/foo" ) func main() { fmt.Println(foo.Hello()) }
// Copyright 2013 The StudyGolang Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // http://studygolang.com // Author:polaris studygolang@gmail.com package logger import ( "config" "io" "log" "os" "time" ) var ( // 日志文件 info...
package database import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewEntClient(t *testing.T) { dbconn, _ := GetSqlDbConn(true) client, err := NewEntClient(dbconn) assert.Nil(t, err) assert.NotNil(t, client) }
package db import ( "bcdb/config" "bcdb/tool" "os" "sort" "sync" "time" "unsafe" ) type merge struct { db *Db runLock sync.Mutex } func newMerge(db *Db) *merge { merge := &merge{ db: db, } return merge } func (self *merge) Run(nums []int) { self.runLock.Lock() defer self.runLock.Unlock() if self.db...
package main import ( "fmt" "reflect" ) type Model interface { m() } type Company struct{} func (Company) m() { // do stuff } type Department struct{} func (*Department) m() { // do stuff } type User struct { CompanyA Company CompanyB *Company DepartmentA Department DepartmentB *Department } func...
package _94_Binary_Tree_Inorder_Traversal type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func inorderTraversal(root *TreeNode) []int { // return inorderTranversalRecursion(root) // return inorderTranversalUnrecursion(root) return inorderTranversalUnrecursionWithStack(root) } func inorderTra...
package main import ( "bytes" "image" "image/png" "reflect" "testing" "github.com/tc-hib/winres" ) func Test_exportedName(t *testing.T) { var ( pngBuf bytes.Buffer fakePng = []byte{0x89, 'P', 'N', 'G', 0xD, 0xA, 0x1A, 0xA, 0xFF} ) img := image.NewNRGBA(image.Rectangle{Min: image.Point{0, 0}, Max: imag...
package k8sml type CloudProvider interface { GetID() string GetVariableValue(variable string) interface{} GetCloud() []Cloud GetType() string GetPolicy() []*IAMPolicy AddRuntimeVariable(key, value string) GetRuntimeVariables() map[string]string ExportModule() error }
package actions import ( "errors" "strings" "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" ) func CheckoutOrder(orderId int64, body *model.BodyCheckoutOrder) (bool, error) { queryString := "" var args []interface...
// Package faterpg fate rpg impl // Fate dice, at least four, preferably four per person. Fate dice are a //special kind of six-sided dice that // are marked on two sides with a plus // If you don’t want to use Fate // symbol (+), two with a minus // dice, you don’t have to—any // symbol (-), and two sides are // set o...
package case4 import ( "errors" "net/http" "golang.org/x/net/context" "google.golang.org/appengine" "google.golang.org/appengine/datastore" "google.golang.org/appengine/log" "google.golang.org/appengine/taskqueue" ) func init() { http.HandleFunc("/case4", handleCase4) http.HandleFunc("/_ah/tq/hello", hand...
package middleware import ( "time" "github.com/gin-gonic/gin" ) type SlowHandlerFunc func(ctx *gin.Context, duration time.Duration) func SlowMiddleware(maxTime time.Duration, callback SlowHandlerFunc) gin.HandlerFunc { return func(ctx *gin.Context) { defer func(startTime time.Time) { elapsed := time.Since(...
package main import ( "flag" "fmt" "os" ) func main() { // flag.CommandLine = flag.NewFlagSet("", flag.ExitOnError) flag.CommandLine = flag.NewFlagSet("", flag.PanicOnError) flag.CommandLine.Usage = func() { fmt.Fprintf(os.Stderr, "Usage Of %s: \n", "Question") flag.PrintDefaults() } flag.Parse() }
package main import ( "context" "github.com/containerd/containerd" "github.com/containerd/containerd/cmd/ctr/commands/content" "github.com/containerd/containerd/errdefs" "github.com/urfave/cli" ) func getImage(ctx context.Context, client *containerd.Client, ref string, clix *cli.Context) (containerd.Image, erro...
// Copyright (c) 2017 Intel Corporation // // 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 ag...
package main import ( "encoding/csv" "log" "os" "strconv" "html/template" ) type OpenClose struct { Open float64 Close float64 } type MarketChanges []OpenClose var mc MarketChanges var t *template.Template func init() { t = template.Must(template.ParseFiles("tpl.gohtml")) } func main() { f , err := os....
package dp import ( "testing" "github.com/stretchr/testify/assert" ) func Test_climbStairs(t *testing.T) { table := []struct { innput int output int }{ { 1, 1, }, { 2, 2, }, { 3, 3, }, { 4, 5, }, } for _, tbl := range table { assert.Equal(t, tbl.output, climbStair...
package set type IntSet struct { M map[int]struct{} } func NewIntSet() *IntSet { return &IntSet{ M: make(map[int]struct{}), } } func (this *IntSet) Add(elt int) *IntSet { this.M[elt] = struct{}{} return this } func (this *IntSet) Exists(elt int) bool { _, exists := this.M[elt] return exists } func (this *...
/* Copyright (c) 2016 Jason Ish * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions...
package imageutil import ( "bytes" "encoding/hex" "crypto/sha256" "testing" ) func TestCropRgba(t *testing.T) { goldHash := "4725a80241458c161db589a64ec7efb378a4e449a70924c0a2a3043408e92495" image, err := ReadRgbaPng("test_data/fruits.png") if err != nil { t.Fatal(err) } width, height :=...
package dcode import ( "fmt" "reflect" ) func Decode(b []byte, d Decoder, i interface{}) error { ret, err := d.call(b) if err != nil { return err } inputType := reflect.TypeOf(i) if inputType.Kind() != reflect.Ptr { return fmt.Errorf("Given %s type is not a pointer", inputType.Name()) } inputTypeName := ...
package byutil import "testing" func Test_Xor2(t *testing.T) { //cmd:=[8]byte{0xFE,0x7F,1,0x4,0,0,0,0} //cmd[7]=Xor(cmd[0:6]) //t.Logf("xor=%d",cmd[7]) } func TestHello(t *testing.T) { } type MyPerson struct { Age int32 Tall int8 } func TestEncodeStruct(t *testing.T) { p:=MyPerson{ Age:10, Tall:1, } da...
// Playing around with this prime sieve example from the golang.org front page. package main import ( "fmt" "math/big" "golang.org/x/text/message" ) func main() { p := message.NewPrinter(message.MatchLanguage("en")) for x := range sieve(gen(1e3)) { p.Printf("%24d\n", x) } } func sieve(in <-chan int64) <-ch...
package main import ( "fmt" "time" ) // Here's the worker, of wich we'll run several concurrent // instances. These workers will receive work on the jobs channel // and send the corresponding results on results var. We'l sleep a // second per job to simulate an expensive task. func worker(id int, jobs <-chan int, r...
package ansi_test import ( "sort" "testing" "unicode/utf8" "github.com/stretchr/testify/require" "github.com/jcorbin/anansi/ansi" "github.com/jcorbin/anansi/terminfo" ) func Test_Terminfo_Integration(t *testing.T) { for _, term := range []string{"xterm", "screen", "linux"} { t.Run(term, func(t *testing.T) ...
// Copyright 2015 Peter Mattis. // // 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 i...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //514. Freedom Trail //In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring",...
package main import ( "fmt" "time" zmq "github.com/pebbe/zmq4" "google.golang.org/protobuf/proto" pb "github.com/Project-Auxo/Olympus/proto/mdapi" ) var addr string = "tcp://127.0.0.1:5556" func main() { socket, _ := zmq.NewSocket(zmq.REQ) defer socket.Close() if err := socket.Connect(addr); err != nil { ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/7/2 8:39 上午 # @File : jz_14_链表倒数k个节点.go # @Description : # @Attention : */ package offer // 对于这种无法获得长度,但是求倒数的情况 // 都可以用双指针解决,1个先走k步,另外一个从头开始,前者到末尾,则后者刚好到倒数k步 func FindKthToTail( pHead *ListNode , k int ) *ListNode { // write code here first,second:=pHead,p...
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
// Licensed to SolID under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. SolID licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
package dynamodb import ( "context" "fmt" "log" "sync" "github.com/qnib/metahub/pkg/storage" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattrib...
package agent import ( "log" "strings" "sync" "time" "github.com/galenguyer/retina/client" "github.com/galenguyer/retina/config" "github.com/galenguyer/retina/core" "github.com/galenguyer/retina/storage" ) var ( lock sync.Mutex ) func Start(config *config.Config) { for _, service := range config.Services ...
package db import ( "bytes" "database/sql" "strconv" "sync" "github.com/textileio/go-textile/pb" "github.com/textileio/go-textile/repo" "github.com/textileio/go-textile/util" ) type CafeRequestDB struct { modelStore } func NewCafeRequestStore(db *sql.DB, lock *sync.Mutex) repo.CafeRequestStore { return &Ca...
package caam import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00800101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caam.008.001.01 Document"` Message *HostToATMAcknowledgementV01 `xml:"HstToATMAck"` } func (d *Document00800101)...
package main import ( "fmt" ) // https://leetcode-cn.com/problems/sort-colors/ //------------------------------------------------------------------------------ func sortColors(nums []int) { sortColors1(nums) } //------------------------------------------------------------------------------ // Solution 1 // 三游标一趟...
// Copyright © 2017 Slotix s.r.o. <dm@slotix.sk> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, me...
package main import ( "fmt" "sort" "reflect" ) /** 1 数组是值类型,长度不可变 2 数组的声明创建方式 [10]int、 [...]int */ /** 1 切片是引用类型,长度可变,通过指向相关数组的指针,len,cap来确定 2 切片的声明创建方式 []int [10]int[:] */ /** make([]int, 50, 100) make返回类型T的初始值 new([100]int)[0:50] new返回一个指针,指向T的零值 array := append(array, 1, 2) copy(array1, ...
package models import ( "context" "errors" "github.com/EddieAlvarez01/sist-backend/storage" "github.com/gocql/gocql" "log" ) type ManageAccountHolder struct { *storage.SistStorage } type AccountHolder struct { ID string `json:"id,omitempty"` Name string `json:"name,omitempty"` LastName string `json:"last_na...
package main import ( "fmt" "github.com/ksclouds/PowerNLP/Seg/Collections" ) func main() { t := Collections.NewDATrie() fmt.Println(Collections.EndRune) fmt.Println(string(Collections.EndRune)) fmt.Println(len(t.Base)) fmt.Println(len(t.RuneCodeMap)) fmt.Println(t.GetRuneCode('d')) t.AppendToTailArray([]run...
package bitty /* Copyright 2020 IBM 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, so...
package contribution import ( "fmt" "strings" tiexternalplugins "github.com/ti-community-infra/tichi/internal/pkg/externalplugins" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/config" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/pluginhelp" "k8s.io/test-infra/prow/pluginhelp/externalplugin...
package main import "fmt" func average(slice []float64) float64 { total := 0.0 for _, item := range slice { total += item } return total / float64(len(slice)) } func main() { array := []float64{101, 3, 77, 82, 12} fmt.Println(average(array)) }