text
stringlengths
11
4.05M
package main import ( "log" "sync" "time" ) func main() { var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go startWorker(i, &wg) } log.Printf("now waiting") wg.Wait() log.Printf("after wait") } func startWorker(workerNum int, wg *sync.WaitGroup) { log.Printf("worker: %v starts", workerNum) ...
package prometheus import ( "crypto/tls" "fmt" "net" "net/http" "net/url" "time" "github.com/openshift/osde2e/pkg/common/config" "github.com/prometheus/client_golang/api" "github.com/spf13/viper" ) // CreateClient will create a Prometheus client. // If no arguments are supplied, the global config will be us...
package binance import ( "context" "net/http" ) // RateLimitService get rate limits type RateLimitService struct { c *Client } // Do send request func (s *RateLimitService) Do(ctx context.Context, opts ...RequestOption) (res []*RateLimitFull, err error) { res = make([]*RateLimitFull, 0) r := &request{ method:...
package goSolution func runningSum(nums []int) []int { n := len(nums) ret := make([]int, n + 1) for i := 0; i < n; i++ { ret[i + 1] = ret[i] + nums[i] } return ret[1: ] }
package qstring import ( "strings" ) // MapBuilders are used to construct queries which map against an objects fields. // // Prefer not using builders directly, instead using the constructors. type MapBuilder struct { builder *strings.Builder } func (kv *MapBuilder) Has(key, value string) *Builder { kv.builder.Wr...
package main /* Copyright © 2020 妙音 <xuender@139.com> */ import "github.com/xuender/roby/cmd" func main() { cmd.Execute() }
package spec import ( "reflect" "strconv" "strings" "time" "github.com/bingoohuang/golog/pkg/typ" "github.com/bingoohuang/golog/pkg/str" "github.com/bingoohuang/golog/pkg/timex" "github.com/pkg/errors" ) type Parser interface { Parse(string) error } // ParseSpec parses a specification to a structure. func...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //717. 1-bit and 2-bit Characters //We have two special characters. The first character can be represented by one bit 0. The second character can be re...
// Copyright 2015 Keybase, Inc. All rights reserved. Use of // this source code is governed by the included BSD license. // +build windows package main import ( "flag" "github.com/keybase/go-logging" "github.com/keybase/go-updater/keybase" ) // Given the name of an installer, this can be run on a // target syst...
package problems import "math" // start with two largest values, as soon as we find a number bigger than both, while both have been updated, return true. func IncreasingTriplet(nums []int) bool { small := math.MaxInt32 big := math.MaxInt32 for _, v := range nums { if v <= small { small = v } else if v <= big...
package main import ( "fmt" "os" "time" "github.com/gomodule/redigo/redis" ) var pool = &redis.Pool{ MaxIdle: 3, IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { return redis.Dial("tcp", ":6379") }, TestOnBorrow: func(c redis.Conn, t time.Time) error { if time.Since(t) < time.M...
package main /* * @lc app=leetcode id=129 lang=golang * * [129] Sum Root to Leaf Numbers */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func sumNumbers(root *TreeNode) int { res := 0 helper129(&res, 0, r...
package main import ( "errors" "io/ioutil" "net/http" "net/http/httptest" "net/url" "strconv" "testing" jennyerrors "github.com/Typeform/jenny/errors" "github.com/Typeform/users/datastore/mockdb" "github.com/Typeform/users/transport/v1" "github.com/Typeform/users/user" "github.com/golang/mock/gomock" ) f...
package adyen2 import ( "crypto/aes" "crypto/rand" "encoding/base64" "fmt" "github.com/pion/dtls/v2/pkg/crypto/ccm" "testing" ) func TestAdyen_Encrypt2(t *testing.T) { key := []byte{ 175, 152, 214, 174, 41, 51, 112, 162, 103, 202, 35, 202, 184, 85, 102, 148, 69, 185...
package main import ( "context" "fmt" "log" "os" "github.com/akito0107/xsqlparser" "github.com/akito0107/xsqlparser/dialect" "github.com/akito0107/xsqlparser/sqlast" "github.com/jmoiron/sqlx" "github.com/urfave/cli" "github.com/akito0107/xmigrate" ) func main() { app := cli.NewApp() app.Name = "xmigrate...
/* Copyright 2020 The Qmgo 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 agreed to in writing, sof...
package xdominion import ( "fmt" ) type XFieldText struct { Name string Constraints XConstraints } // creates the name of the field with its type (to create the table) func (f XFieldText) CreateField(prepend string, DB string, ifText *bool) string { ftype := " text" extra := "" if f.Constraints != nil {...
package ierr import ( "errors" "fmt" ) func NewError(format string, arg ...interface{}) error { return errors.New(fmt.Sprintf(format, arg...)) } func IErr(code int) error { return NewError(ErrorMessage[code]) }
package main import ( "fmt" "net" ) const addr = "localhost:8888" func main() { fmt.Printf("client for server url: %s\n", addr) addr, err := net.ResolveUDPAddr("udp", addr) if err != nil { panic(err) } conn, err := net.DialUDP("udp", nil, addr) if err != nil { panic(err) } defer conn.Close() msg :=...
package jsonschema2go import ( "context" "errors" "fmt" "github.com/ns1/jsonschema2go/internal/cachingloader" "github.com/ns1/jsonschema2go/internal/crawl" "github.com/ns1/jsonschema2go/internal/planning" "github.com/ns1/jsonschema2go/internal/print" "github.com/ns1/jsonschema2go/pkg/gen" "net/url" "path/fil...
//go:build noplugins // +build noplugins package plugins import ( "errors" "sync" "github.com/kabukky/journey/structure" ) // Global LState pool var LuaPool *lStatePool type lStatePool struct { m sync.Mutex files map[string]string saved []map[string]*string } // Load ... func Load() error { LuaPool = n...
package common import ( "context" "fmt" "os" "github.com/werf/werf/pkg/docker" "github.com/werf/werf/pkg/buildah" "github.com/werf/werf/pkg/container_runtime" ) func ContainerRuntimeProcessStartupHook() (bool, error) { buildahMode := GetContainerRuntimeBuildahMode() if buildahMode != "" { return buildah....
package api import ( "github.com/globalsign/mgo/bson" ) type User struct { Id bson.ObjectId `json:"id" bson:"_id"` Nick string `json:"nick" bson:"nick"` Sex byte `json:"sex" bson:"sex"` Email string `json:"email" bson:"email"` Password string `json:"password" bson:"password"` FansUse...
package schema import ( "fmt" "io" "io/ioutil" "os" "regexp" "sort" "strings" "github.com/dvirsky/go-pylog/logging" "github.com/EverythingMe/meduza/errors" "gopkg.in/yaml.v2" ) type IndexType string type ColumnType string type IndexState int8 type Key string func (k Key) IsNull() bool { return k == ""...
package main import ( "gopkg.in/yaml.v2" "io/ioutil" ) type DatabaseConfiguration struct { Username string `yaml:username` Password string `yaml:password` DatabaseName string `database` } type HttpConfiguration struct { Port string `yaml:port` } type Configuration struct { Database Datab...
package equinix import ( "context" "fmt" "net/http" "time" "github.com/equinix/ne-go" "github.com/equinix/rest-go" "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) var networkSS...
package mails import ( "fmt" "os" "testing" _ "github.com/go-sql-driver/mysql" ) func init() { os.Setenv("mailbox_web_site", "example.com") } func TestReplaceReader(t *testing.T) { html := []byte(`<img src="{{READER}}">`) ReplaceReader(&html, "12345678", "87654321", "11") if fmt.Sprintf("%s", html) != `<img...
package game import ( "myLeaf/game/internal" ) var ( Module = new(internal.Module) ChanRPC = internal.ChanRPC ) //首先,模块会被实例化,这样才能注册到 Leaf 框架中(详见 LeafServer main.go),另外,模块暴露的 ChanRPC 被用于模块间通讯。 //internal.Module 模块中最关键的就是 skeleton(骨架),skeleton 实现了 Module 接口的 Run 方法并提供了: //- ChanRPC //- goroutine //- 定时器
package Problem0273 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { num int ans string }{ {50868, "Fifty Thousand Eight Hundred Sixty Eight"}, {100, "One Hundred"}, {30, "Thirty"}, {21, "Twenty One"}, {0, "Zero"}, {123, "One Hundred Twenty Thre...
// Copyright © 2020 Attestant Limited. // 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 pdu import ( "bytes" "encoding/binary" ) type ConcatenatedHeader struct { Reference uint16 TotalParts byte Sequence byte } func (h ConcatenatedHeader) Len() int { if h.Reference < 0xFF { return 5 } return 6 } func (h ConcatenatedHeader) Set(udh UserDataHeader) { var buf bytes.Buffer _ = binar...
package util import "math/rand" var randomStringRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") //GetRandomString returns a random string of given range func GetRandomString(length int) string { r := make([]rune, length) for i := range r { r[i] = randomStringRunes[rand.Intn(len(r...
/* Description Your task is to implement a simple UNIX command parser and file system. Your program will have to implement a file system that can be modified via commands. The starting directory of your file system is an empty root directory /, with no subdirectories or files. Your program must be capable of handling...
package main import ( "strings" ) const ( tagPrefix = "json:\"" tagSuffix = "\"" ) // parseTag splits a struct field's json tag into its name and comma-separated options. func parseTag(tag string) (string, string) { if !strings.HasPrefix(tag, tagPrefix) { return "", "" } if !strings.HasSuffix(tag, tagSuffix)...
package mobile_notificaion_service //`json:"omitempty"` type AndroidNotification struct { Id string TypeEnum int Title string Body string MeUserId int PeerUserId int PostId int GroupId int NotifyId int Sound string Vibrate string ChatKey string }
/* * @lc app=leetcode.cn id=21 lang=golang * * [21] 合并两个有序链表 */ // @lc code=start /** * Definition for singly-linked list. */ package main import "fmt" type ListNode struct { Val int Next *ListNode } func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil { return l2 } if...
package cli import ( "crypto/sha256" "encoding/json" "fmt" "github.com/DataDrake/cli-ng/v2/cmd" "github.com/libp2p/go-libp2p-core/crypto" "github.com/mr-tron/base58/base58" "github.com/multiformats/go-multihash" p2p "github.com/notassigned/p2p-tools/libp2p" ) var GenKey = cmd.Sub{ Name: "genkey", Alias: "...
package server import ( "github.com/hokora/bank/ipc" "github.com/hokora/bank/util" ) const ( GETTRANSACTIONS_ERR_SERVER = 1 GETTRANSACTIONS_ERR_USERNAME_NOT_EXIST = 2 ) func (s *Server) GetTransactionsHandler(ctx *ipc.Context) { pr := util.NewPacketReader(ctx.Packet) username := string(pr.ReadBytesWithLe...
package mhfpacket import ( "github.com/Andoryuuta/Erupe/network" "github.com/Andoryuuta/Erupe/network/clientctx" "github.com/Andoryuuta/byteframe" ) // Parser is the interface that wraps the Parse method. type Parser interface { Parse(bf *byteframe.ByteFrame, ctx *clientctx.ClientContext) error } // Builder is t...
/* Copyright © 2020 NAME HERE <EMAIL ADDRESS> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writi...
package autocert import ( "bytes" "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "crypto/x509/pkix" "encoding/base64" "encoding/json" "encoding/pem" "fmt" "io" "math/big" "net" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/caddyserver/certmagic" "github....
package instructionexec import ( "golib/taskexec/controller" "github.com/astaxie/beego/logs" ) //cmdIExecuter cmd指令执行器 var cmdIExecuter *CMDIExecuter func init() { if cmdIExecuter == nil { cmdIExecuter = &CMDIExecuter{} } controller.Register("CMD", cmdIExecuter) logs.Debug("Register CMD IExecuter.") }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //60. Permutation Sequence //The set [1,2,3,...,n] contains a total of n! unique permutations. //By listing and labeling all of the permutations in ord...
package log import ( "github.com/hxangel/dogo" ) type Access struct { dogo.Controller } func (c *Access) Index() { c.Assign("var","Demo") c.Assign("content","Demo") c.Render(); }
package main import ( "fmt" "math/big" "math/rand" ) func main() { r := rand.New(rand.NewSource(99)) //Want a variable seed p,_ := new(big.Int).SetString("71997739973919110306099993177739412743227643334286989217363396439283464537000853588029739004855929104754800897261407081024749574299035313695899693...
package stopka type Stack struct { stack []Value } func (s *Stack) Push(element Value) { s.stack = append(s.stack, element) } func (s *Stack) Pop() (Value, bool) { if s.IsEmpty() { return nil, false } top := s.stack[len(s.stack)-1] s.stack = s.stack[0 : len(s.stack)-1] return top, true } func (s *Stack) Is...
package main import ( "bytes" "crypto/tls" "encoding/base64" "errors" "fmt" "github.com/disintegration/imaging" "gopkg.in/alexcesaro/quotedprintable.v2" "html/template" "io" "io/ioutil" "mime" "mime/multipart" "net" "net/mail" "net/smtp" "os" "path/filepath" "regexp" "strings" "sync" "time" ) typ...
package mongodb import ( "context" "errors" "fmt" "sync" "testing" "time" "github.com/brigadecore/brigade/v2/apiserver/internal/api" "github.com/brigadecore/brigade/v2/apiserver/internal/lib/mongodb" mongoTesting "github.com/brigadecore/brigade/v2/apiserver/internal/lib/mongodb/testing" // nolint: lll "gith...
package assertion import ( "encoding/json" "fmt" jwt "github.com/golang-jwt/jwt" "github.com/lyokato/goidc/bridge" "github.com/lyokato/goidc/log" oer "github.com/lyokato/goidc/oauth_error" ) func HandleAssertionError(a string, t *jwt.Token, jwt_err error, gt string, c bridge.Client, sdi bridge.DataInterface, ...
package main import ( "flag" "fmt" "io/ioutil" "log" "math/rand" "net/http" "os" "sync" "time" ) var logger *log.Logger func init() { logger = log.New(os.Stdout, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile) } func durationFromString(ds string) (time.Duration, error) { if ds == "" { ds = "0s" } ...
package model type Str struct { S string `json:"source_string"` }
package main // normal solution func reverseList(head *ListNode) *ListNode { pre := &ListNode{} pre = nil cur := head for cur != nil{ next := cur.Next cur.Next = pre //reverse pre = cur cur = next } return pre } // recursively //func reverseList(head *ListNode) *ListNode { // if head == nil || head.N...
package tmhash import ( "hash" ghash "github.com/number571/go-cryptopro/gost_r_34_11_2012" ) const ( Size = ghash.Size256 BlockSize = ghash.BlockSize ) func New() hash.Hash { return ghash.New(ghash.H256) } func Sum(bz []byte) []byte { h := ghash.Sum(ghash.H256, bz) return h[:] } //--------------------...
package examples import ( "fmt" "time" ) func StartChannel() { main() } func main() { ch := make(chan string, 10) handA(ch) fmt.Printf("%s", <-ch) } func handA(ch chan string) { time.Sleep(time.Minute * 1) ch <- "ggg" } func Pipeline() { var handled = make(chan int) var printed = make(chan int) ...
package main import ( "context" "fmt" "log" "os" "os/signal" _ "github.com/austinjan/idps_server/config" "github.com/austinjan/idps_server/servers" "github.com/spf13/viper" ) func main() { logFile, err := os.Create("log") fmt.Println("idps server start version: ", viper.GetString("version")) if err != nil...
package main import ( "fmt" "io/ioutil" "os" "strconv" ) func readFile(filename string) string { filename = fmt.Sprintf("articles/%s", filename) file, err := ioutil.ReadFile(filename) if err != nil { panic(err) } return string(file) } func writeToFile(body string) string { filename := getNextFilename(...
/* Copyright IBM Corporation 2020 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 di...
package main import ( "fmt" "io/ioutil" "log" "net/http" "sync" ) func fetchUrl(url string, wg *sync.WaitGroup) { // Decrement the WaitGroup counter once we've fetched the URL defer wg.Done() response, err := http.Get(url) if err != nil { log.Fatal("Failed to fetch the URL, ", url, " and encountered this...
/* MIT License Copyright 2016 Comcast Cable Communications Management, LLC 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, cop...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03100104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.031.001.04 Document"` Message *CorporateActionNotificationV04 `xml:"CorpActnNtfctn"` } func (d *Document...
package controllers import ( "github.com/barrydev/api-3h-shop/src/actions" "github.com/barrydev/api-3h-shop/src/model" "github.com/gin-gonic/gin" "strconv" ) func GetListCategory(c *gin.Context) (interface{}, error) { var query model.QueryCategory err := c.ShouldBindQuery(&query) if err != nil { return nil...
package kyu8 import "math" func SquareOrSquareRoot(arr []int) []int { var result []int for _, num := range arr { rooted := math.Sqrt(float64(num)) if float64(int(rooted)) == rooted { result = append(result, int(rooted)) } else { result = append(result, int(math.Pow(float64(num), 2))) } } return resu...
package evs import ( "fmt" "os" "strings" ) var ( // Location of broker service default_broker = "pulsar://localhost:6650" // Pulsar topic persistency, should be persistent or non-persistent default_persistence = "non-persistent" // Tenant, default is public, only relevant in a multi-tenant deployment def...
package models // Products data model for products type Products struct { Model Name string `json:"name"` Description string `json:"description"` }
package response import "time" const ( SUCCESS = 200 ERROR = 500 InvalidParams = 400 ErrorPermission = 40001 ErrorExistTag = 10001 ErrorNotExistTag = 10002 ErrorNotExistArticle = 10003 ErrorAuthCheckTokenFail = 20001 ErrorAuthCheckTokenTimeout = 20002 ErrorAuthToken ...
package utils import ( "fmt" "io" "io/ioutil" "net/http" "strings" "github.com/iancoleman/strcase" "github.com/michaelawyu/cloudevents-generator/src/logger" "github.com/michaelawyu/cloudevents-generator/src/vfsgen" ) // FormatName is func FormatName(name string, style string) string { switch style { case "...
package queue // @author: jim_sun // @function: the block queue import ( "container/list" "context" "sync" "time" ) // BlockedLinkQueue 链表阻塞队列 type BlockedLinkQueue struct { list *list.List mu sync.Mutex notEmpty chan struct{} } // NewBlockedLinkQueue build the NewBlockedLinkQueue pointer func NewB...
package dal import ( "testing" "time" . "github.com/smartystreets/goconvey/convey" ) func Test_ping_group_unit(t *testing.T) { Convey("PingGroup", t, func() { pg := NewPingGroup(time.Now(), time.Now()) Convey("addResTime()", func() { Convey("should increment Received, sum Total, & set Min/Max", func() { ...
package app import ( "bytes" "io/ioutil" "os" "path/filepath" "testing" "github.com/SUSE/fissile/model" "github.com/SUSE/termui" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestValidation(t *testing.T) { ui := termui.New(&bytes.Buffer{}, ioutil.Discard, nil) workDir,...
package main import ( "fmt" "log" "net/http" ) type Struct struct { Saudacao string Fulano string } type String string func (s String) ServeHTTP (w http.ResponseWriter, r *http.Request) { for i:=0; i < 1000; i++{ fmt.Fprint(w, "Olá, Mundo!") } } func (t Struct) ServeHTTP (w http.ResponseWriter, r *http.Re...
package main import ( "log" "os" "github.com/go-telegram-bot-api/telegram-bot-api" ) const tokenEnv string = "TOKEN" const ipEnv string = "OPENSHIFT_GO_IP" const portEnv string = "OPENSHIFT_GO_PORT" type State uint const ( InitState = 0 ConfigState = 1 ReadyState = 2 ) func main() { token := os.Getenv(...
package main import ( "database/sql" "fmt" "time" ) import b "bench" func main() { b.WithpkClonePrint(1000, 1000) /* if err := BenchmarkSQLite3(1000000, 20); err != nil { panic(err) } */ } func BenchmarkSQLite3(numEmployees, numDept int) (err error) { start := time.Now() db, err := sql.Open("sqlite3...
package UserMicroservice import ( "MainApplication/internal/User/UserModel" "MainApplication/internal/User/UserRepository" "MainApplication/proto/UserServise" "context" ) type UserServiceManager struct { usClient userService.UserServiceClient } func New(client userService.UserServiceClient) UserRepository.UserD...
// range package main import "fmt" func main() { numeros := []int{2,4,6} suma := 0 for numero := range numeros { suma += numero } fmt.Println("suma:", suma) for i, numero := range numeros { if numero == 3 {} fmt.Println("index", i) } algo := map[string]string{"a": "auto", "b": "bebé"} for key, valu...
package main /* public class Program{ public static void main(String[] args) { Account<String> acc1 = new Account<String>("1876", 4500); Account<String> acc2 = new Account<String>("3476", 1500); Transaction<Account<String>> tran1 = new Transaction<Account<String>>(acc1,acc2, 4000); ...
package config // Config is the interface for each config version type Config interface { GetVersion() string Upgrade() (Config, error) } // New creates a new config type New func() Config // Variables strips all information from the config except variables type Variables func(data map[interface{}]interface{}) (ma...
package solutions /* * @lc app=leetcode id=326 lang=golang * * [326] Power of Three */ /* Your runtime beats 84.01 % of golang submissions Your memory usage beats 100 % of golang submissions (6.2 MB) */ // @lc code=start func isPowerOfThree(n int) bool { if n == 1 { return true } else if n == 0 { return fa...
package main import ( "strings" "github.com/gin-gonic/gin" ) func m3uHandler(c *gin.Context) { m3u := `#EXTM3U #EXTINF:-1,無綫新聞台 ${baseURL}tvb/inews.m3u8 #EXTINF:-1,無綫財經資訊台 ${baseURL}tvb/finance.m3u8 #EXTINF:-1,RTHK 31 ${baseURL}rthk/31.m3u8 #EXTINF:-1,RTHK 32 ${baseURL}rthk/32.m3u8 ` processedBody := strings.Rep...
package hello import "fmt" // Hello - Greet func Hello(name, language string) string { if name == "" { name = "World" } greetPrefix := prefix(language) return greetPrefix + name } func prefix(language string) (greetPrefix string) { switch language { case "Spanish": greetPrefix = "Hola, " case "French": ...
package quickstart import ( "context" "fmt" "github.com/kohge4/go-rakutenapi/rakuten" ) const ( applicationID = "ApplicationID" applicationSecret = "ApplicationSecret" affiliateID = "AffiliateID" ) func QuickStart() { ctx := context.Background() tp := rakuten.Transport{} // Rakuten API client c...
// +build !gm package magick // #include <magick/api.h> // #include "bridge.h" // #include "shear.h" import "C" // Rotate creates a new image that is a rotated copy of an existing one. Positive angles rotate counter-clockwise (right-hand rule), while negative angles rotate clockwise. func (im *Image) Rotate(degrees ...
package hook import ( "container/list" "fmt" "os" "os/signal" "sync" "syscall" ) type Hook struct { task *list.List lock sync.Mutex } var hookHandler = Hook{} func AddShutdownHook(runnables ...func() int) { defer hookHandler.lock.Unlock() hookHandler.lock.Lock() if hookHandler.task == nil { hookHandle...
package file_common type FileServingConfig struct { FileServerId int DiskDirs []string }
package main import ( "fmt" ) func main() { var text string var nRows int var r string text = "PAYPALISHIRING" nRows = 3 r = convert(text, nRows) fmt.Println(r) text = "PAYPALISHIRING" nRows = 1 r = convert(text, nRows) fmt.Println(r) text = "" nRows = 1 r = convert(text, nRows) fmt.Println(r) } func ...
package 双数组动态规划 // 状态: nums1[:i],nums2[:t] // 操作: 都不取、取A取B、取B不取A、取A不取B // 定义: 某状态下的最大点积 func maxDotProduct(nums1 []int, nums2 []int) int { n, m := len(nums1), len(nums2) if n == 0 || m == 0 { return 0 } dp := newMatrix(n+1, m+1) result := -100000000 for i := 1; i <= n; i++ { for t := 1; t <= m; t++ { resu...
package mock import ( "github.com/stretchr/testify/mock" ) type MockSessionStorage struct { mock.Mock } func (m *MockSessionStorage) Put(val string) { m.Called(val) } func (m *MockSessionStorage) Has(key string) bool { ret := m.Called(key) return ret.Bool(0) } func (m *MockSessionStorage) Remove(key string) {...
package paths import ( "fmt" "sort" "strings" graphite_tmpl "github.com/criteo/graphite-remote-adapter/client/graphite/template" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/prompb" ) // MetricLabelsFromTags provides labels for given tags. func MetricLabelsFromTags(tags map[string]str...
package lib func cacheHintRegistryList() string { return "catalog:" } func cacheHintTagList(repository string) string { return "pull:" + repository } func cacheHintTagDetails(repository string) string { return "pull:" + repository }
package main import ( "context" "fmt" pb "github.com/Donng/shipper/vessel-service/proto/vessel" ) type service struct { repo Repository } func (s *service) Create(ctx context.Context, req *pb.Vessel, res *pb.Response) error { if err := s.repo.Create(req); err != nil { return err } res.Vessel = req res.Cre...
package lib import ( "bytes" "errors" "io" "log" "sync" "time" "github.com/dchest/uniuri" "github.com/keroserene/go-webrtc" ) // Remote WebRTC peer. // Implements the |Snowflake| interface, which includes // |io.ReadWriter|, |Resetter|, and |Connector|. // // Handles preparation of go-webrtc PeerConnection. ...
// Copyright 2014 The Cockroach 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 ag...
package assembler func Saxplusbyvsetz(a float32, X []float32, b float32, Y []float32, V []float32, Z []float32) func saxplusbyvsetz(a float32, X []float32, b float32, Y []float32, V []float32, Z []float32) { for i := range X { Z[i] = a*X[i] + b*Y[i]*V[i] } }
/* Copyright [2015] Alex Davies-Moore 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, soft...
package kintone import ( "context" "fmt" "strconv" ) type ApiError struct { Method string RequestPath string StatusCode int ResponseBody string } func (e ApiError) Error() string { return fmt.Sprintf("method: %s, path: %s, status code: %s, body: %s", e.Method, e.RequestPath, strconv.Itoa(e.StatusCod...
package mailer import "strings" type Message struct { To []string From string Subject string Body string User string Type string Info string } // Create html mail message func NewHtmlMessage(to []string, from, userFrom, subject, body string) *Message { msg := NewMessage(to, from, userFrom...
package main import "fmt" func Sender(sendChannel chan<- int) { sendChannel <- 200 } func main() { sendChannel := make(chan int) go Sender(sendChannel) fmt.Println(<-sendChannel) }
package bus import ( "encoding/binary" "unsafe" "github.com/zyxar/berry/sys" ) const ( SMBUS_WRITE = iota SMBUS_READ ) const ( // SMBus transaction types SMBUS_QUICK = iota SMBUS_BYTE SMBUS_BYTE_DATA SMBUS_WORD_DATA SMBUS_PROC_CALL SMBUS_BLOCK_DATA SMBUS_I2C_BLOCK_BROKEN SMBUS_BLOCK_PROC_CALL /* SMBus ...
package metrics // Clone makes a clone of the Statsd client func Clone(tags ...map[string]string) *Statsd { return Get().Clone(tags...) } func Count(name string, n interface{}, tags ...map[string]string) { Get().Count(name, n, tags...) } // Increment increment the given name. It is equivalent to Count(name, 1). fu...
/* * @lc app=leetcode.cn id=476 lang=golang * * [476] 数字的补数 */ // @lc code=start func findComplement(num int) int { } // @lc code=end
package natpmp import ( "bytes" "fmt" "testing" "time" ) type callRecord struct { // The expected msg argument to call. msg []byte result []byte err error } type mockNetwork struct { // test object, used to report errors. t *testing.T cr callRecord } func (n *mockNetwork) call(msg []byte, timeout ...