text
stringlengths
11
4.05M
package main import ( "fmt" "math" ) type shape interface { area() float64 } type circle struct{ x,y,r float64 } type rect struct{ a,b float64 } func main() { c :=circle{0,0,4} r :=rect{4,5.26} fmt.Println(c.area()) fmt.Println(r.area()) fmt.Println(totalarea(&c,&r)) } func (c circle) area() float64{...
package controllers import ( "github.com/gin-gonic/gin" ) func GEThealth(c *gin.Context) { c.JSON(200, gin.H{ "Health Status": "Up and Running", }) }
package eventing import ( "github.com/kyma-incubator/reconciler/pkg/logger" "github.com/kyma-incubator/reconciler/pkg/reconciler/instances/istio" "github.com/kyma-incubator/reconciler/pkg/reconciler/service" ) const ( ReconcilerName = "eventing" actionName = "pre-action" ) //nolint:gochecknoinits //usage of...
package main import ( "fmt" "time" ) func main() { ch := make(chan int) // this will block /* <-ch fmt.Println("Here") */ go func() { // send number to the channel ch <- 353 }() // receive from the channel val := <-ch fmt.Printf("got %d\n", val) fmt.Println("-----") ...
package main //net/rpc 包允许 RPC 客户端程序通过网络或是其他 I/O 连接调用一个服务端对象的公开方法(大小字母开头)。在 RPC 服务端,需要将这个对象注册为可访问的服务,之后该对象的公开方法就能够以远程的方式提供访问。 import ( "net/http" "log" "net" "net/rpc" "errors" "rpc/utils" ) type MathService struct { } func (m *MathService) Multiply(args *utils.Args, reply *int) error { *reply = args.A * a...
package wservice import ( "time" "github.com/sad0vnikov/wundergram/logger" "github.com/sad0vnikov/wundergram/storage/tokens" "github.com/sad0vnikov/wundergram/wunderlist" "github.com/sad0vnikov/wundergram/wunderlist/wobjects" ) //GetUserTodayTasks returns users's today tasks func GetUserTodayTasks(userID int) (...
package main import ( "io" "os" "fmt" "sync" "strconv" "net/url" "net/http" "io/ioutil" "github.com/lestrrat/go-libxml2" ) type Request struct { url string header map[string]string } func (page Request) get_html() []byte { client := &http.Client{} req, _ := http.NewRequest("GET", page.url, nil) for ke...
package mysql import ( "database/sql" "fmt" "project/common/global" "project/utils" "project/utils/config" "go.uber.org/zap" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/schema" ) // Init 配置mysql gorm func Init(cfg *config.Mysql) (err error) { source := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8...
package main const u16bitmax float64 = 65533 const kphMultiple float64 = 1.60934 // This is my car type Car struct { gasPedal uint16 // 0 -> 65535 breakPedal uint16 steeringWheel int16 topSpeedKph float64 } func (c Car) kph() float64 { return float64(c.gasPedal) * (c.topSpeedKph / u16bitmax) } func (...
package notifier import ( "github.com/dollarshaveclub/acyl/pkg/models" "golang.org/x/sync/errgroup" ) //go:generate stringer -type=NotificationEvent // NotificationEvent models events that trigger notifications type NotificationEvent int const ( // CreateEnvironment occurs when an environment is created CreateE...
package go_utils import ( "regexp" "strings" ) // ignoreSpaces 是否去掉前后空格再判断 // isBlank("") = true // isBlank(" ") = false // isBlank("bob") = false // isBlank(" bob ") = false // isBlank("\r\n\t\f") = false func IsEmpty(str string, ignoreSpaces bool) bool { if ignoreSpaces { str = strings.T...
// @Description TODO // @Author jiangyang // @Created 2021/1/5 4:47 下午 package agora_test import ( "context" "encoding/json" "fmt" "github.com/comeonjy/util/agora" "github.com/comeonjy/util/config" "github.com/comeonjy/util/redis" "github.com/sirupsen/logrus" "testing" "time" ) const ( cname = "dem...
package sort func QuickSort(a []int) ([]int, error) { if len(a) <= 1 { return a, nil } if len(a) == 2 && a[0] > a[1] { a[0], a[1] = a[1], a[0] return a, nil } benchmarkValueIndex := 0 benchmarkValue := a[benchmarkValueIndex] for index, value := range a { // 跨过第一个元素 if index == 0 { continue } ...
package main import ( "bytes" "debug/elf" "flag" "fmt" "github.com/u-root/u-root/uroot" "io/ioutil" "log" "os" "os/exec" "path" "path/filepath" "strings" "text/template" ) type copyfiles struct { dir string spec string } const ( // huge suckage here. the 'old' usage is going away but it not gone yet...
package viewmodel type Home struct { Title string Sponsors []Sponsor Speakers []Speaker Counters []Counter } type Sponsor struct { ImageURL string Alt string } type Speaker struct { Duration int Name string Poste string Entreprise string ImageURL string Arialabel string Linkhref ...
package msg // Oauth 验证服务器 100 - 200 const ( OauthTopic = "Oauth_" // 验证服务器监听topic // 发送id OauthId = 100 // 总id 发送 OauthAccount = 101 // 验证账号msgId OauthAccountClose = 102 // 账号下线 // 返回id OauthAccountSuccess = 102 // 客户端成功返回代码 OauthAccountError = 103 // 客户端验证失败返回代码 OauthAc...
package poker_test import ( "bytes" "fmt" "github.com/eduardostalinho/go-with-tests/17_poker" "strconv" "strings" "testing" ) func TestCLI(t *testing.T) { userSends := func(inputs ...string) *strings.Reader { messages := strings.Join(inputs, "\n") + "\n" return strings.NewReader(messages) } t.Run("finis...
package config import "github.com/spf13/viper" type cache struct { MaxSize string } var Cache *cache func loadCacheConfig() { viper.SetDefault("cache.maxSize", "200M") //200 M Cache = &cache{ MaxSize: viper.GetString("cache.maxSize"), } }
package planner import ( "context" "errors" "fmt" "math" "strconv" "sync" "time" "github.com/radekwlsk/go-travel/gotravel/gotravelservice/planner/ants" "github.com/radekwlsk/go-travel/gotravel/gotravelservice/trip" "googlemaps.github.io/maps" ) const Iterations = 10000 type Planner struct { client *maps....
package main import ( "testing" "reflect" ) func TestPuzzleInput(t *testing.T) { expected := 638 lock := spinLock(3,2018) for i := range lock { if lock[i] == 2017 { if lock[i+1] != expected { t.Errorf("Oh No! Expected: %v, Got: %v",expected,lock[i+1]) } } } } func TestSpinLock(t *testing.T) { ...
// Package buffconn is only a test packge for go-callmeback. package buffconn import ( "context" "net" "time" "github.com/fenollp/grpc-callmeback-interceptor/go-callmeback" "github.com/grpc-ecosystem/go-grpc-middleware" "google.golang.org/grpc" "google.golang.org/grpc/test/bufconn" ) const ( pause = 1 * time...
package main import ( "github.com/mkj-gram/go_email_service/internal/emailprovider" "github.com/mkj-gram/go_email_service/internal/emailsender" "github.com/mkj-gram/go_email_service/internal/sendgrid" "github.com/mkj-gram/go_email_service/internal/server" "github.com/mkj-gram/go_email_service/internal/sparkpost" ...
package main import ( "bufio" "fmt" "github.com/logrusorgru/aurora" "log" "os" "regexp" ) func main() { file, err := os.Open(os.Args[2]) if err != nil { log.Fatal(err) } defer file.Close() s := bufio.NewScanner(file) rep := regexp.MustCompile(os.Args[1]) for s.Scan() { fmt.Println(rep.ReplaceAllStri...
package orm import ( "testing" "time" "github.com/iGoogle-ink/gotil/xlog" "github.com/iGoogle-ink/gotil/xtime" ) var ( dsn = "root:root@tcp(mysql:3306)/school?parseTime=true&loc=Local&charset=utf8mb4" ) type Student struct { Id int `gorm:"column:id;primary_key" xorm:"'id' pk"` Name string `gorm:"column:...
package router var ( EmptyErrorResponse = ErrorResponse{} ) type ErrorResponse struct { Code int `json:"-"` Message string `json:"message,omitempty"` InnerError error `json:"-"` } func NewErrorResponse(code int, message string) ErrorResponse { return ErrorResponse{code, message, nil} } func NewErrorResponseWit...
package evs import ( "context" "github.com/apache/pulsar-client-go/pulsar" "log" "os" "time" ) // Describes Users of the Analytic API implement the Handler interface. type Producer struct { name string // Pulsar client // FIXME: Should be shared across publisher/subscriber client pulsar.Client // Output ...
package service import "github.com/myownhatred/botAPI/pkg/repository" type Authorization interface { } type TodoList interface { } type TodoItem interface { } type Service struct { Authorization TodoItem TodoList } func NewService(rep *repository.Repository) *Service { return &Service{} }
package preoblem /* 125. 验证回文串 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我们将空字符串定义为有效的回文串。 示例 1: 输入: "A man, a plan, a canal: Panama" 输出: true 示例 2: 输入: "race a car" 输出: false 题目来源: https://leetcode-cn.com/problems/valid-palindrome/ 解题思路: 就是先整理原来的字符串, 在判断就行了 */ func isPalindrome(s string) bool { var trim ...
package tax var ( getTaxesQuery = `SELECT * FROM shopee_tax` getComponentsQuery = `SELECT * FROM shopee_tax_component` getTaxableProductsQuery = `SELECT a.*, b.code as "tax_code" FROM shopee_taxable_product as a INNER JOIN shopee_tax as b ON a.tax_category_id = b.id` insertTaxableProductQ...
package main import "fmt" func main() { switch { case false: fmt.Println("this should not print ") case (2 == 4): fmt.Println("This should not print2") case (3 == 3): fmt.Println("prints") fallthrough case (4 == 4): fmt.Println("also true, does it print?") } switch 1 { case 1: fmt.Println("1") ...
/* Copyright 2021 The KubeVela 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, softw...
package main import ( "flag" "fmt" "os" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1" "github.com/malware-unicorn/managed-bots/base" "github.com/malware-unicorn/managed-bots/canarybot/canarybot" "golang.org/x/sync/errgroup" ) type ...
package fetch import ( "encoding/base32" "encoding/json" "errors" "time" "github.com/slotix/dataflowkit/splash" "github.com/slotix/dataflowkit/storage" "github.com/slotix/dataflowkit/utils" "github.com/spf13/viper" ) type storageMiddleware struct { //storage instance puts fetching results to a cache storag...
package main import ( "fmt" "io" "net/http" "os" ) func first(w http.ResponseWriter,r *http.Request) { w.Write([]byte(`hello world`)) } func index(w http.ResponseWriter,r *http.Request) { r.ParseForm() //name :=r.Form.Get("name") name :=r.Form["name"] fmt.Println(name) f,err:=os.Open("./src/view/index.h...
package admin import ( "github.com/billyninja/pgtools/connector" "github.com/billyninja/pgtools/scanner" "github.com/julienschmidt/httprouter" "log" "net/http" "strings" ) var allTables []*scanner.Table var baseroute_ string var conn_ *connector.Connector func AutoRoute(rt *httprouter.Router,...
package sql import ( "testing" "github.com/kr/pretty" ) func TestQuery(t *testing.T) { user := Table("user") account := Table("account") accountStatus := Table("account_status") query := Select(user.AllColumns(), account.Column("id").GroupConcat()). From(user). InnerJoin(account.Column("user_id"), user.Co...
package cmd import ( "encoding/json" "fmt" "io" "io/ioutil" "net/http" "os" "os/exec" "runtime" "github.com/kardianos/osext" "github.com/spf13/cobra" ) type release struct { Version string `json:"tag_name"` } // updateCmd represents the update command var updateCmd = &cobra.Command{ Use: "self-update"...
package main import "fmt" func main() { //creating a slice var slice0 []int //len=0, cap=0, not init. (nil) fmt.Println(len(slice0), cap(slice0)) slice1 := []int{} //len=0, cap=0, init fmt.Println(len(slice1), cap(slice1)) slice2 := []int{42} //len=1, cap=1 fmt.Println(len(slice2), cap(slice2)) ...
package uri // KiConnect API URIs. const ( ResourceLinkHrefKey string = "resourceLinkHref" DeviceIDKey string = "deviceId" InterfaceQueryKey string = "interface" SkipShadowQueryKey string = "skipShadow" DeviceIDFilterQueryKey string = "deviceId" TypeFilterQueryKey string = "type" API stri...
package asm import ( "bytes" "encoding/binary" "encoding/hex" "errors" "fmt" "io" "math" "testing" qt "github.com/frankban/quicktest" ) var test64bitImmProg = []byte{ // r0 = math.MinInt32 - 1 0x18, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, } func TestRead...
/* Given a string as input, output the US state whose capital it is if it is a state capital, the capital of the state if it is a state, or Arstotzka if it is neither. Examples: Austin -> Texas Alaska -> Juneau The Nineteenth Byte -> Arstotzka All the capitals and their respective states: Baton Rouge, Louisiana Ind...
/** * Copyright (c) 2019. All rights reserved. * some functions deal with cache data of the groups * Author: tesion * Date: March 29th 2019 */ package group_cache import ( pb "api/talk_cloud" "encoding/json" "errors" "fmt" "github.com/gomodule/redigo/redis" "log" "model" "pkg/user_cache" "strconv" ) // ...
package bmalioss import ( "crypto/hmac" "crypto/sha1" "encoding/base64" "encoding/json" "errors" "fmt" "github.com/alfredyang1986/blackmirror/bmredis" "github.com/hashicorp/go-uuid" "io/ioutil" "log" "net/http" "net/url" "sort" "strings" "time" ) const appid = "LTAINO7wSDoWJRfN" const appsec = "PcDzLSO...
package helpers import ( "fmt" "io/ioutil" "net/http" "regexp" "time" ) type Table struct { Keyspace string Name string SizeBytes int64 IsYsql bool } type TablesFuture struct { Tables []Table Error error } // TODO: replace this with a call to a json endpoint so we don't h...
package leetcode import "testing" func TestLongestPalindrome(t *testing.T) { t.Log(longestPalindrome("babad")) t.Log(longestPalindrome("bababd")) t.Log(longestPalindrome("cbbd")) t.Log(longestPalindrome("abcda")) }
package tenniskata type tennisGame1 struct { score1 int score2 int player1Name string player2Name string } // TennisGame1 constructs a TennisGame for kata 1 func TennisGame1(player1Name string, player2Name string) TennisGame { return &tennisGame1{ player1Name: player1Name, player2Name: player2Name}...
package models import "github.com/go-ozzo/ozzo-validation" // Article represents an article record. type Article struct { Id int `json:"id" db:"id"` Title string `json:"title" db:"title"` Content string `json:"content" db:"content"` Author string `json:"author" db:"author"` } // Validate validates the...
package golibs var( BUILD_VERSION ="xxx.xxx.xx" BUILD_DATE_TIME = "xxxx-xx-xx xx:xx:xx" ApplicationName = "Application" OrganizationName = "xxxx" ) func GetVersionInfo()string{ return "\n===========================================\n"+ "Copyright(C) " + OrganizationName + "Ltd. all right ...
package database import ( "context" ) type ServiceMock struct { GetUserMock func(ctx context.Context, userID int64) (*Account, error) InsertUserMock func(ctx context.Context, dbUser *Account) (int64, error) } func (s ServiceMock) GetUser(ctx context.Context, userID int64) (*Account, error) { return s.GetUserM...
package Mysql import ( "xwork/Extend/DB" "xwork/Extend/Gophp" "fmt" "time" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) // Cache Memcache adapter. type Db struct { conn *gorm.DB server string conninfo string maxIdle int ma...
package tcp import ( "context" "github.com/vlorc/lua-vm/base" vmnet "github.com/vlorc/lua-vm/net" ) func NewTCPFactory(driver vmnet.NetDriver, opt ...func(*TCPFactory)) *TCPFactory { o := &TCPFactory{ driver: driver, context: context.Background(), connectTimeout: base.Duration(5000), listen...
package ql720nw import ( "errors" "fmt" "net" ) var boolOneZeroMap = map[bool]string { false: "0", true: "1", } type Ql720nw struct { conn net.Conn } func (q *Ql720nw) ReInit() (err error) { _, err = q.conn.Write([]byte("\x1B@")) return } func (q *Ql720nw) PageFeed() (err error) { _, err = q.conn.Write([]...
package main import ( "fmt" "sort" "time" ) func main() { ch := make(chan int) go func() { for { select { case v, ok := <-ch: fmt.Println(v, "1") if !ok { return } } } }() go func() { for { select { case v, ok := <-ch: fmt.Println(v, "2") if !ok { return ...
package controllers /* 购买这个操作需要单独提供一个服务来进行支持 使用时间驱动模型来解决库存问题 1. 库存锁定问题 2. */ import ( "errors" "fmt" "runtime" "sync" ) //type ShopEvent struct { // //购物事件 // User models.User // GoodDetail models.GoodDetail // Num int // // 当购物事件处理完成之后进行回调 // Controller *controllers.IndexController //} type SecOrderResultchan...
package gcloud // ServiceAccount is google service account type ServiceAccount struct { ProjectID string `json:"project_id"` ClientID string `json:"client_id"` ClientEmail string `json:"client_email"` }
package config import ( "time" "github.com/imrenagi/go-payment" ) // NewFreeFee returns a fee config reader which has no fee at all func NewFreeFee(gateway payment.Gateway) FeeConfigReader { return &freeFee{ gateway: gateway, } } type freeFee struct { gateway payment.Gateway } func (f freeFee) GetGateway() ...
package network import ( "encoding/hex" "encoding/json" "eos-network/config" "eos-network/crypto" "fmt" "github.com/emicklei/go-restful" "github.com/pkg/errors" "io/ioutil" "strconv" "strings" "time" ) type RestMgr struct { } func NewRestMgr() *RestMgr { return &RestMgr{} } func (r *RestMgr) Register(co...
package bmkafka import ( "fmt" "github.com/alfredyang1986/blackmirror/bmerror" "github.com/confluentinc/confluent-kafka-go/kafka" "sync" ) var producer *kafka.Producer var onceProducer sync.Once // GetProducerInstance get one KafkaProducerInstance. func (bkc *Config) GetProducerInstance() (*kafka.Producer, error...
package multiplication import ( "testing" "../matrix" ) // Std benchmarks func BenchmarkStandart3x3(b *testing.B) { m1 := matrix.Zeros(3, 3) m2 := matrix.Zeros(3, 3) for i := 0; i < b.N; i++ { Multiply(m1, m2) } } func BenchmarkStandart9x9(b *testing.B) { m1 := matrix.Zeros(9, 9) m2 := matrix.Zeros(9, 9)...
package parquet import "testing" func assertCompare(t *testing.T, a, b Value, cmp func(Value, Value) int, want int) { if got := cmp(a, b); got != want { t.Errorf("compare(%v, %v): got=%d want=%d", a, b, got, want) } } func TestCompareNullsFirst(t *testing.T) { cmp := CompareNullsFirst(Int32Type.Compare) assert...
package controllers import ( "chatAppServer/models" "encoding/json" ) /*MsgController 消息控制器 */ type MsgController struct{ UserController } /*MsgResult 返回结果 */ type MsgResult struct { Status int `json:"status"` Msg string `json:"msg"` Data []models.SysMsg `json:"data" description:"用户消息...
package main_test import ( "fmt" "math" "testing" main "github.com/tehwalris/coffee-random/backend" ) func TestWeightedRand(t *testing.T) { iterations := 10000 tolerance := 0.01 cases := []struct { weights []float32 prob []float32 // Probability for each index (sum 1). Nil if error expected. }{ {[]...
package main import ( "fmt" "strconv" ) func test(){ i:=int32(97) ret2:=fmt.Sprintf("%d",i) //这里将int32类型转换为string类型 fmt.Printf("%#v\n",ret2) //string类型 } func strconvtest(){ str:="666" ret,err:=strconv.ParseInt(str,10,64) //把字符串转换为64位的十进制int类型 if err!=nil{ fmt.Printf("parse int failed,err:",err) ret...
package config import ( "log" "math/rand" "time" "github.com/blang/semver" sd "crazyant.com/deadfat/data/go" ) const ( bTimeFmt = "20060102T15:04:05-07:00" defaultRankMatchWaitSec = 15 * time.Second defaultRankScan = 3 * time.Second ) type Tiers struct { Lv int32 Score int32 Up...
package main import "fmt" func main() { //// 声明一个传递整型的管道 //var ch1 chan int //// 声明一个传递布尔类型的管道 //var ch2 chan bool //// 声明一个传递int切片的管道 //var ch3 chan []int // //// 创建一个能存储10个int类型的数据管道 //ch1 = make(chan int, 10) //// 创建一个能存储4个bool类型的数据管道 //ch2 = make(chan bool, 4) //// 创建一个能存储3个[]int切片类型的管道 //ch3 = make(...
package leetcode import "fmt" func dayOfYear(date string) int { var y, m, d int fmt.Sscanf(date, "%d-%d-%d", &y, &m, &d) leap := false if y%400 == 0 { leap = true } else if y%100 != 0 && y%4 == 0 { leap = true } days := []int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} ans := 0 if m >= 3 && leap {...
package common // 工具函数
package utils import ( "github.com/pkg/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/klog" "github.com/litmuschaos/chaos-operator/pkg/apis/litmuschaos/v1alpha1" ) //NOTE: The hostFileVolumeUtils doesn't contain the function to derive hostFileVols from chaosengine //and thereby, the corresponding ...
package repo import ( "testing" "github.com/abhinav/git-pr/gateway/gatewaytest" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" ) func TestGuess(t *testing.T) { tests := []struct { url string want Repo wantErr string }{ {url: "git@github.com:foo/bar", want: Repo{Owner: "foo", ...
//go:build windows // +build windows package sys import ( "os/exec" "syscall" "time" ) func CmdWait(cmd *exec.Cmd, timeout time.Duration) (error, bool) { var err error done := make(chan error) go func() { done <- cmd.Wait() }() select { case <-time.After(timeout): go func() { <-done // allow gorout...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package engine import ( "github.com/Azure/aks-engine/pkg/api" "github.com/Azure/aks-engine/pkg/api/vlabs" "github.com/Azure/aks-engine/pkg/i18n" ) // VlabsContainerService is the type we read and write from file // nee...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //770. Basic Calculator IV //Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvar...
package main import ( "fmt" "net/http" ) func doLogin(w http.ResponseWriter, req *http.Request) { var userName = req.FormValue("username") var password = req.FormValue("password") if userName == "Alvin" && password == "awawaw" || userName == "Agnes" && password == "octaviani" { fmt.Fprintf(w, "Hello, "+us...
package proximo import ( "context" "errors" "github.com/utilitywarehouse/go-pubsub" "github.com/utilitywarehouse/go-pubsub/proximo/internal/proximoc" ) var _ pubsub.MessageSource = (*messageSource)(nil) type messageSource struct { consumergroup string topic string broker string } type Message...
package main import ( _ "embed" "os" "text/template" ) const templateText = ` {{- "" -}} Go templates are {{ index .Emojis "fire" }}! {{ if not (eq .ScaryThing "") }}Just do not get scared by the "{{ .ScaryThing }}" and you will {{ index .Emojis "heart"}} them! {{ end }} {{- "" -}} ` const templateTextView = ` {{...
package main import ( "bufio" "os" "fmt" "strconv" "strings" ) type petrolPump struct{ fuel int distanceNext int } func getPumpStations()[]petrolPump { scanner := bufio.NewScanner(os.Stdin) scanner.Scan() scanner.Text() pumps := make([]petrolPump, 0) for scanner.Scan()...
/* You are given an integer array nums of length n, and an integer array queries of length m. Return an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i]. A subsequence is an array that can b...
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package ptrace import ( "testing" "time" "github.com/stretchr/testify/assert" "go.opentelemetry.io/collector/pdata/pcommon" ) var tracesOTLP = func() Traces { td := NewTraces() rs := td.ResourceSpans().AppendEmpty() rs.Resource()....
package ptp const ( flagTruncated = 0x1 iffTun = 0x1 iffTap = 0x2 iffOneQueue = 0x2000 iffnopi = 0x1000 ) type ifReq struct { Name [0x10]byte Flags uint16 pad [0x28 - 0x10 - 2]byte }
package gcloudfn import ( "crypto/rand" "encoding/json" "fmt" "net/http" "os" "strings" "github.com/google/uuid" "github.com/senslabs/alpha/sens/errors" "github.com/senslabs/alpha/sens/httpclient" "github.com/senslabs/alpha/sens/logger" "github.com/senslabs/alpha/sens/types" "golang.org/x/crypto/bcrypt" )...
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { s := bufio.NewScanner(os.Stdin) s.Scan() n, _ := strconv.Atoi(s.Text()) items := make([]int, 0) prints := make([]int, 0) for i := 0; i < n; i++ { s.Scan() vals := strings.Split(s.Text(), " ") switch vals[0] { case "1": ...
// +build !mock package synapse import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) var credentials map[string]interface{} var requestData map[string]interface{} var userID string = "5e6917b85b5a1e0081e0e309" // Change this to test a user on your platform var testID string var authKey strin...
package 数 func hammingWeight(num uint32) int { return HammingWeight(int(num)) // 二进制内部表示是相同的,因此 uint32 -> int 并不影响结果。 } // HammingWeight 获取汉明重量。 func HammingWeight(num int) int { count := 0 for num != 0 { num = removeLowestOne(num) count++ } return count } // removeLowestOne 移除最低位1。 func removeLowestOne(num...
package utils import ( "github.com/robertkrimen/otto" "reflect" ) func SliceToJavascriptArray(js *otto.Otto, slice interface{}) otto.Value { if reflect.TypeOf(slice).Kind() != reflect.Slice { panic("You must pass in a slice to utils.SliceToJavascriptArray") } val := reflect.ValueOf(slice) arr, _ := js.Object(...
package main import () type List struct { Begin int End int Num int }
package blobstore import ( "bytes" "crypto" "crypto/sha1" "encoding/hex" "hash" "io" "io/ioutil" "os" "sort" "strings" "testing" ) var testData = []struct { input, expectedHash, expectedPath string }{ {"Hola!", "f648cdc2cee763f6cb9087a0580729712d93250e", "f6/48/cd/c2/f648cdc2cee763f6cb9087a0580729712...
package clients import ( "github.com/golang/protobuf/protoc-gen-go/generator" "github.com/twoism/protoc-gen-example/clients/ruby" ) func GenerateAll(gen *generator.Generator) { for _, file := range gen.Request.GetProtoFile() { for _, srv := range file.GetService() { // Generate http python client and server c...
package arrays func zero(a [][]int) [][]int { n := len(a) columns := make(map[int]bool) rows := make(map[int]bool) for i := 0; i < n; i++ { for j := 0; j < n; j++ { if a[i][j] == 0 { columns[i] = true rows[j] = true } } } for i := 0; i < n; i++ { for j := 0; j < n; j++ { _, ok1 := column...
package collector import ( "database/sql" "log" "os" "strconv" "github.com/morhekil/goratio/feeder/data" ) // fetch next row from the query results, and create page struct of it func fetch(xs *sql.Rows) (uint64, *data.Event) { id, x, err := scan(xs) if err != nil { log.Fatalf("fetch failed: %s", err) } re...
package cmd import ( "errors" "fmt" "io/ioutil" "os" "os/exec" "strings" "regexp" "github.com/fatih/color" "github.com/spf13/cobra" ) var file string // applyCmd represents the apply command var applyCmd = &cobra.Command{ Use: "apply", Short: "Apply the format to a commit message", Long: `Applies the...
package utils import ( "errors" "net" "strconv" ) func GetListenerPort(listener net.Listener) (int, error) { if listener == nil { return 0, errors.New("nil listener") } _, portStr, err := net.SplitHostPort(listener.Addr().String()) if err != nil { return 0, err } port64, err := strconv.ParseInt(portStr...
// Package maij should trigger TestGoDocPackageNameReject package main import ( "strings" "testing" ) func reject(t *testing.T, filename, funcname string) { chk := &docCheck{} for _, ct := range chk.get(t, filename).ct { if strings.Contains(ct.ctok.lit, funcname) { return } } t.Fatal("did not flag bad te...
package address import ( "incognito-chain/privacy/operation" ) type PrivateAddress struct { privateSpend *operation.Scalar privateView *operation.Scalar } // Get Public Key from Private Key func GetPublic(private *operation.Scalar) *operation.Point { return new(operation.Point).ScalarMultBase(private) } func (...
package projector type Command interface { Prefixes() []string Request() string Handle(string) } var SupportedCommands = []Command{ &Freeze{}, &Power{}, &Blank{}, }
package routers import ( "github.com/astaxie/beego/context" ) func GetIp(ctx *context.Context) (ip string){ ip=ctx.Input.IP(); if("::1"==ip){ ip="127.0.0.1"; } return; }
package _290_Word_Pattern import "strings" func wordPattern(pattern string, str string) bool { var pm = make(map[rune][]int) for idx, b := range pattern { idxs, _ := pm[b] idxs = append(idxs, idx) pm[b] = idxs } strs := strings.Split(str, " ") if len(strs) != len(pattern) { return false } var diffWord ...
package repository import ( "github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/entity" "gorm.io/gorm" ) type ReportRepository interface { DetailReportByEvent(eventId uint) ([]entity.Report, error) GetAllSummaryEvent() ([]entity.SummaryReport, error) GetAllSummaryEventByCreator(creatorId uint...
package api import "database/sql" var DataBasePtr *sql.DB
/* Copyright 2011 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 writing, software di...
package gout import ( "bytes" "fmt" "io" "io/ioutil" "net/http" "os" "strings" ) type DebugOption struct { Write io.Writer Debug bool Color bool } type DebugOpt interface { Apply(*DebugOption) } type DebugFunc func(*DebugOption) func (f DebugFunc) Apply(o *DebugOption) { f(o) } // 暂时不启用 /* func DebugC...