text
stringlengths
11
4.05M
package ravendb import "time" // DatabaseStatistics describes a result of GetStatisticsCommand type DatabaseStatistics struct { LastDocEtag int64 `json:"LastDocEtag"` CountOfIndexes int `json:"CountOfIndexes"` CountOfDocuments int64 `json:"CountOfDocuments"` CountOfRevisionDocu...
package data import ( "math/rand" "testing" ) func BenchmarkStorage_Get(b *testing.B) { s := New() for i := 0; i < 10000000; i++ { str := randomString(6) s.Add(str, str) } input := "abcd" b.ResetTimer() for i := 0; i < b.N; i++ { _, _ = s.Get(input) } } var chars = "abcdefghijklmnop" func randomStr...
package generator import ( "bytes" "fmt" "html/template" "sort" "strings" "github.com/RomanosTrechlis/blog-generator/config" ) // Category holds the data for a category type Category struct { Name string Link string Count int } // categoriesGenerator struct type categoriesGenerator struct { catPostsMap ...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package policy import ( "context" "sync" "time" "chromiumos/tast/common/fixture" "chromiumos/tast/common/pci" "chromiumos/tast/common/policy" "chromiumos/tast/common...
package repository import ( "context" "github.com/caos/zitadel/internal/project/model" ) type ProjectRepository interface { ProjectByID(ctx context.Context, id string) (*model.ProjectView, error) CreateProject(ctx context.Context, name string) (*model.Project, error) UpdateProject(ctx context.Context, project *...
package krc import ( "encoding/json" "fmt" "sync" "time" "github.com/Shopify/sarama" "github.com/jbvmio/kafkactl" "github.com/jbvmio/krc/config" "github.com/jbvmio/krc/kafka" "github.com/spf13/cast" ) func ValidateConfig(config *config.Config) { if config.LocalBoot == "" { config.LocalBoot = kafka.Select...
//package with commands package commands import ( "database/sql" "fmt" "log" "strings" _ "github.com/mattn/go-sqlite3" ) // LastBook выводит последние 20 добавленных книг. func LastBook(database string) string { type Book struct { id int title string } var id int var title string db, err := sql.O...
package users import ( "bytes" "encoding/json" "io/ioutil" "net/http" "net/http/httptest" ) func (u *UsersTest) TestUsers_V1CreateUserHandler() { name := "test from test case" address := "test from test case" newUserTest := User{ Name: name, Address: address, } jsonStr, _ := json.Marshal(newUserTes...
package keeper import ( "context" "encoding/json" "errors" "fmt" "math/big" "time" "github.com/ethereum/go-ethereum/eth/tracers" "github.com/palantir/stacktrace" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/comm...
package thermal import ( "context" "sync" "github.com/spf13/viper" "github.com/superchalupa/sailfish/src/log" "github.com/superchalupa/sailfish/src/ocp/testaggregate" "github.com/superchalupa/sailfish/src/ocp/view" domain "github.com/superchalupa/sailfish/src/redfishresource" eh "github.com/looplab/eventhori...
// 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 api import ( "encoding/json" "net/http" "github.com/ankur-anand/gostudygroup-bot/config" "github.com/ankur-anand/gostudygroup-bot/helper" ) var ( cfg = config.Cfg logger = helper.Logger ) // resWithError JSON func resWithError(w http.ResponseWriter, code int, message string) { resWithJSON(w, code,...
package service // Service Define a service interface type Service interface { // Add calculate a+b Add(a, b int) int // Subtract calculate a-b Subtract(a, b int) int // Multiply calculate a*b Multiply(a, b int) int // Divide calculate a/b Divide(a, b int) (int, error) }
/* * Copyright IBM Corporation 2021 * * 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 o...
package systemdeps import ( "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" ) // List of system processes. type Processes struct { Processes []Process `json:"processes"` } // Representation of a process and it's dependencies. type Process struct { Name string `json:"name"` Dependencies []str...
// 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 cache import "sync" /* Дано: InMemoryCache - потоко-безопасная реализация Key-Value кэша, хранящая данные в оперативной памяти Задача: 1. Реализовать метод GetOrSet, предоставив следующие гарантии: - Значение каждого ключа будет вычислено ровно 1 раз - Конкурентные обращения к существующим ключам не блокируют...
package e7 import ( "errors" "testing" "github.com/google/go-cmp/cmp" ) func TestTopic_String(t *testing.T) { tests := []struct { in Topic want string }{ {in: Criticism, want: "Criticism"}, {in: RealityCheck, want: "Reality Check"}, {in: HeroicTale, want: "Heroic Tale"}, {in: ComfortingCheer, want...
/* * Copyright 2022 Kube Admission Webhook 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 applicabl...
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gcbench import ( "flag" "fmt" ) type Bytes int64 var si = []string{"", "k", "M", "G", "T", "P", "E", "Z", "Y"} const ( B Bytes = 1 KB Bytes = 1...
package market import cosmostypes "github.com/cosmos/cosmos-sdk/types" // ================= Query ================= // type GetConfigResponse struct { OwnerAddr cosmostypes.AccAddress `json:"owner_addr"` ATerraContract cosmostypes.AccAddress `json:"aterra_contract"` InterestModel cosmostypes.AccAdd...
package main func main(a int) { var a int }
package main import ( "bufio" "fmt" "io/ioutil" "os" ) func main() { /* if _, err := os.Stat("log.txt"); os.IsNotExist(err) { fmt.Println("Log file does not exist") } else { fmt.Println("Log file exists") } contentBytes, err := ioutil.ReadFile("names.txt") if err == ...
package auth import ( "fmt" "net/http" "strings" "time" "github.com/gempir/gempbot/internal/api" "github.com/gempir/gempbot/internal/config" "github.com/gempir/gempbot/internal/helixclient" "github.com/gempir/gempbot/internal/log" "github.com/gempir/gempbot/internal/store" "github.com/golang-jwt/jwt" "gith...
//go:generate mockgen -destination ../../internal/test/mock/pkg/runtime/mock_runtime.go github.com/wetware/ww/pkg/runtime ServiceFactory,EventProducer,EventConsumer,Service package runtime import ( "context" "fmt" "reflect" ww "github.com/wetware/ww/pkg" "go.uber.org/fx" ) // DependencyError is returned if an ...
package storage import ( "errors" ) // ErrStorageAccessConflict is an error for accessing key conflict var ErrStorageAccessConflict = errors.New("specified key is under accessing") // Store is an interface for caching data into backend storage type Store interface { Create(key string, contents []byte) error Delet...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package ui import ( "context" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/local/audio" "chromiumos/tast/local/audio/crastestclient" "chromiumos/tast/local/chrom...
package chat import ( "encoding/json" socketio "github.com/googollee/go-socket.io" "github.com/streadway/amqp" "log" ) type AMQPMessage struct { Message Message Emails []string } type Message struct { User User Content string Type string Game Game } type Game struct { Id int } type User struct { Id int...
package sql import ( "fmt" "reflect" "strings" ) func SelectAll(structVal interface{}) string { valType := reflect.TypeOf(structVal) numFields := valType.NumField() fields := make([]string, numFields) for i := 0; i < numFields; i++ { fields[i] = valType.Field(i).Name } fmt.Println("HERE", strings.Join(fiel...
package command type CreateTacoBoxCommand struct { CreatorId string Name string `json:"name" validate:"required"` } type UpdateTacoCommand struct { Name string `json:"name"` OperationUserID string TacoBoxID string `validate:"required"` }
package physics import ( "github.com/20zinnm/spac/common/constants" "github.com/jakecoffman/cp" ) type TranslationalState struct { Position cp.Vector Velocity cp.Vector } func (t TranslationalState) Step(dt float64) TranslationalState { return TranslationalState{ Position: t.Position.Add(t.Velocity.Mult(dt)),...
package main import ( "bufio" "flag" "fmt" "os" "path/filepath" "regexp" "sync" "sync/atomic" "time" ) var countOnly bool var scan bool var pattern *regexp.Regexp var sum int32 var openFilesCount int32 var group sync.WaitGroup var numFiles int32 var numLines int32 func scanFile(path string) { for atomic.L...
/* * Copyright 2018, Oath Inc. * Licensed under the terms of the MIT license. See LICENSE file in the project root for terms. */ package state import ( "log" "sync" "time" ) type Lock struct { maxCount int mutex sync.Mutex locks []time.Time } func NewLock(maxLockCount int) Lock { return Lock{maxCoun...
package stconfig import ( "fmt" "github.com/tealeg/xlsx" ) type Sheet struct { Row uint16 Col uint16 Data [][]string } func ReadXlsx(file string, sheet string) (*Sheet, error) { wk, err := xlsx.OpenFile(file) if err != nil { return nil, err } if len(wk.Sheets) > 0 { var st *xlsx.Sheet if sheet == "...
package hud import ( "bytes" "testing" "time" "github.com/stretchr/testify/assert" "github.com/tilt-dev/tilt/pkg/model/logstore" ) func TestPrinterProgressBackoff(t *testing.T) { out := &bytes.Buffer{} now := time.Now() printer := NewIncrementalPrinter(Stdout(out)) printer.Print([]logstore.LogLine{ logs...
package gorm_test import ( "testing" "github.com/go-test/deep" "github.com/porter-dev/porter/internal/models" "gorm.io/gorm" ) func TestCreateInfra(t *testing.T) { tester := &tester{ dbFileName: "./porter_create_aws_infra.db", } setupTestEnv(tester, t) initProject(tester, t) defer cleanup(tester, t) in...
package main import ( "log" "net/http" "os" "time" "github.com/go-openapi/runtime/middleware" "github.com/gorilla/mux" "github.com/mactsouk/handlers" ) var SQLFILE string = "/tmp/users.db" var PORT string = ":1234" var IMAGESPATH = "/tmp/files" type notAllowedHandler struct{} func (h notAllowedHandler) Serv...
/* * @lc app=leetcode.cn id=881 lang=golang * * [881] 救生艇 */ package leetcode import "sort" // @lc code=start func numRescueBoats(people []int, limit int) int { sort.Ints(people) res := 0 i, j := 0, len(people) - 1 for i < j { if people[i] + people[j] <= limit { i++ j-- res++ }...
package main import ( "fmt" "time" ) /** 8.3 包结构 - 源文件头部以"package<name>"声明包名称。 - 包由同一目录下的多个源码文件组成。 - 包名类似namespace,与包所在目录名,编译文件名无关。 - 可执行文件必须包含 package studyNote,入口函数 studyNote。 */ /** 8.3.2 初始化 - 每个源文件都可以定义一个或多个初始化函数。 - 编译器不保证多个初始化函数执行次序。 - 初始化函数在单一线程被调用,仅执行一次。 - 初始化函数在包所有全局变量初始化后执行。 - 在所有初始化函数结束后才执行main...
package main import "fmt" func main(){ sum := 0 for i:=1;i<1000;i++{ if ((i%3==0) || (i%5==0)){ sum+=i } } fmt.Println(sum) }
package app import ( "testing" "github.com/go-redis/redis" "time" ) var ( client *redis.Client ) func TestAppSetup(t *testing.T) { //Use test redis client = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, }) } func TestApp_StartApp(t *testing.T) { apps := [4]*Ap...
/******************************************************************************* * Copyright 2017 Samsung Electronics 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...
package models import ( "time" "github.com/jinzhu/gorm" ) // Code ... type Code struct { gorm.Model SendID uint Code string `gorm:"type:varchar(50);not null"` IsUse int32 `gorm:"type:tinyint(1);default:0;not null"` ExpiresAt time.Time `gorm:"type:datetime;not null"` Send Send }
/* Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. */ package main func swa...
// 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...
// Copyright 2021 The Perses 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 ...
// Copyright 2018 The gVisor 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 agree...
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-present Datadog, Inc. package datadogagent import ( "context" "fmt" "strconv" "strings" "...
// mksyscall.pl syscall_linux.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package syscall import "unsafe" import "syscall" // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fcntl(fd uintptr, cmd int, arg int) (val int, err error) { r0, _, e1 := syscall.Syscall(syscall.SYS_FCNTL, u...
package recursion var Position [9]int var SubNum = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} var ZhiNum = []int{1, 2, 3, 5, 7, 11, 13, 17, 19} func IsZhi(n int) bool { for i := 0; i < 9; i++ { if n == ZhiNum[i] { return true } } return false } func CheckB(i, n int) bool { //纵 if i-3 >= 0 { // 跳过0,1,2 if Is...
//go:build integration // +build integration package integration import ( "bytes" "context" "testing" "time" "github.com/stretchr/testify/assert" ) func TestOneUp(t *testing.T) { f := newK8sFixture(t, "oneup") f.SetRestrictedCredentials() f.TiltUp("oneup") // ForwardPort will fail if all the pods are not...
package p_00001_00100 // 17. Letter Combinations of a Phone Number, https://leetcode.com/problems/letter-combinations-of-a-phone-number/ func letterCombinations(digits string) []string { var result []string if len(digits) == 0 { return result } lettersByDigit := map[byte]string{ '2': "abc", '3': "def", '4...
package testutil // GifType is a gif's mime type const GifType = "image/gif" // GifBin is the binary of a tiny gif var GifBin = []byte{ 0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02,...
// 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 gpucuj tests GPU CUJ tests on lacros Chrome and ChromeOS Chrome. package gpucuj import ( "context" "fmt" "math" "os" "path/filepath" "sort" "android.googl...
package api import ( "BiliBili.com/pkg/utils" "BiliBili.com/service" "github.com/gin-gonic/gin" ) func UserRegister(c *gin.Context) { var userRegisterService service.UserRegister _ = c.ShouldBind(&userRegisterService) res := userRegisterService.Register() c.JSON(200,res) } func UserLogin(c *gin.Context) { va...
package v1alpha2 import ( "encoding/json" "errors" ) // DefaultPlatformArchitecture defines the default // architecture used by mirroring platform // release payloads. const DefaultPlatformArchitecture = "amd64" // PlatformType defines the content type for platforms type PlatformType int // TypeOCP is default con...
package main import ( "fmt" "github.com/kormat/adventofcode/util" "log" "os" "sort" "strconv" "strings" ) func main() { lines, ok := util.ReadFileArg(os.Args[1:]) if !ok { os.Exit(1) } paper := 0 ribbon := 0 for _, line := range lines { dims, err := parseDims(line) if err { os.Exit(1) } pap...
package oonimkall_test import ( "testing" "github.com/ooni/probe-cli/v3/pkg/oonimkall" ) func TestSessionWebConnectivity(t *testing.T) { if testing.Short() { t.Skip("skip test in short mode") } sess, err := NewSessionForTesting() if err != nil { t.Fatal(err) } ctx := sess.NewContext() config := &oonimka...
package unimatrix type Response struct { parser *Parser } func NewResponse(body []byte) (*Response, error) { parser, error := NewParser(body) if error != nil { return nil, error } return &Response{parser: parser}, nil } func (response *Response) Name() (string, error) { return response.parser.Name, nil } ...
package main import ( "context" "flag" "github.com/real-nil/grpc-pubsub/proto/pubsub" "google.golang.org/grpc" "io" "log" "sync/atomic" "time" ) var ( pubsubAddr = flag.String(`pubsub`, `:3456`, `set pubsub address`) topic = flag.String(`topic`, `hellogrpc`, `set topic for subscribe`) timeout = fla...
package requests import ( "encoding/json" "fmt" "io/ioutil" "net/url" "strings" "github.com/google/go-querystring/query" "github.com/atomicjolt/canvasapi" "github.com/atomicjolt/canvasapi/models" "github.com/atomicjolt/string_utils" ) // GetSingleCourseCourses Return information on a single course. // // A...
package image import ( "context" "os" "path/filepath" "github.com/Dynatrace/dynatrace-operator/src/controllers/csi/metadata" "github.com/Dynatrace/dynatrace-operator/src/dockerconfig" dtypes "github.com/Dynatrace/dynatrace-operator/src/dtclient" "github.com/Dynatrace/dynatrace-operator/src/installer/common" "...
package services import ( "github.com/aswinda/notifyme/application/api/interfaces" ) type UserService struct { interfaces.IUserRepository } func (service *UserService) GetUserDetail(userId int) (string, error) { result, err := service.GetUserDetail(userId) if err != nil { // handle error } return result, ni...
package main import ( "fmt" "net" "bufio" "strings" ) func game(conn1 net.Conn, conn2 net.Conn) { writer1 := bufio.NewWriter(conn1) reader1 := bufio.NewReader(conn1) writer2 := bufio.NewWriter(conn2) reader2 := bufio.NewReader(conn2) for { // conn1 からの入力待ち line1, err1 := reader1.ReadString('\n') if ...
package main import ( "fmt" "regexp" "strconv" "strings" "github.com/igvaquero18/hermezon/scraper" ) type price struct{} // Run checks all the products in the database and tracks its // price in the corresponding store, looking for price drops. func (p price) Run() { sugar.Debug("checking all products for pri...
// 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 memory const ( // KiB is the number of bytes in a kibibyte. KiB = 1024 // MiB is the number of bytes in a mebibyte. MiB = KiB * 1024 // GiB is the number of byt...
package symmetrictree import ( "github.com/ovsoil/leetcode/framework/structures" ) // TreeNode Use structures.TreeNode type TreeNode = structures.TreeNode /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isSymmetric(root *T...
package main import ( "fmt" // "net/http" "os" "runtime" "sync" "sync/atomic" "time" ) var ( startIncr int32 endIncr int32 ) const goCount = 100000 const plusCount = 10000 const callCount = 1000 func IncrCounter(num *int32) { atomic.AddInt32(num, 1) } func LoadCounter(num *int32) int32 { return atomic...
package main import ( "fmt" "github.com/jinzhu/gorm" "github.com/spf13/viper" ) //DbConnection - This method will initialize a GORM DB object with the database information. func DbConnection(c *viper.Viper) (*gorm.DB, error) { db, err := gorm.Open("postgres", fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmod...
package main import ( "bytes" "math" ) type Statistics struct { letters []Letter } type Letter struct { lower []byte upper []byte count int expected float64 freq float64 } func percent(a, b int) float64 { /* Takes in two numbers and returns the percentage */ return (float64(a) / float64(b)) * 100 } fun...
package parking import ( "reflect" "testing" ) func Test_110(t *testing.T) { want := []bool{true, true, false, false} ps := Constructor(1, 1, 0) got := []bool{ ps.AddCar(1), ps.AddCar(2), ps.AddCar(3), ps.AddCar(1), } if !reflect.DeepEqual(want, got) { t.Fatalf("\nwant:%v\ngot :%v\n", want, got) }...
package main import ( "context" "fmt" "net/http" "time" "golang.org/x/sync/singleflight" ) var gt singleflight.Group func greetTimer(w http.ResponseWriter, r *http.Request) { var results singleflight.Result fmt.Println("Greet", time.Now()) defer fmt.Println("Greet finished", time.Now()) ctx, _ := context....
package server import ( "net/http" "github.com/gorilla/mux" "google.golang.org/appengine/datastore" "google.golang.org/appengine" "strconv" "io/ioutil" "encoding/json" ) type Wallet struct { Id int64 `json:"id"datastore:"-"` Name string `json:"name"` Balance float64 `json:"balance"` } func GetWallet(w http...
package models import "github.com/astaxie/beego/orm" func init() { orm.RegisterModel(&UserSkills{}) } type UserSkills struct { Id int User *User `orm:"rel(fk)"` Skill *Skill `orm:"rel(fk)"` Level int } func (u *UserSkills) TableIndex() [][]string { return [][]string{ []string{"Id", "User"}, } }
/* Copyright 2016 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 agreed to in writing, ...
// Package locker provides locker interface // package locker //go:generate mockgen -source=main.go -destination=./mock_locker/main.go import ( "context" "io" "time" ) type ( Locker interface { LockContext(context.Context, time.Duration) error UnLock() error TryLock() error io.ReadWriteSeeker io.Closer...
package task107 import ( "math" ) func FindNum(k int) int { result := 0 if k > 1 { for i := 1; i < k; i++ { if math.Pow(4, float64(i)) < float64(k) { result = i } } return result } return 0 }
package main import ( "fmt" "sync" "sync/atomic" ) var incr uint64 //incrementor func main() { var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func() { atomic.AddUint64(&incr, 1) fmt.Println("Increment is:", atomic.LoadUint64(&incr)) wg.Done() }() } wg.Wait() println("All ro...
package gocosmos import ( "fmt" "reflect" "testing" ) func TestStmt_NumInput(t *testing.T) { name := "TestStmt_NumInput" testData := map[string]int{ "CREATE DATABASE dbtemp": 0, "DROP DATABASE dbtemp": 0, "CREATE DATABASE IF NOT EXISTS dbtemp": 0, "DROP DATABASE IF EXISTS db...
package main import ( "github.com/stretchr/testify/assert" "math/big" "testing" ) type Pair struct { a int b int64 } func TestFib(t *testing.T) { initdp() vals := [14]Pair{{1, 1}, {8, 21}, {15, 610}, {22, 17711}, {29, 514229}, {36, 14930352}, {43, 433494437}, {50, 12586269025}, {57, 365435296162}, {64, 1061...
package logging // Config ログ設定構造体. type Config struct { filePath string fileName string levelFile Level levelConsole Level } // NewConfig ログ設定を作成します. func NewConfig(filePath, fileName string, levelFile, levelConsole Level) *Config { return &Config{ filePath, fileName, levelFile, levelConsole, ...
package main import ( "fmt" "github.com/micro/go-config" ) func main() { config.LoadFile("config.json") fmt.Println(config.Map()["mongo"]) }
package dlink import ( "log" ) func ConfigureDHCPAuto(destination string, user string, _ string) { t, err := NewTelnet(destination) if err != nil { log.Fatalln(err) } Login(t, user) t.Sendln("config dhcp_auto enable") t.Expect("DGS-3100# ") WriteConfig(t) Reboot(t) } // func configure(destination string...
package main import ( "sort" "testing" ) func TestAlphabetic(t *testing.T) { for _, tc := range []struct{ name string strings alphabetic want []string } { { name: "basic", strings:alphabetic{"a.b", "d.c", "b.e"}, want: []string{"a.b", "b.e", "d.c"}, }, { name: "withKeysAndValues", strin...
/* Copyright 2020 Docker Compose CLI 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 a...
package tempconv // CToF converts a Celsius temperature to a Fahrenheit func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) } // FToC converts a Fahrenheit temperature to a Celsius func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) } // KToC converts a Kelvin temperature to a Celsius func...
package subscraping import ( "context" "crypto/tls" "net/http" "time" ) // NewSession creates a new session object for a domain func NewSession(domain string, keys Keys, timeout int) (*Session, error) { client := &http.Client{ Transport: &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 100...
package client_test import ( "context" "crypto/x509" "fmt" "io/ioutil" "path/filepath" "testing" "github.com/EventStore/EventStore-Client-Go/stream_position" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/EventStore/EventStore-Client-Go/client" "github.com/EventSto...
package app import ( "errors" "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestIsInvalidRequestError(t *testing.T) { stdErr := errors.New("simple error") assert.False(t, IsInvalidRequestError(stdErr)) irErr := InvalidRequestError("invalid request") assert.True(t, IsInvalidRequestError(irErr))...
package main import ( "os" "log" "encoding/csv" "io" "fmt" ) func main() { irisCsv,err:=os.Open("readingcsv/data/iris.csv") if err!=nil{ log.Fatal(err) } reader:=csv.NewReader(irisCsv) reader.FieldsPerRecord=-1 var irisData [][]string for { record,err:=reader.Read() if err!=nil { if err==i...
package client type TankMessage map[string]interface{} func (m TankMessage) Id() int64 { return int64(m.Tank()["Id"].(float64)) } func (m TankMessage) Tank() Message { return Message(m["Tank"].(map[string]interface{})) }
package main import ( "fmt" "log" "time" ) func main2() { model := QueuedScheduler{} model.Run() for i := 0; i < 10 ; i++ { worker := make(chan int) go func(i int) { for{ model.WorkerReady(worker) // 去分发一个worker 让request 分发 request := <- worker // 收到10个 time.Sleep(time.Second) log...
package routing import ( "allbooks/models" "strings" ) type CollectionContext struct { Context models.CollectionContext } type CollectionAction func(context *CollectionContext) func NewCollectionRoute(name, method, pattern string, action CollectionAction) Route { wrapperAction := func(context Context) { coll...
// 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...
// Copyright 2022 Gravitational, 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 agree...
// +build ignore package humanize import "os" var fl, err = os.Create("/some/path")
package model_test import ( "testing" "github.com/apex/log" "github.com/ooni/probe-cli/v3/internal/engine/model" ) func TestPrinterCallbacksCallbacks(t *testing.T) { printer := model.NewPrinterCallbacks(log.Log) printer.OnProgress(0.4, "progress") }
package events import "time" func (e *Event) TimeOffset() time.Duration { return time.Duration(e.Time) * time.Millisecond }
package dynamic_programming import ( "math" "testing" ) //石子游戏 func stoneGame(piles []int) bool { n := len(piles) //dp[i][j]表示i到j之间Alex最多可以赢Lee的分数 dp := make([][]int, n) for i := 0; i < n; i++ { dp[i] = make([]int, n) } for i := 0; i < n; i++ { dp[i][i] = piles[i] } for i := 1; i < n; i++ { for j := ...
package main import ( "context" "fmt" "net/http" "os" "runtime" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "pack.ag/amqp" kingpin "gopkg.in/alecthomas/kingpin.v2" ) var ( username string pass...