text
stringlengths
11
4.05M
package zbar // #include <stdlib.h> // #include <zbar.h> import "C" import "unsafe" type Image struct { c_image *C.zbar_image_t } // NewImage creates new Image instance func NewImage() *Image { img := Image{} img.c_image = C.zbar_image_create() return &img } // Destroy is an image destructor func (i *Image) Des...
// 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 in wr...
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. package myoohoohoo2 import ( "appengine" //"appengine/blobstore" "appengine/datastore" "encoding/json" "fmt" //"io" "net/http" //"os" . "github.com/q...
package chapter2 import "fmt" func init() { fmt.Println("=== Slices ===") var carTypes[3] string carTypes[0] = "Toyota" carTypes[1] = "Ford" carTypes[2] = "Nissan" fmt.Println(carTypes[1]) carTypes2 := [3]string{"Toyota", "Ford", "Nissan"} fmt.Println(carTypes2[0]) carTypesSlice := []string{"Toyota", "Ford...
package pipeline import ( "fmt" "time" "github.com/sherifabdlnaby/prism/app/component" "github.com/sherifabdlnaby/prism/app/config" "github.com/sherifabdlnaby/prism/app/pipeline/persistence" "github.com/sherifabdlnaby/prism/pkg/job" "go.uber.org/zap" ) type wrapper struct { *pipeline jobChan chan job.Job } ...
package main import ( "fmt" ) type Greeter struct { helloPhrase string } func (g Greeter) Hello() { fmt.Println(g.helloPhrase) } func main() { g := Greeter{helloPhrase: "Hey everyone!"} g.Hello() }
package script import "reflect" //Table type. type Table struct { Type } //Make makes a table. func (*Table) Make(q Ctx, collection Collection, sizes ...int) { var T = reflect.TypeOf(collection).Elem() var V = reflect.ValueOf(collection).Elem() var L, ok = T.FieldByName("L") if !ok { panic("table type must h...
package main import ( "os" "text/template" ) type person struct { Name string Age int } func main() { p := person{"kamil", 35} tpl, _ := template.New("test").Parse("Hello {{ .Name }}, you are {{ .Age }} years old") err := tpl.Execute(os.Stdout, p) if err != nil { panic(err) } }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
// Copyright 2017 Yahoo Holdings Inc. // Licensed under the terms of the 3-Clause BSD License. package provider import ( "errors" "testing" "github.com/stretchr/testify/assert" "k8s.io/api/extensions/v1beta1" "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/client-go/tools/c...
package main import ( "flag" "os" "github.com/projectdiscovery/gologger" "github.com/projectdiscovery/httpx/common/customheader" customport "github.com/projectdiscovery/httpx/common/customports" "github.com/projectdiscovery/httpx/common/fileutil" ) // Options contains configuration options for chaos client. ty...
// +build windows package distribution import ( "encoding/json" "github.com/docker/distribution/manifest/schema1" "github.com/docker/docker/image" ) func setupBaseLayer(history []schema1.History, rootFS image.RootFS) error { var v1Config map[string]*json.RawMessage if err := json.Unmarshal([]byte(history[len(h...
package main import ( "text/template" "os" "fmt" ) type bikes struct{ Name string Model int } type cars struct{ Name string Model int } type vehicles struct { Bike1 []bikes Car1 []cars } var file *template.Template func init(){ file = template.Must(template.ParseFiles("passstruct.gohtml")) } func main(...
package stats import ( "sync" "testing" ) func benchmarkChannelsRoutine(b *testing.B, e chan bool) { for i := 0; i < b.N; i++ { Increment("abc123", 5) Increment("def456", 5) Increment("ghi789", 5) Increment("abc123", 5) Increment("def456", 5) Increment("ghi7...
package task import ( "bankBigData/AutomaticTask/db" "bankBigData/AutomaticTask/dbConfig/tableTaskFile" "bankBigData/AutomaticTask/entity/config" "bankBigData/_public/ftp" "bankBigData/_public/log" "bankBigData/_public/util" "bufio" "fmt" "gitee.com/johng/gf/g" "io" "os" "strconv" "strings" "sync" ) typ...
package app import ( "net/http" "github.com/gin-gonic/gin" ) func pongHandler(c *gin.Context) { c.Set("rendered", true) c.String(http.StatusOK, "pong") } func blankHandler(c *gin.Context) { c.Set("controller", `blank`) c.Set("action", `index`) } func simplePugHandler(c *gin.Context) { db, _ := NewGormDB(c) ...
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package main import ( "fmt" "time" "github.com/dgrijalva/jwt-go" ) const SigningKey = "somethingsupersecret" func main() { // New web token. token := jwt.New(jwt.SigningMethodHS256) // Set a header and a claim token.Header["typ"] = "JWT" token.Claims["exp"] = time.Now().Add(time.Hour * 96).Unix() // Gen...
package kui import ( "fmt" "testing" ) func Race(v1, v2, g int) [3]int { if v1 >= v2 { return [3]int{-1, -1, -1} } // v1*t + g = v2*t // g = v2*t - v1*t // g/t = v2 - v1 // 1/t = (v2 - v1) / g // t = g / (v2 - v1) t := float64(float64(g) / float64(v2-v1)) // return [3]int{int(t), int(t*60) % 60, int(math...
// SPDX-License-Identifier: Apache-2.0 // Copyright © 2020 Intel Corporation package af import ( "context" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) // Linger please var ( _ context.Context ) // PfdManagementTransactionAppDeleteAPIService type type PfdManagementTransactionAppDeleteAPIService s...
package neatly_test import ( "github.com/stretchr/testify/assert" "github.com/viant/neatly" "github.com/viant/toolbox/data" "testing" ) func TestFieldExpression_Set(t *testing.T) { { var object = data.NewMap() field1 := neatly.NewField("Field1") field1.Set(123, object) assert.Equal(t, 123, object.GetInt...
// Copyright (C) 2019 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 applica...
package handlers import ( "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "github.com/authelia/authelia/v4/internal/mocks" ) type LogoutSuite struct { suite.Suite mock *mocks.MockAutheliaCtx } func (s *LogoutSuite) SetupTest() { s.mock = mocks.NewMockAutheliaCt...
package email import ( // "k8sproject/config" "github.com/connext-cs/pub/config" "fmt" "net" "net/smtp" "strings" ) type MailInfo struct { loginAuth unencryptedAuth host string content string title string } type unencryptedAuth struct { smtp.Auth } func (a unencryptedAuth) Start(server *smtp.Server...
package main import ( "log" "os" "github.com/brutella/hc" "github.com/RonMelkhior/homekit-lightify/lightify" "github.com/brutella/hc/accessory" _ "github.com/joho/godotenv/autoload" ) func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) if err := lightify.Init(); err != nil { log.Fatal(err) } de...
package main import "exchange_websocket/bitfinex_websocket" func main() { bf := bitfinex_websocket.BitfinexWebsocketInit() bf.BFKlineWebsocket() for true { bf.WsConnect() go func() { bf.Ping() }() bf.Subscribe("kline") bf.ReadMessage() } }
package middleware import "sync" import "math" import "time" import "log" import "errors" import "reflect" import "fmt" import "github.com/nu7hatch/gouuid" import . "../packet" import . "../message" import . "../client_request_handler" type Subscribed struct{ Map map[string][]MessageListener } func (sd *Subscribe...
package useatomic import ( "sync/atomic" "testing" "time" ) func TestAtomic(t *testing.T) { // 原子操作的第一个参数,是被操作的值 因为原子操作函数需要是被操作值得指针,而不是这个值本身,被传入函数的参数值都会被复制 // 原子操作加法函数做原子减法操作 有符号类型 num := int32(18) t.Logf("the num is %d\n", num) atomic.AddInt32(&num, int32(3)) t.Logf("the num is %d\n", num) ...
package fetcher import ( "fmt" ) func newRedHatFetchRequests(target []string) (reqs []fetchRequest) { const t = "https://www.redhat.com/security/data/oval/com.redhat.rhsa-RHEL%s.xml.bz2" for _, v := range target { reqs = append(reqs, fetchRequest{ target: v, url: fmt.Sprintf(t, v), bzip2:...
package storage import ( "context" "github.com/mongodb/mongo-go-driver/bson" ) // GetByName queries mongodb for an item with // the correct name func (m *MongoStorage) GetByName(ctx context.Context, name string) (*Item, error) { c := m.Client.Database(m.DB).Collection(m.Collection) var i Item if err := c.FindOn...
package main import ( "ethos/altEthos" "ethos/syscall" "ethos/kernelTypes" "ethos/defined" "log" "strings" ) var userName string var currentTransactionID int64 func init() { SetupMyRpcTransactionStartIReply(transactionStartIReply) SetupMyRpcTransactionEndIReply(transactionEndIReply) SetupMyRpcReadIReply(rea...
package order import ( "context" "time" "tpay_backend/merchantapi/internal/common" "tpay_backend/model" "tpay_backend/utils" "tpay_backend/merchantapi/internal/svc" "tpay_backend/merchantapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type TransferOrderNotifyLogic struct { logx.Logger ctx ...
package scanner import ( "fmt" "go/token" "io/ioutil" "runtime" "sort" "testing" "h12.io/gombi/scan" ) var sampleGoFile = runtime.GOROOT() + "/src/go/scanner/scanner.go" func TestSingle(t *testing.T) { // fmt.Println(int(token.INT)) } type sortItem struct { count int tok token.Token } type sortItems []...
package main import ( "fmt" "os" "sort" "strconv" ) // parseFloat func pf(s string) float64 { f, err := strconv.ParseFloat(s, 64) if err != nil { fmt.Fprintf(os.Stderr, "\nError converting '%s' to float\n\n", s) return 0.0000 } return f } func sortSpotPrice(entry []spotPriceItem, ascending bool) { sort....
package models import ( "errors" ) var ErrInvalidEmailCode = errors.New("Invalid or expired email code") var ErrSmtpNotEnabled = errors.New("SMTP not configured, check your grafana.ini config file's [smtp] section") // EmailAttachFile is a definition of the attached files without path type EmailAttachFile struct { ...
package routers import ( "github.com/astaxie/beego" ) func init() { beego.GlobalControllerRouter["GoldenTimes-web/controllers:ArtistController"] = append(beego.GlobalControllerRouter["GoldenTimes-web/controllers:ArtistController"], beego.ControllerComments{ "CreateArtist", `/artist`, []string{"post"}, ...
// Copyright 2019 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 meta_test import ( "testing" "time" "github.com/BurntSushi/toml" "github.com/messagedb/messagedb/meta" ) func TestConfig_Parse(t *testing.T) { // Parse configuration. var c meta.Config if _, err := toml.Decode(` dir = "/tmp/foo" election-timeout = "10s" heartbeat-timeout = "20s" leader-lease-timeout =...
/* Package logger sets up logging for the application, based on Uber zap's logger. */ package logger import ( "go.uber.org/zap" "sync" ) // Package internal variable to implement singleton var ( innerLogger *zap.Logger innerSugar *zap.SugaredLogger onceLogger sync.Once ) // GetLogger returns singleton logger ...
package data import ( "database/sql" "errors" "github.com/google/wire" _ "github.com/go-sql-driver/mysql" xerrors "github.com/pkg/errors" "geektime/Go-000/Week04/internal/biz" ) const ( MYSQLSRC = "root:123456@tcp(192.168.141.180:3306)/test?charset=utf8" ) var ErrRecordNotFound = errors.New("record not foun...
package main import ( "fmt" "io/ioutil" "strings" ) func part1() { // Assumes current working directory is `day-03/`! fileContent, err := ioutil.ReadFile("puzzle-input.txt") if err != nil { fmt.Println(err) } polymerUnits := strings.Split(string(fileContent), "") processedUnits := processUnits(polymerUnit...
/* * Copyright 2018-present Open Networking Foundation * 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 ...
package database import ( "memoapp/model" "net/url" ) // Client データベースクライアントのインターフェース type Client interface { Set(*model.Memo) ([]byte, error) Get(url.Values) ([]byte, error) DEL(url.Values) ([]byte, error) Exists(url.Values) (bool, error) SetByte(url.Values, []byte) error Close() error } var ( pkgName = "d...
package models import ( "fmt" "time" "github.com/go-redis/redis" ) func SaveUrlRecord(uniqueKey, longURL string) *redis.StatusCmd { status := DB.Set(uniqueKey, longURL, 5*time.Minute) return status } func IsUniqueKeyAlreadyUsed(uniqueKey uint64) bool { result := DB.Exists(fmt.Sprint(uniqueKey)) var isAlready...
package events import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "os" "strings" "time" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/binding/format" root "github.com/direktiv/direktiv/cmd/exec/cmd" "github.com/spf13/cobra" goutil "golang.org/x/...
package linkaja import "fmt" func GenerateItems(items []PublicTokenItemRequest) string { var is string for i, v := range items { if i > 0 { is = is + "," } is = is + fmt.Sprintf("[\"%v\", \"%v\", \"%v\"]", v.Name, v.Price, v.Quantity) } return fmt.Sprintf("[%v]", is) }
package reminder import ( "fmt" "os/exec" "time" ) // Reminder - type Reminder interface { Start() Stop() } type reminder struct { done chan struct{} config Config } // Task - type Task struct { Title string `json:"title"` Message string `json:"message"` Interval string `json:"interval"` } // Confi...
package main import ( "log" "math/rand" "sync" "sync/atomic" "time" ) type ( // semaphore 是一个接收struct类型的channel,这样定义 semaphore 既是一个channel,也可以实现自定义的方法 semaphore chan struct{} readerWriter struct { name string write sync.WaitGroup readerControl semaphore shutdown chan struct{...
package interfaces type PasswordServiceProvider interface { EncodePassword(password string) string }
/* Copyright Greg Haskins <gregory.haskins@gmail.com> 2017, All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by ap...
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package translate import ( "context" "fmt" "strings" "cloud.google.com/go/translate" "golang.org/x/text/language" ) // Translator ... type Translator interface { Close() Translate(ctx context.Context, input, source, target string) (string, error) DetectLanguage(ctx context.Context, input string) (string, err...
package server import ( "net/http" "net/url" "os" "path" "strings" "github.com/cinus-ue/securekit/internal/webapps/fileserver/util" ) type archiveCallback func(f *os.File, fInfo os.FileInfo, relPath string) error func matchSelection(info os.FileInfo, selections []string) (matchName, matchPrefix bool, childSel...
package slice import "github.com/cheekybits/genny/generic" type T generic.Type type V generic.Type func Map_T_V(sl []T, f func(e T) V) []V { res := []V{} for _, e := range sl { res = append(res, f(e)) } return res }
package system import "errors" var ErrorSizesDoesNotMatch = errors.New("could not load full file") var ErrorCreateFile = errors.New("could not create file") var ErrorWriteFile = errors.New("could not write to file") var ErrorLoading = errors.New("unexpected error occurred while loading file") var ErrorOpening = e...
package goSolution func numMatchingSubseq(s string, words []string) int { n := len(s) m := len(words) f := make([]int, m) for i := 0; i < n; i++ { for j := 0; j < m; j++ { if f[j] < len(words[j]) && words[j][f[j]] == s[i] { f[j] += 1 } } } ret := 0 for i := 0; i < m; i++ { if f[i] == len(words[...
package worldx import ( "testing" ) type TestDataItem struct { receiver City result []Direction } func TestAvailableDirs(t *testing.T) { testDataItems := []TestDataItem{ {City{name: "Foo"}, []Direction{}}, {City{name: "Foo", north: "some"}, []Direction{North}}, {City{name: "Foo", south: "some"}, []Direct...
package main import ( "github.com/dearcj/golangproj/bitmask" "github.com/dearcj/golangproj/msutil" pb "github.com/dearcj/golangproj/network" ) type Player struct { additionalMoves uint32 emotion bitmask.Bitmask parent *Object currentGun *Gun angle1 int32 angle2 i...
package rpcdb import ( "fmt" "github.com/alioygur/gores" "golang.org/x/net/context" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" ) func TestDebugContext(t *testing.T) { req, _ := http.NewRequest("GET", "/", nil) req.Header.Add("debug-breakpoint", "request example:*") req.Header.Add("debug...
package mathhelper import ( "testing" "github.com/stretchr/testify/assert" ) func TestIsEqualFloat32(t *testing.T) { // Given // When val1 := IsEqual(float32(10.0001), float32(10.00009)) val2 := IsEqual(float32(10.0005), float32(10.00001)) val3 := IsEqual(float32(10.00009), float32(10.0001)) val4 := IsEqual...
package lib import ( "fmt" "github.com/keptn/go-utils/pkg/api/models" api "github.com/keptn/go-utils/pkg/api/utils" "github.com/keptn/keptn/distributor/pkg/config" "strings" "sync" ) type ControlPlane struct { UniformHandler *api.UniformHandler EnvConfig config.EnvConfig currentID string mux ...
package atomix import ( "reflect" "testing" ) func mustEqual(tb testing.TB, got, want interface{}) { tb.Helper() if !reflect.DeepEqual(got, want) { tb.Fatalf("got: %v, want: %v", got, want) } }
package gojson import ( "bytes" "encoding/json" "fmt" "reflect" ) // Marshal has no documentation func Marshal(v interface{}) ([]byte, error) { enc := &encoder{buf: new(bytes.Buffer)} var data json.RawMessage var err error if data, err = enc.marshal(reflect.ValueOf(v)); err != nil { return nil, err } retu...
package main /* * @lc app=leetcode.cn id=84 lang=golang * * [84] 柱状图中最大的矩形 */ // 单调递增栈,优化暴力解中重复的步骤 // @lc code=start func largestRectangleArea(heights []int) int { maxArea := 0 var stack []int var left = make([]int, len(heights)) var right = make([]int, len(heights)) stack = nil for i := 0; i < len(heigh...
package test import ( "fmt" ) func test2() { fmt.Println("test2") }
package jarviscore import "errors" var ( // ErrLoadFileReadSize - loadfile invalid file read size ErrLoadFileReadSize = errors.New("loadfile invalid file read size") // ErrNotConnectNode - not connect node ErrNotConnectNode = errors.New("not connect node") // ErrNoCtrlCmd - no ctrl cmd ErrNoCtrlCmd = errors.New...
package config import ( "time" "gopkg.in/ini.v1" ) // AppConfig App配置项 type AppConfig struct { Release bool `ini:"release"` Port uint `ini:"port"` *EtcdConfig `ini:"etcd"` } // EtcdConfig Etcd集群配置文件 type EtcdConfig struct { Endpoints []string `ini:"endpoints"` DialTimeout time.Duration `ini...
package boom import ( "testing" "go.mercari.io/datastore/v2/internal/testutils" ) func TestBoom_NewTransaction(t *testing.T) { ctx, client, cleanUp := testutils.SetupCloudDatastore(t) defer cleanUp() type Data struct { ID int64 `datastore:"-" boom:"id"` Str string } bm := FromClient(ctx, client) key,...
package api import ( "bytes" "fmt" "log" routing "github.com/qiangxue/fasthttp-routing" "github.com/guilhermesteves/aclow" "github.com/valyala/fasthttp" ) func RegisterRoutes(app *aclow.App) { router := app.Resources["router"].(*routing.Router) router.Use(logHandler(), panicHandler(), corsHandler()) listT...
package ffprobe import ( "log" "os" "os/exec" "runtime" "strings" ) // Prober has logic that changes based on platform type Prober interface { getDevicesCmd() string getFfmpegCmd(ProberCommon) ([]string, error) } // Devices has information about ffmpeg multimedia devices type Devices struct { Audios []string...
package unit type UnitFileState int const ( UnitFileStateError UnitFileState = iota - 1 UnitFileStateDisabled UnitFileStateEnabled UnitFileStateStatic UnitFileStateMasked UnitFileStateLinked ) var MapUnitFileState = map[string]UnitFileState{ "disabled": UnitFileStateDisabled, "enabled": UnitFi...
//author xinbing //time 2018/8/28 14:18 //字符串工具 package utilities import ( "math/rand" "time" ) var randomStrSource = []byte("0123456789abcdefghijklmnopqrstuvwxyz") //获取随机字符串 func GetRandomStr(length int) string { result := make([]byte,length) r := rand.New(rand.NewSource(time.Now().UnixNano() + rand.Int63())) //...
package bitbar import ( "fmt" "strconv" "time" "github.com/DennisDenuto/igrb/data/diskstore" "github.com/DennisDenuto/igrb/multicast" "github.com/concourse/atc" "github.com/git-duet/git-duet" "strings" ) type Painter struct { MainItems []string } func (p *Painter) AddMainMenuItems(item string) { p.MainIte...
// Copyright (c) 2017-2018 The qitmeer developers // Copyright (c) 2014-2016 The btcsuite developers // Copyright (c) 2015-2017 The Decred developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package params import ( "time" "math/big" "github.com/Qitmeer/qitm...
package files import ( "errors" "os" "path/filepath" shared "github.com/cazier/resume/pkg/shared" ) func Exists(path string, is_file bool) bool { resp, err := os.Stat(path) if os.IsNotExist(err) { return false } else if errors.Is(err, os.ErrPermission) { shared.Exit(1, "The destination path (%s) has bad p...
package main import ( "flag" "github.com/gin-gonic/gin" "net/http" "os" ) var addr = flag.String("addr", ":8080", "address") func main() { flag.Parse() r := gin.New() r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "hello %s this message from %s/%s", c.Query("name"), os.Getenv("POD"), os.Getenv("N...
package main import ( "strings" "sync" "testing" "github.com/go-test/deep" "golang.org/x/tools/go/loader" ) type programCache struct { sync.Mutex loadedProgs map[string]*loader.Program } func (p *programCache) load(path string) (prog *loader.Program, err error) { p.Lock() defer p.Unlock() if p.loadedProgs...
package biz import ( "context" "github.com/go-kratos/kratos/v2/log" ) type User struct { Name string Email string } type UserRepo interface { CreateUser(ctx context.Context, a *User) (int64, error) } type CardRepo interface { CreateCard(ctx context.Context, id int64) (int64, error) } type UserUsecase struc...
// Copyright 2019 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 gorden var strategies = make(map[string]Strategy) func AddStrategy(name string, strategy Strategy) { strategies[name] = strategy }
package middlewares import ( "fmt" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) func SetCorsMiddlewares(e *echo.Echo) { fmt.Println("masuk ke CORS") e.Use(middleware.CORSWithConfig(middleware.CORSConfig{ AllowOrigins: []string{"*"}, AllowHeaders: []string{echo.HeaderOrigin, echo.Head...
package main import ( "fmt" ) // 想法: // 左指针找奇数,右指针找偶数,然后交换 func sortArrayByParity(A []int) []int { i := 0 j := len(A) - 1 for i < j { if A[i]%2 == 0 { i++ } else if A[j]%2 != 0 { j-- } else { tmp := A[j] A[j] = A[i] A[i] = tmp } } return A } func main() { A := []int{3, 6, 8, 89, 4, 9...
package redis import ( "github.com/astaxie/beego" "github.com/go-redis/redis" "time" ) type Client struct { baseClient *redis.Client } //内部调用 func RedisClient(class string) *Client { Addr := "" Password := "" DB := 0 switch class { case "user": Addr = beego.AppConfig.String("common_addr") Password = be...
package atomic import ( "sync" "sync/atomic" ) // Ordinal holds a global a value // and can only be initialized once type Ordinal struct { ordinal uint64 once *sync.Once } // NewOrdinal returns ordinal with once // setup func NewOrdinal() *Ordinal { return &Ordinal{once: &sync.Once{}} } // Init sets the ord...
package gencoder import ( "io" "time" "unsafe" pb "github.com/bgokden/veri/veriservice" ) var ( _ = unsafe.Sizeof(0) _ = io.ReadFull _ = time.Now() ) ////////// func SizeKey(d *pb.DatumKey) (s uint64) { { l := uint64(len(d.Feature)) { t := l for t >= 0x80 { t >>= 7 s++ } s++ } ...
package commands import ( "fmt" "github.com/getkin/kin-openapi/openapi3" "github.com/michaelsauter/go-oas-server/pkg/generator" ) // Generate renders Go files based on specification in file into directory outputDir. func Generate(file string, outputDir string) error { spec, err := openapi3.NewSwaggerLoader().Loa...
package main import ( "strconv" ) /** 二进制求和 给你两个二进制字符串,返回它们的和(用二进制表示)。 输入为 非空 字符串且只包含数字 `1` 和 `0`。 示例1: ``` 输入: a = "11", b = "1" 输出: "100" ``` 示例2: ``` 输入: a = "1010", b = "1011" 输出: "10101" ``` 提示: - 每个字符串仅由字符 `'0'` 或 `'1'` 组成。 - `1 <= a.length, b.length <= 10^4` - 字符串如果不是 `"0"` ,就都不含前导零。 */ func AddBinary(a s...
package aoc2015 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func day13sampleScenario() *tableScenario { // guaranteed not to error scenario, _ := newTableScenario(day13sampleInput) return scenario } func day13myScenario() *tableScenario { scenario, _ := n...
/* Copyright 2018 The HAWQ Team. */ package controller
package config import ( "fmt" "io/ioutil" "path/filepath" "github.com/fsnotify/fsnotify" ) func init() { RegisterProvider(newFileProvider()) } func newFileProvider() *FileProvider { fp := &FileProvider{ cache: make(map[string]string), cb: make(chan ProviderCallback), disabledWatch...
package pacs import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00200102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:pacs.002.001.02 Document"` Message *PaymentStatusReportV02 `xml:"pacs.002.001.02"` } func (d *Document00200102) AddMe...
package main import ( "context" "encoding/json" "fmt" "net/http" "os" pb "github.com/polarbroadband/gnmi/pkg/gnmiprobe" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/kr/pretty" log "github.com/sirupsen/logrus" ) var ( ENCODING = "JSON" // container image release RELEASE = ...
package robot import ( "encoding/json" "fmt" "robot-go/robot/msg" "strconv" ) // 登录发送的第一条消息,bind_user func SendLogin(rb *Robot) { _msg := msg.NewMsgRequest("bind_user", "") _msg.SetParam("userId", rb.userId) _msg.SetParam("gameId", HALL_GAMEID) _msg.SetParam("clientId", rb.clientId) fmt.Println("SendLogin=="...
package middleware import ( "github.com/BukkitAPI-Translation-Group/docsbox/api" "github.com/BukkitAPI-Translation-Group/docsbox/conf" "github.com/labstack/echo" "github.com/labstack/echo-contrib/session" "net/http" "strings" ) func Auth(adminRequired bool) echo.MiddlewareFunc { return func(next echo.HandlerFu...
package resource import ( "blog/resource/log" "github.com/go-jar/mysql" "blog/conf" ) var MysqlClientPool *mysql.Pool func InitMysql() { config := &mysql.PoolConfig{NewClientFunc: NewMysqlClient} config.MaxConns = conf.MysqlConf.PoolSize config.MaxIdleTime = conf.MysqlConf.PoolClientMaxIdleTime MysqlClientP...
package feed import "camp/skel/model" // Del 定义删除操作 func (feeds *Feeds) Del(id int,txt string) (err error) { feedsModel := model.NewFeed() feedsModel.Id= id feedsModel.Txt= txt if err = feedsModel.Del(); err != nil { return } return }
package raft import ( "bytes" "math/rand" "sync" "sync/atomic" "time" "fmt" "../labgob" "../labrpc" ) // // 常量 // const ( Candidate = 0 Follower = 1 Leader = 2 HeartBeatInterval = 100 ElectionTimeout = 150 ElectionRandomTimeRange = 150 ) // /...
package blockchain import "testing" func TestCreateSimpleBlockchain(t *testing.T) { simplechain := NewBlockchain() if simplechain == nil { t.Error("Error creating Blockchain object") } } func TestCreateNextBlock(t *testing.T) { simplechain := NewBlockchain() block := simplechain.NextBlock() if block == ni...
package annotations import ( "strings" "time" "github.com/haproxytech/config-parser/v3/types" "github.com/haproxytech/kubernetes-ingress/controller/haproxy/api" "github.com/haproxytech/kubernetes-ingress/controller/store" ) type GlobalHardStopAfter struct { name string data *types.StringC client api.HAP...
package executor import ( "bytes" "encoding/json" "fmt" "sort" "sync" "sync/atomic" "time" "github.com/cbergoon/merkletree" "github.com/meshplus/bitxhub-core/agency" "github.com/meshplus/bitxhub-kit/crypto" "github.com/meshplus/bitxhub-kit/crypto/asym" "github.com/meshplus/bitxhub-kit/types" "github.com/...