text
stringlengths
11
4.05M
package main import ( "net/http" "os" ) func main() { port := os.Getenv("PORT") if port == "" { port = "9001" } http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./static")))) http.HandleFunc("/getBids", getBids) err := http.ListenAndServe(":"+port, nil) if err != nil { panic(err) } } fun...
/* Copyright © 2019 Red Hat 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 ...
package auth import ( "github.com/appleboy/gin-jwt" "github.com/gin-gonic/gin" gojwt "gopkg.in/dgrijalva/jwt-go.v3" ) type CurrentUser struct { Id int `json:"id"` Username string `json:"username"` Status int `json:"status"` Uniacid int `json:"uniacid,omitempty"` Uid int `json:"uid,om...
package producer import ( "fmt" "github.com/couchbase/plasma" ) func (p *Producer) openPlasmaStore() error { vbPlasmaDir := fmt.Sprintf("%v/%v_timer.data", p.eventingDir, p.app.AppName) cfg := plasma.DefaultConfig() cfg.File = vbPlasmaDir cfg.AutoLSSCleaning = autoLssCleaning cfg.MaxDeltaChainLen = maxDeltaC...
// Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in complian...
package models import ( "errors" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "reflect" "time" "topos-backend-assignment/db" ) type Building struct { ID bson.ObjectId `bson:"_id" json:"id"` Bin int64 `bson:"bin" json:"bin"` BoroughCode int `bson:"boroughCode" json:"boroughCo...
package main import ( "database/sql" "errors" "fmt" "strconv" "testing" "time" "github.com/jforcode/Go-Util" "github.com/magiconair/properties" ) func InitDb() *sql.DB { p := properties.MustLoadFile("test.properties", properties.UTF8) db, err := getDbFromProps(p) if err != nil { panic(err) } return d...
package types import ( "context" "github.com/rancher/wrangler-api/pkg/generated/controllers/core" "github.com/rancher/k3p/pkg/generated/controllers/helm.k3s.io" "github.com/rancher/wrangler-api/pkg/generated/controllers/batch" "github.com/rancher/wrangler-api/pkg/generated/controllers/rbac" "github.com/rancher/...
// +build !client package main import ( "./puddlestore" "flag" "fmt" ) func main() { var port int var addr string var debug bool flag.IntVar(&port, "port", 0, "The server port to bind to. Defaults to a random port.") flag.IntVar(&port, "p", 0, "The server port to bind to. Defaults to a random port. (shortha...
package jobs import ( "log" "sync" "time" "github.com/go-ignite/ignite/models" "github.com/go-ignite/ignite/ss" ) type CronJob struct { mux sync.Mutex } //dailyStats: Daily task, check & stop expired containers. func (ctx *CronJob) DailyStats() { ctx.mux.Lock() defer ctx.mux.Unlock() //1. Load all service...
package FlatFS import ( "log" "github.com/nu7hatch/gouuid" "syscall" "github.com/sarpk/go-fuse/fuse" ) type AttrMapper interface { GetAddedUUID(attributes *QueryKeyValue, queryType QueryType) (string, bool) FindAllMatchingQueries(attributes *QueryKeyValue) ([]UUIDToQuery, bool) DeleteUUIDFromQuery(attributes *...
package invoice import ( "bytes" "encoding/json" "fmt" "github.com/boltdb/bolt" "github.com/julienschmidt/httprouter" "gopkg.in/validator.v2" "log" "math/rand" "net/http" "strconv" "strings" "time" ) var db *bolt.DB const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func init() {...
package service import "context" func (svc *Service) Show(ctx context.Context) error{ return svc.ent.Show(ctx) }
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package DB /** * @author liujun * @version V1.0 * @date 2022/7/15 18:58 * @author-Email ljfirst@mail.ustc.edu.cn * @description */ type DBOperationInterface interface { ExecQuery(sqlStr string) ([]*SQLTestDataEntity, error) ExecQueryAllUTData() ([]*SQLTestDataEntity, error) ExecInsert(entity *SQLTestDataEnti...
package tgbot var EliteTimeBotToken = "-- BOT TOKEN HERE --"
package network import ( "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "sync" "time" ) type trackKeyType struct { A, B int } type report struct { delta int key string } // Graph is the entire simulated network type Graph struct { Config *graphConfig Junctions []*Junction tracks ...
package utreexo import ( "fmt" ) /* The transform operations can probably be moved into a different package even. They're some of the tricky parts of utreexo, on how to rearrange the forest nodes when deletions occur. */ // RemoveTransform takes in the positions of the leaves to be deleted, as well // as the number...
package middleware import ( "github.com/I-Reven/Hexagonal/src/application/core/service" "github.com/I-Reven/Hexagonal/src/framework/logger" "github.com/gin-gonic/gin" "os" ) type Tracker struct { log logger.Log track logger.Tracker service service.TrackService } func (m Tracker) Handler() gin.HandlerFun...
package main import ( "encoding/json" "math" "strconv" "time" monitoring "github.com/agareev/MoexLib/monitoring" config "github.com/agareev/MoexLib/other" ) // ResponseEngines json ResponseEngines from infcx type ResponseEngines struct { Marketdata struct { Columns []string `json:"columns"` Data [][]...
package main import ( "fmt" "github.com/ltinyho/ltcache/ltcache" "log" "net/http" "time" ) var db = map[string]string{ "Lt": "630", "Sql": "589", "Zzl": "567", } func main() { ltcache.NewGroup("scores", 2<<10, ltcache.GetterFunc(func(key string) ([]byte, error) { log.Println("[SlowDB] search key", key) ...
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import "fmt" func main() { // i, j, k, l, m, n := "hello", 32, 10.12, 42.0, true, 10i var ( i string j int k float64 l float64 m bool n complex128 ) fmt.Printf("%T %#v\n", i, i) // string, "" fmt.Printf("%T %#v\n", j, j) // int, 0 fmt.Printf("%T %#v\n", k, k) // float64, 0.0 fmt.Prin...
package sLSM // 开放地址 一次探测法 type HashTable struct { cmp Comparer size uint64 curSize uint64 table []*KVPair } func NewHashTable(size uint64, cmp Comparer) *HashTable { table := make([]*KVPair, size*2) var i uint64 for i = 0; i < size*2; i++ { table[i] = EMPTY } return &HashTable{ cmp: cmp, ...
package main import ( "strconv" "strings" ) //297. 二叉树的序列化与反序列化 //序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。 // //请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。 // //示例: // //你可以将以下二叉树: // //1 /// \ //2 3 /// \ //4 5 // //序列...
package main import ( "container/heap" "fmt" "strconv" ) // Leetcode 5703. (medium) func maxAverageRatio(classes [][]int, extraStudents int) float64 { h := PassCntHeap{} for _, c := range classes { heap.Push(&h, [2]int{c[0], c[1]}) } for i := 0; i < extraStudents; i++ { c := heap.Pop(&h).([2]int) c[0]++ ...
package Reorder_List import ( "testing" "github.com/stretchr/testify/assert" ) func Test_reorderList(t *testing.T) { ast := assert.New(t) h1 := combineListFromArray([]int{1, 2, 3, 4, 5, 6}) reorderList(h1) ast.Equal([]int{1, 6, 2, 5, 3, 4}, getArrayFromList(h1)) h2 := combineListFromArray([]int{1, 2, 3, 4, 5...
package support // pagination struct type Pagination struct { Start int `json:"start" validate:"min=0"` Size int `json:"size" validate:"min=0"` } // 初始化分页参数 func (page *Pagination) Init() { if page.Start - 1 < 0 { page.Start = 1 } page.Start = (page.Start - 1) * page.Size }
package controllers import ( "fmt" "github.com/astaxie/beego" ) //MainController è il maincontroller del portale type MainController struct { beego.Controller } //ErrorController manage error page type ErrorController struct { MainController } //Error404 func for 404 error func (c *ErrorController) Error404() ...
package tailer import ( "testing" "time" ) func Test_buildLogFileName(t *testing.T) { aTime := time.Date(2017, 6, 12, 11, 0, 0, 0, time.Local) result := buildLogFileName(aTime) expect := "error/postgresql.log.2017-06-12-11" if result != expect { t.Fatalf("result %s != expect %s", result, expect) } }
package main import ( "os" "log" "github.com/kniren/gota/dataframe" "fmt" ) func main() { advertFile , err := os.Open("linearregression/data/Advertising.csv") //advertFile , err := os.Open("../Advertising.csv") if err!=nil{ log.Fatalf("Error open file %v",err) } defer advertFile.Close() advertFrame:=...
package cmd import ( e "github.com/cloudposse/atmos/internal/exec" u "github.com/cloudposse/atmos/pkg/utils" "github.com/spf13/cobra" ) // describeComponentCmd describes configuration for components var describeComponentCmd = &cobra.Command{ Use: "component", Short: "Execute 'describe...
package models import ( "fmt" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" // import your required driver "time" ) // Create OnBoardingImage models type OnBoardingImage struct { Id int `orm:"pk;auto"` ImageUrl string CreatedBy int UpdatedBy int CreatedAt time.Time `orm:"auto_now_add;...
// Copyright (C) 2020 Storj Labs, Inc. // See LICENSE for copying information. package strictcsv import "github.com/zeebo/errs" var ( // Error is an error class for the package. Error = errs.Class("strictcsv") )
package usecase import ( "github.com/16francs/examin_go/domain/model" "github.com/16francs/examin_go/domain/service" "github.com/16francs/examin_go/interface/request" ) type UserUsecase interface { Create(request request.CreateUser) error } type userUsecase struct { service service.UserService } func NewUserUs...
package licensing import ( "path" "strings" ) const ( // GroupName is the group name for this API GroupName = "licensing" // Version is the version for this API Version = "v2" // LicenseResource is the name of the license resource LicenseResource = "license" keySeparator = "/" ) var ( apiKeyPrefix = pat...
package main import "fmt" func main() { var z myType = 123 z.println() } type myType int func (value myType) println() { fmt.Println(value) }
package app import ( "fmt" "log" "net/http" "os" "github.com/dgrijalva/jwt-go" app "github.com/ebcp-dev/gorest-api/app/utils" "github.com/ebcp-dev/gorest-api/db" "github.com/gorilla/mux" _ "github.com/lib/pq" "github.com/spf13/viper" ) // References DB struct in db.go. var d db.DB type App struct { Route...
package smartling import ( "fmt" "net/url" ) // LimitOffsetRequest is a base request for all other requests to set // pagination options, e.g. limit and offset. type LimitOffsetRequest struct { Offset int Limit int } // GetQuery returns URL-encoded representation of current request. func (request LimitOffsetRe...
package iban import ( "fmt" "regexp" "strconv" "strings" "github.com/anecsoiu/banking/country" "bgithub.com/anecsoiu/anking/bban" ) const ( // minIbanSize represents minimal length of iban. minIbanSize = 15 // modCheck represents value used in mod check. modCheck = 98 // modValue represents value used i...
// Copyright © SAS Institute Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
package statestore import "github.com/zhaohaijun/matrixchain/core/store/common" type MemoryStore struct { memory map[string]*common.StateItem } func NewMemDatabase()*MemoryStore{ return &MemoryStore{ memory:make(map[string]*common.StateItem) } } func (db *MemoryStore) Put(prefix byte,key[]byte,value states.State...
package main import "fmt" func sup(name string) string { return "Sup, " + name } func main() { fmt.Println(sup("Ewan")) }
package main import ( "encoding/csv" "flag" "log" "os" "github.com/kchristidis/overlap" ) func main() { // Define flag headers := flag.Bool("headers", false, "Does the input file have headers?") // Parse the flag flag.Parse() // Parse the command-line arguments trailing the flag. args := flag.Args() inFi...
package cpu import "testing" func tax(value byte) (*CPU) { var p *CPU = NewCPU() p.A = value p.Tax() return p } func tay(value byte) (*CPU) { var p *CPU = NewCPU() p.A = value p.Tay() return p } func tsx(value byte) (*CPU) { var p *CPU = NewCPU() p.SP = value p.Tsx()...
package data import ( "strings" ) type Alg struct { Moves []string } func NewAlg(moves string) *Alg { alg := Alg{} alg.AddMoves(moves) return &alg } func (a Alg) Copy() *Alg { return NewAlg(a.String()) } func (a *Alg) AddMove(m string) *Alg { switch m { // Simply ignoring not recognized move case "R",...
package osd import ( "context" "github.com/onsi/ginkgo" . "github.com/onsi/gomega" machineV1beta1 "github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1" "github.com/openshift/osde2e/pkg/common/alert" "github.com/openshift/osde2e/pkg/common/helper" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apim...
package app import ( "context" "encoding/json" "log" "net/http" matrix_db "shpong/db/matrix/gen" "strconv" "strings" "time" "github.com/Jeffail/gabs/v2" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5/pgtype" ) type IndexEventsParams struct { Last string `json:"last"` Filter string `json:"filter"`...
package trace import ( "errors" v1 "k8s.io/api/core/v1" ) var ( ErrParentEntityNotFound = errors.New("the parent entity could not be found") ) type Entity struct { Type EntityType Name string } func ObjectReferenceToEntity(objectRef v1.ObjectReference) *Entity { var entityType EntityType switch objectRef.Ki...
package mvt import ( //vt "github.com/buckhx/diglet/mbt/mvt/vector_tile" //"reflect" "testing" ) // These tests all come from the vector-tile-spec 2.0 // https://github.com/mapbox/vector-tile-spec/tree/master/2.0#435-example-geometry-encodings func TestReadPoints(t *testing.T) { tests := []geomTest{ {[]uint32{9...
package articles import ( "sort" "strings" "unicode" ) type Tags []string type TagMap map[string]Articles type TagCloud []tagCloud type tagCloud struct { Tag string Wight int } func (t TagCloud) Len() int { return len(t) } func (t TagCloud) Swap(i, j int) { t[i], t[j] = t[j], t[i] } type byWight struct...
package interaction import ( "errors" "github.com/joshprzybyszewski/cribbage/model" ) type Player interface { ID() model.PlayerID NotifyBlocking(model.Blocker, model.Game, string) error NotifyMessage(model.Game, string) error NotifyScoreUpdate(g model.Game, msgs ...string) error } func New(pID model.PlayerID...
// Defining the `list` command. package cmd import ( "errors" "fmt" "strings" "github.com/JosephLai241/shift/database" "github.com/JosephLai241/shift/timesheet" "github.com/JosephLai241/shift/utils" "github.com/spf13/cobra" ) // listCmd represents the list command. var listCmd = &cobra.Command{ Use: "list...
package main import "fmt" func main() { var pointer *int // nil pointer if pointer != nil { fmt.Println("Value of pointer: ", *pointer) } else { fmt.Println("The value of pointer is 'nil'") } var someNumber = 60 pointer = &someNumber // Address of 'someNumber' fmt.Println("The value of pointer: ", *point...
package internal import ( G "github.com/ionous/sashimi/game" "github.com/ionous/sashimi/util/ident" ) type nullValue PropertyPath func (_ nullValue) Set(value G.IValue) {} func (_ nullValue) Num() (ret float64) { return } func (_ nullValue) SetNum(float64) {} func (n nullValue) Object() G.IObject ...
package mailmanv2 import ( "testing" "math/rand" "strconv" "fmt" "time" "bytes" "regexp" ) var ( TestResults chan string ) // // Endpoint functions // func TimePayload(wr *WorkRequest, w *Worker) { var buffer bytes.Buffer // Write testing message diff, err := strconv.ParseInt(wr.Payload, 10, 64) if err...
package main import ( "strings" "testing" ) var testCases = []struct { name string input string expected int }{ { name: "simple overlap", input: `#1 @ 1,3: 4x4 #2 @ 3,1: 4x4 #3 @ 5,5: 2x2`, expected: 4, }, { name: "double overlap", input: `#1 @ 1,3: 4x4 #2 @ 3,1: 4x4 #3 @ 4,4: 2x2`, expecte...
// Copyright 2018 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package arc import ( gotesting "testing" "time" "chromiumos/tast/local/arc" "chromiumos/tast/local/chrome" "chromiumos/tast/testing" "chromiumos/tast/testing/testchec...
package model /* SELECT index 切换到指定的数据库,数据库索引号 index 用数字值指定,以 0 作为起始索引值。 默认使用 0 号数据库。 返回 error==nil 就是成功的 */ func (rd *RedisHandleModel) Select(index int) error { _, err := rd.Do("SELECT", index) return err } /* AUTH password 通过设置配置文件中 requirepass 项的值(使用命令 CONFIG SET requirepass password ),可以使用密码来保护 Redis 服务器。 返回 e...
package cmd import ( "strings" "testing" "github.com/stretchr/testify/assert" ) func TestParseSource(t *testing.T) { testCases := []struct{argument string; expected []*Source}{ { argument: "app:yes", expected: []*Source{ { Name: "app", Command: "yes", }, }, }, { argument: "app...
package backup type MockBackupService struct { } func (b *MockBackupService) Upload(file string) error { return nil } func (b *MockBackupService) Authenticate() error { return nil }
package lloyd import ( "net/http" "sync" ) var ( respWriterPool sync.Pool zeroRespWriter = &responseWriter{} ) type responseWriter struct { hdr http.Header ctx *Ctx } func acqRespWriter() *responseWriter { v := respWriterPool.Get() if v == nil { return new(responseWriter) } return v.(*responseWriter) }...
package builder import ( "github.com/zlsgo/zdb/driver/sqlite3" ) var ( // DefaultDriver is the default flavor for all builders DefaultDriver = &sqlite3.Config{} )
package pools import ( "fmt" "unsafe" ) func ExampleAddrTCPConnPool() { addr := "www.baidu.com:80" var v1, v2 uint64 p := NewAddrTCPConnPool(1) c1, err := p.Get(addr) if err != nil { fmt.Println(err) return } v1 = *(*uint64)(unsafe.Pointer(c1)) p.Put(addr, c1) c2, err := p.Get(addr) if err != nil { ...
package main import ( containit "containit/types" "fmt" "io/ioutil" ) type dependencyDag struct { vertices map[string]*containit.Service } func LoadDirectory(baseDirectory string) (map[int64][]*containit.Service, map[string]*containit.Service, error) { dag := &dependencyDag{ vertices: make(map[string]*contain...
package jsonvalidate import ( e "errors" "net/url" "strconv" "testing" "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) func TestNewRegistryRef(t *testing.T) { // Test the happy case for creating a new registry. This involves creating // cyclical data structures, so it's difficult to express th...
package participant import ( "t32/game" "testing" ) func TestPushPlayerOnWaitingForPlayers(t *testing.T) { c := new(spyClient) r := new(spyReferee) r.RespStatus = game.StatusWaitingForPlayers _ = New('A', c, r) if r.Players[0] != 'A' { t.Fatal("participant wasn not added to players") } if !c.ReqWaiting...
// Copyright 2014 Aller Media AS. All rights reserved. // License: GPL3 // Package job provides local job information and access. package job import ( log "github.com/Sirupsen/logrus" "net/http" "path/filepath" ) type HTTPFetcher struct { proto string } func (ff *HTTPFetcher) String() string { return "HTTP" }...
package logmein func boolToInt(b bool) int { v := 0 if b { v = 1 } return v }
package db import ( "testing" ) func TestFindUsernameExists(t *testing.T) { testUsername := "test-user-1" if result := FindUsername(testUsername); result == "" { t.Fatalf("Expected temp database to have username %s\n", testUsername) } } func TestGetUsers(t *testing.T){ expectedLen := len(TempUserMap) ...
package main import ( //"fmt" ) func _FerrExit(___VerrMsg string, ___Verr error) { if ___Verr != nil { _FpfNex("Error: <%s>[%v]", ___VerrMsg, ___Verr) } } // _FerrExit func _FnullExit(___VerrMsg string, ___Vck interface{}) { if ___Vck == nil { _Fex("Error: " + ___VerrMsg) } } // _FnullExit func _FnotNullExi...
package filter import ( "github.com/naili-xing/singa_auto_scheduler/pkg/sascheduler/collection" v1 "k8s.io/api/core/v1" "k8s.io/klog" framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1" "strings" ) func MatchGpu2Pod( pod *v1.Pod, nodes []*v1.Node, filteredNodesStatuses framework.NodeToStatusMap) { ...
package hasher import ( "crypto/sha256" "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tilt-dev/tilt/internal/tiltfile/starkit" "github.com/tilt-dev/tilt/internal/tiltfile/starlarkstruct" ) const assertTilt = ` def equals(expected, observed): if expect...
package main import "fmt" /* Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You a...
package handlers import ( "encoding/json" "net/http" "net/http/httptest" "net/url" "os" "path" "strings" "testing" "github.com/husobee/vestigo" "github.com/libgit2/git2go" "github.com/tmaesaka/cellar/config" ) var ( testCfg = config.NewApiConfig() testRepoName = "project_x" testDir = "/tmp/_c...
// Copyright 2020 Paul Greenberg greenpau@outlook.com // // 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 applic...
// Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
package strategies import ( "github.com/matang28/reshape/reshape" "sync" "time" ) type bufferedStrategy struct { batchSize int flushTimeout time.Duration queue chan []interface{} mutex sync.Mutex } func NewBufferedStrategy(batchSize int, flushTimeout time.Duration) *bufferedStrategy { return...
package util import ( "reflect" "strings" ) func Contains(list interface{}, target interface{}) bool { if reflect.TypeOf(list).Kind() == reflect.Slice || reflect.TypeOf(list).Kind() == reflect.Array { listvalue := reflect.ValueOf(list) for i := 0; i < listvalue.Len(); i++ { if target == listvalue.Index(i).I...
package test import ( "testing" ) func TestVendor(t *testing.T) { if !deriveEqual(&UseVendor{}, &UseVendor{}) { t.Fatal("not equal") } }
package translator import ( "fmt" "github.com/leonhfr/nand2tetris/src/vm/bytecode" ) type Translator struct { filename string entry bool in <-chan *bytecode.Command out chan string errors chan error labels int } func New(filename string, entry bool, in <-chan *bytecode.Command, out chan st...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package sharedfolders provides support for sharing folders with Crostini. package sharedfolders import ( "context" "time" "chromiumos/tast/errors" "chromiumos/tast/l...
package main import ( "errors" "fmt" ) func greeting(name string) (string, error) { if len(name) == 0 { return "", errors.New("Name cannot be empty") } return "hello " + name, nil } // custom type as error type myError struct { arg int prob string } // implement Error() on type myError // to make custom e...
package user import ( "context" "time" "github.com/anrid/codecoach/internal/config" "github.com/anrid/codecoach/internal/domain" token_gen "github.com/anrid/codecoach/internal/pkg/token" "github.com/pkg/errors" "go.uber.org/zap" ) // UseCase ... type UseCase struct { c *config.Config a domain.AccountDAO u ...
package main import ( "bytes" "fmt" "ftploader/app" "github.com/gorilla/mux" "github.com/secsy/goftp" "gopkg.in/yaml.v2" "io/ioutil" "log" "net/http" "os" "sync" "time" ) var logpath string = "" func main() { port := "3000" if len(os.Args) == 2 { port = os.Args[1] } r := mux.NewRouter() r.HandleFu...
package main import "strconv" // Leetcode 738. (medium) func monotoneIncreasingDigits(N int) int { s := []byte(strconv.Itoa(N)) i := 1 for i < len(s) && s[i-1] <= s[i] { i++ } if i < len(s) { for i > 0 && s[i-1] > s[i] { s[i-1]-- i-- } i++ for i < len(s) { s[i] = '9' i++ } } res, _ := s...
package gotty import ( "fmt" "io" "os" ) type TermInfo interface { Parse(attr string, params ...interface{}) (string, error) } func NewTerm() (TermInfo, error) { term := os.Getenv("TERM") if term == "" { term = "vt102" } return OpenTermInfo(term) } func ClearLine(out io.Writer, ti TermInfo) { // el2 (cle...
// Copyright (c) IBM Corporation 2019. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0, which is available at // http://www.eclipse.org/legal/epl-2.0. // // SPDX-License-Identifier: EPL-2.0 // //nolint package mqjms import ( "errors" "githu...
package parser import ( "os" "path" "strings" "github.com/tinyzimmer/k3p/pkg/types" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer" corescheme "k8s.io/client-go/kubernetes/scheme" ) // BaseManifestParser represents the base elements for a parser interface. It contains // conveni...
package leetcode // 每天都存在交易.只要保证后一天比前一天价格高就交易 func maxProfit(prices []int) int { l := len(prices) profit := 0 for i := 1; i < l; i++ { if d := prices[i] - prices[i-1]; d > 0 { profit += d } } return profit }
package datastructandalgorithm import "testing" func TestMove(t *testing.T) { Move(5, 'a', 'b', 'c') }
package main //467. 环绕字符串中唯一的子字符串 //把字符串 s 看作是“abcdefghijklmnopqrstuvwxyz”的无限环绕字符串,所以s 看起来是这样的: // //"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". //现在给定另一个字符串 p 。返回s 中唯一 的 p 的 非空子串的数量。 // // // //示例1: // //输入: p = "a" //输出: 1 //解释: 字符串 s 中只有一个"a"子字符。 //示例 2: // //输入: p = "cac" //输出: 2 //解释: 字符串 ...
package pipeline import "time" func JobIDPtr(i uint64) *JobID { jid := JobID(i) return &jid } func RunIDPtr(r uint64) *RunID { rid := RunID(r) return &rid } func TimePtr(t time.Time) *time.Time { return &t } func StringPtr(s string) *string { return &s } func BoolPtr(b bool) *bool { return &b } func IntPt...
package itree import ( "math/rand" "testing" "github.com/stretchr/testify/assert" ) func TestNewTree(t *testing.T) { tree, err := NewTree([]Interval{ Interval{Start: 1, End: 3}, Interval{Start: 5, End: 8}, Interval{Start: 10, End: 12}, Interval{Start: 13, End: 16}, }) assert.NoError(t, err) assert.Eq...
// SPDX-License-Identifier: MIT package ast import ( "net/http" "strconv" "strings" "time" "github.com/issue9/version" "github.com/caixw/apidoc/v7/internal/locale" "github.com/caixw/apidoc/v7/internal/xmlenc" ) const dateFormat = time.RFC3339 type ( // Attribute 表示 XML 属性 Attribute struct { xmlenc.Base...
package tree func flatten(root *TreeNode) { if root == nil { return } flatten(root.Left) flatten(root.Right) left := root.Left right := root.Right root.Left = nil root.Right = left for root.Right != nil { root = root.Right } root.Right = right }
package main import ( "encoding/json" "math" ) // A Rad is an angular measurement of radians. type Rad float64 // UnmarshalJSON unmarshals from JSON text specifying a quantity in degrees. func (r *Rad) UnmarshalJSON(b []byte) error { var f float64 if err := json.Unmarshal(b, &f); err != nil { return err } *r...
package main import "fmt" var y = 43 func main() { // Short declaration x := 42 fmt.Printf("%T", x) y = 44 fmt.Printf("%T", y) }
package civ import ( "fmt" "sort" "github.com/schollz/closestmatch" "github.com/ecshreve/civ-bot-go/internal/constants" ) // Civ represents an individual civilization. type Civ struct { // Key is the CivKey enum entry for this Civ. Key constants.CivKey // CivBase is the string representation of the Civ's na...
package lib import ( "net/http" "net/http/httputil" "net/url" "os" "path/filepath" ) type limitedReq struct { w http.ResponseWriter req *http.Request done chan struct{} } func limitHandler(num int, h http.Handler) http.Handler { if num <= 0 { return h } ch := make(chan *limitedReq, num) go func(c...