text
stringlengths
11
4.05M
package main import ( "go/scanner" "go/token" "io/ioutil" "os" ) type TokenSet map[string]struct{} // GoTokens gets the tokens from set of source files. func GoTokens(srcpaths []string) (toks TokenSet, err error) { tokc := make(chan []string) errc := make(chan error) fs := token.NewFileSet() files := 0 for...
// Copyright 2013 Benjamin Gentil. All rights reserved. // license can be found in the LICENSE file (MIT License) package zlang import ( "fmt" "strings" "unicode" "unicode/utf8" ) const ( LeftBlockDelim = '{' RightBlockDelim = '}' LeftParentDelim = '(' RightParentDelim = ')' ParamDelim = ',' ...
package main import ( "log" "logindemo/config" "logindemo/controler" "logindemo/db" "net/http" "github.com/gorilla/mux" ) func main() { db.Connect() handleRequests() } func handleRequests() { r := mux.NewRouter() r.HandleFunc("/api/register", controler.SignUpUser).Methods("POST") r.HandleFunc("/api/l...
package store import ( goredis "github.com/go-redis/redis" "time" ) var LogDB redisClient type redisClient interface { ZAdd(key string, val string) error ZRange(keys []string) (map[string][]string, error) LPush(key, val string) error LRange(key string) ([]string, error) Close() error } type redis struct { c...
package binance_test import ( "github.com/ramezanius/crypex/exchange/binance" "github.com/ramezanius/crypex/exchange/tests" ) func (suite *binanceSuite) TestSubscribeReports() { suite.NoError(suite.exchange.SubscribeReports()) suite.TestOrders() tests.Wait() suite.NoError(suite.exchange.UnsubscribeReports()) ...
package daos import ( wm "github.com/constant-money/constant-web-api/models" "github.com/jinzhu/gorm" "github.com/pkg/errors" ) type CollateralLoanDAO struct { db *gorm.DB } // InitCollateralLoanDAO : func InitCollateralLoanDAO(database *gorm.DB) *CollateralLoanDAO { return &CollateralLoanDAO{ db: database, ...
package main import ( "Fit-Time-Backend/controllers" "log" "net/http" ) func main() { // List of Routes http.HandleFunc("/", controllers.Hello) // Starts the http server err := http.ListenAndServe(":8090", nil) if err != nil { log.Println(err.Error()) } }
package p01 // Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func qs(a []int, left, right int) { if left >= right { return } i, j := left, right p := a[left] for i < j { for i < j && a[j] >= p { j-- } if i < j { a[i] = a[j] } for i < j ...
package robotmsg import ( "fmt" "github.com/grearter/rpa-agent/api" "github.com/sirupsen/logrus" ) // List 获取未Pulled的消息列表 func List() (messageAPIs []*api.RobotMessage, err error) { sql := fmt.Sprintf("SELECT * from %s WHERE pulled = false", tableName) rows, err := sqliteDB.Query(sql) if err != nil { logrus.E...
package main import ( "fmt" ) func main() { si := []int{1, 2, 3, 4, 5, 6, 82} si2 := []int{1, 22, 3, 4, 76, 82} fmt.Println(funcao1(si...)) fmt.Println(funcao2(si2)) } func funcao1(x ...int) int { total := 0 for _, v := range x { total += v } return total } func funcao2(x []int) int { total := 0 for ...
package subscription import ( "context" watchv1 "github.com/syncromatics/kafmesh/internal/protos/kafmesh/watch/v1" "github.com/pkg/errors" "google.golang.org/grpc" ) // ClientFactory generates WatchClients for a pod type ClientFactory struct{} // Client gets a Watch client for an address func (f *ClientFactory...
package server import ( "fmt" "log" "net" "net/http" _ "net/http/pprof" "runtime" "sync" "github.com/danmrichards/udpecho/internal/utils" ) // EchoServer is a UDP server that echos packets back to the sender. type EchoServer struct { c net.PacketConn workers int done chan struct{} wg sync.W...
package main // EQR ... var EQR fc = func(en bool, args ...interface{}) []interface{} { return []interface{}{en && (args[0].(float64) == args[1].(float64))} } // GTR ... var GTR fc = func(en bool, args ...interface{}) []interface{} { return []interface{}{en && (args[0].(float64) > args[1].(float64))} } // LTR ... ...
package container type Container struct { Id string Root string Config *Config }
/* it's a-me! Today's task is simple: write a program, or a function that displays the idle small Mario sprite, from Super Mario Bros, on NES, over a blue background. Any kind of entry is valid as long as it displays those 12 * 16 pixels anywhere on the screen / window / browser. (EDIT: the displayed image can be s...
package actions import ( "errors" "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 GetCategoryTreeById(categoryId int64) (*model.CategoryTree, error) { query := connect.QueryMySQL{ QueryString: "WHERE parent_...
package redix import ( "fmt" "github.com/garyburd/redigo/redis" ) type Connx struct { readWho string // "src" , "dest srcConn redis.Conn destConn redis.Conn } func NewConnx(srcConn redis.Conn, destConn redis.Conn, readWho string) *Connx { return &Connx{ readWho: readWho, srcConn: srcConn, destConn: d...
package utils import ( _ "github.com/denisenkom/go-mssqldb" "github.com/jmoiron/sqlx" ) var Db *sqlx.DB //init函数先于main函数执行,初始化操作 func init() { var err error // connStr := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;", server, user, password, port, database) Db, err = sqlx.Open(`sqlserver`,...
// Copyright 2019-2023 The sakuracloud_exporter 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 appl...
package storage import ( "encoding/json" "fmt" "testing" "time" "github.com/stretchr/testify/suite" "go-gcs/src/config" "go-gcs/src/entity" "go-gcs/src/service" "go-gcs/src/service/googlecloud/storageprovider" ) type GoogleCloudStorageSuite struct { suite.Suite sp *service.Container } func (suite *Google...
package frontend import ( "encoding/json" "io/ioutil" "net/http" "path/filepath" "github.com/jim-minter/rp/pkg/api" ) func (f *frontend) postOpenShiftClusterCredentials(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Content-Type") != "application/json" { api.WriteError(w, http.StatusUnsupportedMe...
package queue import l "list" // Queue implements a basic queue // Enqueue / Dequeue type Queue struct { list l.List } // Enqueue enqueues a value func (q *Queue) Enqueue(value int) { q.list.InsertAt(value, 1) } // Dequeue dequeues a value func (q *Queue) Dequeue() int { dequeued := q.Back() q.list.DeleteAt(q.l...
/* * @lc app=leetcode.cn id=154 lang=golang * * [154] 寻找旋转排序数组中的最小值 II */ package solution // @lc code=start func findMin(nums []int) int { head, tail := 0, len(nums)-1 for head < tail { mid := (head + tail) / 2 if nums[mid] < nums[tail] { tail = mid } else if nums[mid] > nums[tail] { head = mid + 1...
package usecase import ( "errors" "github.com/huf0813/pembukuan_tk/entity" "github.com/huf0813/pembukuan_tk/repository/sqlite" ) type CustomerUseCase struct { CustomerRepo sqlite.CustomerRepo } type CustomerUseCaseInterface interface { GetCustomers() ([]entity.Customer, error) AddCustomerValidation(name, phone...
package system_test import ( "testing" "github.com/kumahq/kuma/pkg/test" ) func TestSystem(t *testing.T) { test.RunSpecs(t, "System Suite") }
package main import "fmt" // struct pengganti class pada OOP type Siswa struct { nama, kelas string umur int } // menambahkan method ke struct func (s Siswa) getNama() (nama string) { // (s Siswa) menandakan method ini milik Siswa nama = fmt.Sprintf("Nama Saya %v \n", s.nama); // dan variabel s menjadi cara m...
// Copyright (c) 2020 Zededa, Inc. // SPDX-License-Identifier: Apache-2.0 package utils import ( "errors" "fmt" "os" "github.com/lf-edge/eve/pkg/pillar/base" "github.com/lf-edge/eve/pkg/pillar/cas" "github.com/lf-edge/eve/pkg/pillar/containerd" "github.com/lf-edge/eve/pkg/pillar/diskmetrics" "github.com/lf-e...
package back import ( "log" ) const ( SC_URL = "https://docs.google.com/spreadsheets/d/1ud6IZFjoT0Hyvh6TjbGq7czDezs9M3ODqEKysQ04h8E/pub?gid=0&single=true&output=csv" ) func SiteCopy() ([][]string, error) { data, err := readCSVFromUrl(SC_URL) if err != nil { log.Println(err) return nil, err } return data, ...
package service import ( "io" "project/app/admin/models" "project/app/admin/models/bo" "project/app/admin/models/cache" "project/app/admin/models/dto" cache2 "project/common/cache" "project/utils" "go.uber.org/zap" ) type Dept struct { } func (d *Dept) SelectDeptList(de *dto.SelectDeptDto, orderData []bo.Or...
package gosnowth import ( "bytes" "testing" ) func TestScanMetricName(t *testing.T) { t.Parallel() cases := []struct { input string // input tok scanToken // token lit string // metric name literal }{ { input: "testing", tok: tokenMetric, lit: "testing", }, { input: "testin...
package middleware import ( "fmt" "github.com/juju/errgo" "log" "net/http" "os" "runtime/debug" ) type Recovery struct { Logger *log.Logger } func NewRecovery() *Recovery { return &Recovery{ Logger: log.New(os.Stdout, "[klask] ", 0), } } func (self *Recovery) ServeHTTP( res http.ResponseWriter, req *ht...
package second import "fmt" type GetName interface { getName() string } type Student struct { Name string Age int ID string } type Teacher struct { Name string } func (s Student) getName() string { return s.Name + "@gmail.com" } func (t Teacher) getName() string { return t.Name + "@gmail.com" } //expor...
// Copyright 2023 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 ...
package solutions import "math" /* * @lc app=leetcode id=7 lang=golang * * [7] Reverse Integer */ /* Your runtime beats 100 % of golang submissions Your memory usage beats 56.43 % of golang submissions (2.1 MB) */ // @lc code=start func reverse(x int) int { sum := 0 for x != 0 { n := x % 10 if sum > math....
package main import "fmt" // 59. 螺旋矩阵 II // 给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 // 示例: // 输入: 3 // 输出: // [ // [ 1, 2, 3 ], // [ 8, 9, 4 ], // [ 7, 6, 5 ] // ] // https://leetcode-cn.com/problems/spiral-matrix-ii/ func main() { fmt.Println(generateMatrix(3)) fmt.Println(generateMatrix2(3)) } // 法一...
// Copyright 2020 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 setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01800104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.018.001.04 Document"` Message *RequestForOrderStatusReportV04 `xml:"ReqForOrdrStsRpt"` } func (d *Docume...
/* 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...
/** * Created with IntelliJ IDEA. * User: Administrator * Date: 14-2-25 * Time: 下午4:40 * To change this template use File | Settings | File Templates. */ package main import ( "net" // "log" "packet" // "os" "sync" "time" //"fmt" "common" "runtime" // "helper" ) //// 命令接口 //type CmdInterface interfac...
package sqlbuilder import ( "fmt" "strings" ) type table struct { name string joinType int joinConstraints []SQLProvider subQuery SQLProvider } func (t *table) GetSQL(cache *VarCache) string { if t.joinType == join_none { if t.subQuery != nil { return t.subQuery.GetSQL(cache) ...
package explain import ( "github.com/pkg/errors" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" ) func lookup(schema *apiextv1.JSONSchemaProps, path []string) (*apiextv1.JSONSchemaProps, error) { if len(path) == 0 { return schema, nil } properties := map[string]apiextv1.JSONSchemaProps{} ...
package mongodb import ( "github.com/b2wdigital/goignite/pkg/config" "log" ) const ( ConfigRoot = "transport.client.mongodb" Uri = ConfigRoot + ".uri" HealthEnabled = ConfigRoot + ".enabled" HealthDescription = ConfigRoot + ".health.description" HealthRequired = ConfigRoot + ".health.r...
package service import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strings" "time" "github.com/sirupsen/logrus" "github.com/Hudayberdyyev/weather_api/models" "github.com/Hudayberdyyev/weather_api/pkg/repository" ) const ( APIKey = "559cd760f10f8731db7e748be0666c37" URL = "http...
func uncommonFromSentences(A string, B string) []string { s1:=strings.Split(A," ") s2:=strings.Split(B," ") m:=make(map[string]int) res:=[]string{} for _,v:=range s1{ m[v]+=1 } for _,v:=range s2{ m[v]+=1 } for k,v:=range m{ if v==1 && len(k)>0{ res...
package core import ( "fmt" "image/color" "math" "math/rand" ) //Vec3 contains 3 components - can //be used to represent colors, points, vectors etc. type Vec3 struct { X, Y, Z float64 } func Clamp(x float64, min float64, max float64) float64 { if x < min { return min } if x > max { return max } return...
package main import ( "bytes" "fmt" "net/http" "os" "strings" ) func main() { if body, err := http.Get(`http://checkip.amazonaws.com/`); err == nil { buffer := new(bytes.Buffer) buffer.ReadFrom(body.Body) fmt.Println(strings.TrimSpace(buffer.String())) } else { errorMessage := fmt.Sprintf("+%v", err) ...
package cmd import ( "fmt" "os" "github.com/ovh/venom" ) // Exit func display an error message on stderr and exit 1 func Exit(format string, args ...interface{}) { fmt.Fprintf(os.Stderr, format, args...) venom.OSExit(1) }
package main import ( "crypto/sha256" "fmt" ) func main() { hasher := sha256.New() fmt.Println(hasher.Sum([]byte("hello world"))) fmt.Printf("%d\n", hasher.Sum([]byte("hello world"))) }
package compress import ( "bytes" "compress/flate" "fmt" "io" "io/ioutil" "reflect" "testing" "github.com/gobwas/ws" "github.com/gobwas/ws/wsutil" ) func TestCompressWriter(t *testing.T) { for i, test := range []struct { label string level int fragmented bool seq [][]byte result ...
// 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 applicable law or agreed to in writing...
package codegen const goTemplate = ` // Generated by Meduza. Do not rewrite unless you know what you're doing... package model import "github.com/EverythingMe/meduza/schema" {{ define "Column" }}\ {{ .GoName }} schema.{{.Type}} ~db:"{{.Name}}\ {{ if .Options.required }},required{{end}}"\ {{ if .Options.max_len }} m...
package main import ( "fmt" "testing" ) func scoreChecker(input []Frame, expectedScore int, expectedError error) error { score, err := GetScore(input) if err != expectedError && !(err != nil && expectedError != nil && err.Error() == expectedError.Error()) { return fmt.Errorf("Score error : %+v, expected %+v",...
package clock import "fmt" // Clock represents a time without dates. type Clock struct { hour, minute int } // New returns a new Clock at hour:minute. func New(hour, minute int) Clock { hour += minute / 60 minute %= 60 if minute < 0 { minute += 60 hour -= 1 } hour %= 24 if hour < 0 { hour += 24 } re...
package user import ( "github.com/gin-gonic/gin" "net/http" "github.com/jinzhu/gorm" "fmt" "beaver/user/usermodel" "beaver/apputils" ) func UserRouter(router *gin.RouterGroup, db gorm.DB) { router.GET("", func(ctx *gin.Context) { result := usermodel.Fetch(&db) fmt.Println(result) ctx.JSON(http.StatusOK,...
package orm import ( "DataApi.Go/database/models/YPA" "DataApi.Go/lib/common" "fmt" "github.com/jinzhu/gorm" "strings" ) type YpaSourceReportDaily = YPA.YpaSourceReportDaily func SelectBetweenDailyYpa(db *gorm.DB, startDate int, endDate int) []common.JSON { table := "ypa_source_report_daily" var ypaSourceRepo...
// Copyright © 2017 Jimmy Song // // 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 pt import ( "bufio" "fmt" "io" "net" "time" "golang.org/x/net/proxy" "net/url" "strconv" "encoding/binary" ) const ( socksVersion = 0x04 socksCmdConnect = 0x01 socksResponseVersion = 0x00 socksRequestGranted = 0x5a socksRequestRejected = 0x5b ) // Put a sanity timeout on how long ...
// 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 utils import "github.com/lucasjones/reggen" func GenerateCodeForOrder () (string,error){ return reggen.Generate("[0-9]{2}[a-z]{3}[A-Z]{3}", 8) }
package main import ( "flag" "fmt" ) var ( flagConfigFile = flag.String("config", "./config.yml", "Path to configuration file") flagDryRun = flag.Bool("dry-run", false, "Dry run mode") cfg *Config ) func InArray(k string, arr []string) bool { for _, val := range arr { if val == k { return t...
package users import ( "time" rand "github.com/Pallinder/go-randomdata" uuid "github.com/satori/go.uuid" log "github.com/sirupsen/logrus" bh "github.com/timshannon/bolthold" bolt "go.etcd.io/bbolt" "github.com/Zenika/marcel/api/db/internal/db" ) func EnsureOneUser() error { return db.Store.Bolt().Update(fun...
package controllers import ( "github.com/astaxie/beego" "github.com/morephp/blog/models" "math/rand" "time" ) type MainController struct { beego.Controller } func (this *MainController) Get() { rand.Seed(time.Now().UnixNano()) // iconS := []string{"phone","email","screen", "earth",} // this.Data["Icon"] = ic...
package handlers import ( "github.com/olivetree123/coco" "github.com/olivetree123/river/pocket" ) func PopHandler(c *coco.Coco) coco.Result { node := pocket.DataList.Pop() return coco.APIResponse(node) }
package main import "fmt" func main() { var test byte fmt.Printf("test=%c,test=%d\n", test, test) //直接输出byte值,就是输出了对应的字符的码值 var a byte = 'n' fmt.Println("a=", a) //如果我们希望输出对应的字符,需要使用格式化输出%c var b byte = '0' fmt.Printf("b=%c,b=%d\n", b, b) //当我们定义一个中文字符的时候,因为byte的长度是0-255,长度不够,我们通常用int来声明,所以字符的本质其实就是一个整数 //例...
package main func Modulo(a, b int) int { temp := a % b if temp < 0 { return (temp + b) } return temp }
package main type Job interface { Filenames() (tmplname, outname string) } type GenListJob struct { Names []string } func (job *GenListJob) Filenames() (string, string) { return "gen_list_job.tmpl", "gen_list.go" } type GenSearchJob struct { Names []string } func (job *GenSearchJob) Filenames() (string, string...
package dushengchen /** Submission: https://leetcode.com/submissions/detail/371271670/ */ func lengthOfLastWord(s string) int { // wordMap := map[string]bool{} lastWordStart, lastWordEnd := 0, 0 start := 0 r := []rune(s) for i, v := range r { if v == ' ' { if start < i { lastWordStart, lastWordEnd = ...
/* * @lc app=leetcode.cn id=13 lang=golang * * [13] 罗马数字转整数 */ package solution // @lc code=start var m13 = map[string]int{ "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, } func romanToInt(s string) (ans int) { pre := 0 for i := len(s) - 1; i >= 0; i-- { c := s[i : i+1] num := m13[...
package kinetic import ( "encoding/binary" "errors" "runtime" "syscall" "testing" "time" . "github.com/smartystreets/goconvey/convey" ) func TestProducerStop(t *testing.T) { producerInterface, _ := new(KinesisProducer).Init() producerInterface.NewEndpoint(testEndpoint, "stream-name") producer := producerIn...
/* 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 writ...
package structs type VoiceEnrollment struct { CreatedAt int `json:"createdAt"` ContentLanguage string `json:"contentLanguage"` VoiceEnrollmentId int `json:"voiceEnrollmentId"` Text string `json:"text"` APICallId string `json:"apiCallId"` } type GetAllVoiceEnrollmentsReturn st...
package requests import "time" var _ = time.Time{} type CreateEvent struct { EventCreated time.Time EventEnds *time.Time Summary string Organizer string EventUser string EventBegins time.Time EventID string Location string Source string Attendees string } type UpdateEvent ...
package main import "github.com/jinzhu/gorm" // Holding stores the number of stocks owned type Holding struct { Stock Stock Count uint } // Value of Stocks in holding func (h *Holding) Value(db *gorm.DB) float64 { return float64(h.Count) * h.Stock.Value(db) }
package database import ( "time" "errors" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "themis/utils" "themis/models" ) // IWorkItemStorage is the interface for the workitem storage. type IWorkItemStorage interface { Insert(workItem models.WorkItem) (bson.ObjectId, error) Update(workItem models.WorkIt...
// 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" "math" ) var a1, a2 int var b1, b2 = 1, 2 var ( e float32 f bool ) const ( a = iota b, c = iota, iota d = iota ) const j = iota const k, y = iota, iota func basic() { var z float64 fmt.Println(z, -z, 1/z, -1/z, z/z) // "0 -0 +Inf -Inf NaN" nan := math.NaN() fmt.Println(...
package common import ( "reflect" "strings" ) //结构体转为map func Struct2Map(obj interface{}, notcol string) map[string]interface{} { t := reflect.TypeOf(obj) v := reflect.ValueOf(obj) var data = make(map[string]interface{}) for i := 0; i < t.NumField(); i++ { if !strings.Contains(notcol, t.Field(i).Name) { ...
package memory import ( "fmt" "regexp" "sort" "strings" "sync" "time" "github.com/signaller-matrix/signaller/internal" "github.com/signaller-matrix/signaller/internal/models" "github.com/signaller-matrix/signaller/internal/models/common" "github.com/signaller-matrix/signaller/internal/models/createroom" "g...
// Copyright 2019 The Kubernetes 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 ...
package range_sum_bst // TreeNode provides interface for treeNode struct type TreeNode interface { GetValue() int GetRight() TreeNode GetLeft() TreeNode SetRight(TreeNode) SetLeft(TreeNode) } type treeNode struct { val int left TreeNode right TreeNode } func (t *treeNode) GetValue() int { return t.val } ...
/* We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API int guess(int num), which returns three possible resu...
package testing import ( "fmt" "github.com/devspace-cloud/devspace/pkg/util/survey" fakesurvey "github.com/devspace-cloud/devspace/pkg/util/survey/testing" "github.com/sirupsen/logrus" ) // FakeLogger just discards every log statement type FakeLogger struct { Survey *fakesurvey.FakeSurvey } // NewFakeLogger re...
package leetcode func InOrder(cur *TreeNode, tail **TreeNode) { if cur != nil { InOrder(cur.Left, tail) (**tail).Right = cur (**tail).Left = nil *tail = cur InOrder(cur.Right, tail) } } func increasingBST(root *TreeNode) *TreeNode { tmp := &TreeNode{} out := tmp InOrder(root, &tmp) tmp.Left = nil ret...
package storage import ( "context" "github.com/vitalyisaev2/buildgraph/common" "github.com/vitalyisaev2/buildgraph/vcs" ) // Storage is an abstraction layer above the particular SQL/NoSQL storages; // it should implement all the methods required by front and graph layer; type Storage interface { // PushEvent Sa...
package piscine func NRune(s string, n int) rune { for index, runes := range s { //the index starts from zero, hence +1 if n == index+1 { return runes } } return 0 }
package Data import ( "golang.org/x/text/encoding" "golang.org/x/text/encoding/charmap" "golang.org/x/text/encoding/unicode" ) type Encoding interface { Encode(str string) ([]byte, error) Decode([]byte) (string, error) } func encode(str string, encoder *encoding.Encoder) ([]byte, error) { return encoder.Bytes(...
package neatly import ( "github.com/stretchr/testify/assert" "github.com/viant/toolbox" "testing" ) func Test_asDataStructure(t *testing.T) { { input := `[1,2,3]` output, err := asDataStructure(input) assert.Nil(t, err) assert.EqualValues(t, []interface{}{float64(1), float64(2), float64(3)}, output) } ...
package filters import ( "strconv" "github.com/neuronlabs/neuron-core/query" "github.com/neuronlabs/neuron-postgres/internal" ) // Incrementor is the function that returns next query increment value. // Used to obtain the queries values with the incremented arguments. func Incrementor(s *query.Scope) int { retu...
package main import ( "context" "log" "os" "strings" "time" "google.golang.org/grpc" "github.com/bradenbass/echo/client/sdk" echopb "github.com/bradenbass/echo/proto" ) func main() { args := os.Args // Create a new Echoer Client echoerClient, err := echo.NewClient("127.0.0.1:9000", true) if err != nil ...
package primitives_test import ( "encoding/xml" "fmt" "github.com/plandem/xlsx/format" "github.com/plandem/xlsx/internal/ml/primitives" "github.com/stretchr/testify/require" "testing" ) func TestConditionOperator(t *testing.T) { type Entity struct { Attribute primitives.ConditionOperatorType `xml:"attribute,...
package main import ( "encoding/json" "flag" "fmt" "log" "net/http" "os" "strconv" "github.com/gorilla/handlers" "github.com/gorilla/mux" "github.com/slcjordan/reading" ) var info = log.New(os.Stdout, "", log.LstdFlags) func filename(r *http.Request) string { return map[string]string{ "book-of-mormon":...
package biliLiveHelper type CmdType string const ( CmdAll CmdType = "" CmdLive CmdType = "LIVE" CmdPreparing CmdType = "PREPARING" CmdDanmuMsg CmdType = "DANMU_MSG" CmdWelcomeGuard CmdType = "WELCOME_GUARD" CmdWelcome CmdType = "...
package problem0693 func hasAlternatingBits(n int) bool { // 如果符合条件的话,这里的结果是 11111... tmp := n ^ (n >> 1) return (tmp & (tmp + 1)) == 0 }
package jira import ( "bytes" "errors" "io/ioutil" "net/http" "testing" ) type rt struct { err error response *http.Response } func (r rt) RoundTrip(req *http.Request) (*http.Response, error) { if r.err != nil { return nil, r.err } return r.response, nil } func TestConsumeResponseWithError(t *testi...
package flag_test import ( "github.com/hoenirvili/skapt/argument" "github.com/hoenirvili/skapt/flag" gc "gopkg.in/check.v1" ) type flagsSuite struct{} var _ = gc.Suite(&flagsSuite{}) func (f flagsSuite) newFlags() flag.Flags { return flag.Flags{ {}, {Short: "u", Long: "url"}, {Short: "k", Long: "specialk"...
package cwb import ( "context" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" ) const ( libraryVersion = "0.0.1" defaultBaseURL = "https://opendata.cwb.gov.tw/" defaultUserAgent = "go-cwb/" + libraryVersion ) type service struct { client *Client } // A Client manages communication with t...
package encoding import ( "encoding/json" ) // TransformObject used to transform source object to result object based on json tag func TransformObject(source interface{}, result interface{}) error { sourceBytes, err := json.Marshal(source) if err != nil { return err } err = json.Unmarshal(sourceBytes, &result...
package msgHandler import ( "encoding/json" "fmt" "github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/reqMsg" "time" com "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/consensusManager/comm/consensusType" "github.com/HNB-ECO/HNB-Blockcha...
package main import "fmt" func main() { // convertion: []bytes to string fmt.Println(string([]byte{'h', 'e', 'l', 'l', 'o'})) // we'll learn about []bytes soon }
package appengine import ( "github.com/maykonlf/go-api-debugger/handlers" "net/http" ) func init() { http.HandleFunc("/", handlers.MainHandler) //appengine.Main() //port := os.Getenv("PORT") //if port == "" { // port = "8080" //} // //log.Printf("Listening on port %s", port) //log.Fatal(http.ListenAndServ...