text
stringlengths
11
4.05M
package main import ( "fmt" "sync" "sync/atomic" "time" ) var ( shutDown int32 wg sync.WaitGroup ) func main() { wg.Add(2) go doWork("aaa") go doWork("bbb") time.Sleep(1000 * time.Millisecond) atomic.StoreInt32(&shutDown, 1) wg.Wait() fmt.Println("main finish.") } func doWork(name string) { d...
package handler import ( "net/http" "github.com/gin-gonic/gin" "github.com/new-adventure-areolite/grpc-app-server/pd/fight" ) // LoadSession ... func LoadSession(fightSvcClient fight.FightSvcClient) gin.HandlerFunc { return func(c *gin.Context) { userID := c.GetString("id") resp, err := fightSvcClient.LoadS...
package main import ( "math" "fmt" ) /* You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. Example...
package server import ( "net/http/httptest" "strings" "testing" "github.com/tjheslin1/Patterdale/testutil" ) func TestCloseHandler_ServeHTTP(t *testing.T) { respRecorder := httptest.NewRecorder() quit := make(chan bool, 1) testLogger := testutil.NewTestLogger() closeHandler := &closeHandler{quit, testLogge...
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func read_input(filePath string) []string { f, err := os.Open(filePath) if err != nil { panic(err) } defer f.Close() var lines []string scanner := bufio.NewScanner(f) for scanner.Scan() { lines = append(lines, scanner.Text()) } if err :=...
package api import ( "context" "github.com/powerman/narada-go/narada" "github.com/qarea/ctxtg" "github.com/qarea/jirams/entities" ) var l = narada.NewLog("api: ") // NewRPCAPI creates an instance of API, implementing RPC interface func NewRPCAPI(client TrackerClient, parser ctxtg.TokenParser) *API { return &AP...
package main import( "fmt" ) // variadic functions with fibonacci numbers func numb(nums ...int) { fmt.Print(nums, " ") total := 0 for _, num := range nums { total += num } fmt.Println("sum of the numbers:", total) } func main() { fmt.Println("") fmt.Println("Fibonacci numbers:") fmt.Pri...
package cursor import ( "github.com/gomodule/redigo/redis" "log" ) type Cursor struct { conn redis.Conn count int hasDone bool next int } func New(conn redis.Conn, count int) *Cursor { if count <= 0 { count = 256 } return &Cursor{conn: conn, count: count, hasDone: false, next: 0} } func (cursor *...
package utils import ( "testing" "github.com/OrbitalbooKING/booKING/server/models" ) func TestHashPassword_ValidInput(t *testing.T) { testUser := models.User{ Nusnetid: "e123", Password: "123", } unHashedUser := testUser err := HashPassword(&testUser) if err != nil { t.Errorf("Expected no errors. Got th...
package edgediscovery import ( "encoding/json" "fmt" "net" "strings" ) const ( protocolRecord = "protocol-v2.argotunnel.com" ) var ( errNoProtocolRecord = fmt.Errorf("No TXT record found for %s to determine connection protocol", protocolRecord) ) type PercentageFetcher func() (ProtocolPercents, error) // Pro...
// Copyright (C) 2020 Storj Labs, Inc. // See LICENSE for copying information. package pb import proto "github.com/gogo/protobuf/proto" // Unmarshal is an alias for proto.Unmarshal. func Unmarshal(buf []byte, pb proto.Message) error { return proto.Unmarshal(buf, pb) } // Marshal is an alias for proto.Marshal. func ...
package main import ( "fmt" "github.com/akamensky/argparse" "kubeitcli/ConfigHandler" "kubeitcli/httpd" "kubeitcli/httpd/functions" "os" ) var rClient httpd.RequestClient var cHandler ConfigHandler.ConfigHandler func main() { parser := argparse.NewParser("kubeit", "Handler for creating kubeIT workflows and sc...
package main import ( "flag" "fmt" "log" "net/rpc" "net/rpc/jsonrpc" "time" "github.com/yam8511/zrpc" ) // Arith 數學運算 type Arith int // Args 參數 type Args struct { A, B int } // Sum 總和 func (t *Arith) Sum(args *Args, sum *int) error { if args.A == 0 && args.B == 0 { return zrpc.NewZrpcError("422", "缺少參數"...
package stdlib import ( "context" "encoding/json" "time" "github.com/niolabs/gonio-framework" "github.com/niolabs/gonio-framework/props" ) type CounterIntervalSimulatorBlock struct { nio.Producer Config CounterIntervalSimulatorConfig duration time.Duration limit int64 total int64 count int64 s...
// 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 metrics import ( "io/ioutil" "os" "reflect" "strconv" "strings" "testing" ) // makeHist parses a sequence of pipe-separated "<min> <max> <count>" buckets, // ...
package util import ( "crypto/md5" "crypto/sha1" "encoding/hex" "hash" "io" "os" ) type Sha1Stream struct { _sha1 hash.Hash } func (s *Sha1Stream) Upload(data []byte) { if s._sha1 == nil { s._sha1 = sha1.New() } s._sha1.Write(data) } func (s *Sha1Stream) Sum() string { return hex.EncodeToString(s._sha1...
package main import "fmt" func main() { fmt.Println("print test1() return v=", test1()) fmt.Println("print test1() return v=", test2()) fmt.Println("print test1() return v=", test3()) fmt.Println("print test1() return v=", test4()) } // 执行顺序 // return最先执行->return负责将结果写入返回值中->接着defer开始执行一些收尾工作->最后函数携带当前返回值退出 // 函...
// Copyright 2018 SEQSENSE, 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 db // AccountManager ... type AccountManager interface { AddAccount(*Account) error UpdateAccount(*Account) error } // FolderManager ... type FolderManager interface { AddRoot(*Folder) error UpdateRoot(*Folder) error AddChildToFolder(rootID string, parentID string, child *Folder) error RemoveChildFromFo...
package router import ( "github.com/gin-gonic/gin" "github.com/ramailh/backend/fetch/rest/controller" "github.com/ramailh/backend/fetch/rest/middlewares" ) func NewRouter() *gin.Engine { rtr := gin.Default() fetch := rtr.Group("/fetch") { fetch.GET("/with-usd", middlewares.JWTAuth, controller.GetDataWithUSD)...
// 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 types type LoginRequest struct { Name string `form:"name" binding:"required,min=3,max=10"` Password string `form:"password" binding:"required,min=12,max=20"` } type RegisterRequest struct { LoginRequest Email string `form:"email" binding:"required,email"` Phone string `form:"phone" binding:"omi...
// 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 meechum type Handler interface { Fire(*Result) error Levels() []ErrorCode String() string } var handlers map[string][]Handler func RegisterHandler(n Handler) error { if handlers == nil { handlers = make(map[string][]Handler, 50) } for _, level := range n.Levels() { handlers[level.String()] = append...
package main import ( "backend-github-trending/db" "backend-github-trending/handler" "backend-github-trending/log" "backend-github-trending/repository/repo_imp" "backend-github-trending/router" "fmt" "github.com/labstack/echo/v4" "os" ) func init() { fmt.Println("init package main") os.Setenv("APP_NAME", "...
package main import "fmt" /* ---------------------- n = 0, r(0) = 0 n = 1, r(1) = 10 n = 2, r(2) = 9 * 9 + r(1) n = 3, r(3) = 9 * 9 * 8 + r(2) + r(1) n = 11, r(11) = 9 * 9 * 8 * ... * 2 * 1 * 0 + r(10) + ... + r(1) ---------------------- */ func countNumbersWithUniqueDigits(n int) int { if (n == 0) { return 1 } ...
package main import ( "fmt" "time" ) func main() { i := 2 fmt.Print("write ", i, " as ") switch i { case 1: fmt.Println("one") case 2: fmt.Println("two") case 3: fmt.Println("three") } // comma for multiple expressions // use of default switch time.Now().Weekday() { case time.Saturday, time.Sunday...
package main import "fmt" func main() { fmt.Println("The numbers program shows you how to add, subtract") fmt.Println("multiple and divide integer numbers.") fmt.Println("One plus one is typed: 1+1") fmt.Print("1+1=") fmt.Println(1 + 1) fmt.Println("Ten subtract three is typed: 10-3") fmt.Print("10-3=") fmt....
package matrix func MatrixMul(a, b [][]int64) [][]int64 { ret := [][]int64{} lenOfA := len(a) for i := 0; i < lenOfA; i++ { row := []int64{} for j := 0; j < lenOfA; j++ { sum := int64(0) for k := 0; k < lenOfA; k++ { sum += a[i][k] * b[k][j] } row = append(row, sum) } ret = append(ret, row)...
package memory import ( "context" "fmt" "github.com/adamluzsi/frameless/ports/comproto" "reflect" "sync" "github.com/adamluzsi/frameless/pkg/errorkit" "github.com/adamluzsi/frameless/ports/crud" "github.com/adamluzsi/frameless/pkg/reflectkit" "github.com/adamluzsi/frameless/ports/crud/extid" "github.com/ad...
package api import ( "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "time" "user/pkg/log" ) func NewGinEngine() *gin.Engine { e := gin.New() e.Use(loggerM(), gin.Recovery()) return e } func loggerM() gin.HandlerFunc { return func(ctx *gin.Context) { logger := log.WithContext(ctx) startTime := ti...
package http import ( "crypto/tls" "crypto/x509" "net/http" "strings" "github.com/go-logr/logr" regv1 "github.com/tmax-cloud/registry-operator/api/v1" "github.com/tmax-cloud/registry-operator/internal/common/auth" "github.com/tmax-cloud/registry-operator/internal/common/certs" logf "sigs.k8s.io/controller-ru...
package main import ( "fmt" "player" ) func main(){ fmt.Printf("\n作业一\n") ro:=rot{ r: 10, s: 0, Long: 0, } ro.s = ro.S() ro.Long = ro.L() fmt.Printf("%v",ro) //========================================== fmt.Printf("\n作业二\n") sp := player.Sporter{ Name: "王二狗", Sex: "未知", Sport: ...
package provider import ( "context" "errors" "fmt" "math" "os/exec" "regexp" "strconv" "strings" "time" "github.com/evcc-io/evcc/util" "github.com/evcc-io/evcc/util/jq" "github.com/evcc-io/evcc/util/request" "github.com/itchyny/gojq" "github.com/kballard/go-shellquote" ) // Script implements shell scri...
package myhttp import ( "fmt" "net/http" "strings" "log" "encoding/json" "sync" "time" "math" "strconv" ) var CacheMapWithTime sync.Map var CacheMap sync.Map func sayhelloName(w http.ResponseWriter, r *http.Request) { r.ParseForm() //解析参数,默认是不会解析的 fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息 fmt.Println("pa...
package backend import ( "time" ) type VmConfig struct { GpuCount int64 `json:"gpu_count"` GpuType string `json:"gpu_type"` Zone string `json:"zone"` } // StartAttributes contains some parts of the config which can be used to // determine the type of instance to boot up (for example, what image to use) typ...
package main import ( "context" "flag" "fmt" "log" "os" "os/signal" "syscall" "github.com/garciademarina/deporvillage/pkg/adding" broker "github.com/garciademarina/deporvillage/pkg/broker/rabbitmq" "github.com/garciademarina/deporvillage/pkg/listing" "github.com/garciademarina/deporvillage/pkg/server" "gi...
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copy...
package seq type Seq struct{ xs []string } func New(es ...string) Seq { return Seq{xs: es} } func (s Seq) Map(fi interface{}, args ...interface{}) Seq { switch f := fi.(type) { case func(string) string: for i, x := range s.xs { s.xs[i] = f(x) } case func(string, string, string, int) string: for i, x := ...
// 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 firmware import ( "context" "chromiumos/tast/remote/firmware" "chromiumos/tast/remote/firmware/fixture" "chromiumos/tast/testing" "chromiumos/tast/testing/hwde...
package crypto import ( "crypto/rand" "io" "shadowsocks-go/pkg/crypto/algorithm" "shadowsocks-go/pkg/util" ) //Crypto use for crypto wrap type Crypto struct { Key []byte alg algorithm.Algorithm } //NewCrypto create a new crypto func NewCrypto(method, password string) (*Crypto, error) { cryp := &Crypto{} va...
package seq import ( "github.com/stretchr/testify/assert" "testing" ) func TestAppend(t *testing.T) { res := NewGeneSeq(A,C,G) res.Append(NewGeneSeq(A,C)) assert.Equal(t, res.seq, NewGeneSeq(A,C,G,A,C).seq) } func TestEquality(t *testing.T) { //assert.True(t, newSeq([] Alphabet{A,C}, DNA).equal(newSeq([] Alp...
package butler import ( "errors" "fmt" "github.com/bmc-toolbox/bmcbutler/asset" "github.com/bmc-toolbox/bmclib/cfgresources" "github.com/bmc-toolbox/bmclib/devices" "github.com/sirupsen/logrus" "reflect" "strings" "time" ) type SetupAction struct { Asset *asset.Asset Id int Log *log...
package myError import ( "errors" ) // type error interface { // Error() string // } type errorString struct { Op string Err error } // New returns an error that formats as the given text. func New(text, reason string) error { return &errorString{text, errors.New(reason)} } func (a *errorString) Error() strin...
package kata import ("math") import ("strings") import("strconv") func NbDig(n int, d int) int { // your code k := 0.0 sum := 0 for i:= 0; i <= n; i++{ k = math.Pow(float64(i),2) s := strconv.Itoa(int(k)) j := strconv.Itoa(d) sum += strings.Count(s,j) } return sum }
package command import ( "fmt" "regexp" ) type GreetCommand struct { pattern *regexp.Regexp } func Greet() GreetCommand { return GreetCommand{regexp.MustCompile(`(?i)greet\s+([^\s].*)`)} } func (c GreetCommand) Pattern() *regexp.Regexp { return c.pattern } func (c GreetCommand) Run(query string) []string { r...
package query import ( "bytes" "strconv" "gophr.pm/gocql/gocql@3ac1aabebaf2705c6f695d4ef2c25ab6239e88b3" ) // SelectQueryBuilder constructs a select query. type SelectQueryBuilder struct { columns []string table string conditions []*Condition limit *int } // Select starts constructing a select q...
package configure import ( "errors" "time" "github.com/evcc-io/evcc/api" "github.com/evcc-io/evcc/charger" "github.com/evcc-io/evcc/meter" "github.com/evcc-io/evcc/util/templates" "github.com/evcc-io/evcc/vehicle" "gopkg.in/yaml.v3" ) type DeviceTestResult string const ( DeviceTestResultValid D...
package models import "go.mongodb.org/mongo-driver/mongo" // 仓库职员表 type WarehouseStuff struct { ComID int64 `json:"com_id" bson:"com_id"` //公司id UserId int64 `json:"user_id" bson:"user_id"` // 用户id Username string `json:"username" bson:"username"` // ...
package models type Nodes struct { NodesList []List `json:"list"` } type Location struct { City string `json:"city"` Latitude float64 `json:"latitude"` Longitude float64 `json:"longitude"` Country string `json:"country"` } type NetSpeed struct { Download float64 `json:"download"` Upload float64 `j...
package game import "time" type Miner struct { BaseMachine } func NewMiner(chunk *Chunk, x, y int, ori Orientation) *Miner { miner := &Miner{ BaseMachine: BaseMachine{ BaseObject: *NewBaseObject(x, y, chunk, ori, "Miner", TYPE_MACHINE), Level: 1, Frequency: 1, LastTick: time.Now(), In: ...
import ( "sort" "strings" ) /* * @lc app=leetcode id=648 lang=golang * * [648] Replace Words * * https://leetcode.com/problems/replace-words/description/ * * algorithms * Medium (56.02%) * Likes: 745 * Dislikes: 131 * Total Accepted: 56.3K * Total Submissions: 99.5K * Testcase Example: '["cat","b...
package grpc import ( "context" "github.com/fwidjaya20/demo-distributed-event-store/internal/event" "github.com/fwidjaya20/demo-distributed-event-store/internal/event/models" pb "github.com/fwidjaya20/demo-distributed-event-store/pkg/protobuf/eventstore" "log" ) type EventGrpcService struct { EventService event...
package forms import ( "errors" "fmt" "reflect" "strconv" "strings" ) // Form is the interface that wraps the validation functionality provided by this // package. To implement the Form interface, struct types must embed a pointer to // DefaultForm, since the interface includes unexported fields that DefaultForm...
package nats import ( "context" "fmt" "github.com/go-kit/kit/endpoint" "github.com/go-kit/kit/log" "github.com/nats-io/go-nats" ) // Server wraps an endpoint and implements http.Handler. type Server struct { e endpoint.Endpoint addr string dec DecodeRequestFunc enc Encod...
func removeDuplicates(inputStream chan string, outputStream chan string) { var last string for str := range inputStream { if str != last { outputStream <- str last = str } } close(outputStream) } // Напишите элемент конвейера (функцию), что запоминает предыдущее значение и отправляет значения // на след...
package solutions func rob(nums []int) int { rob, dontRob := 0, 0 for _, number := range nums { rob, dontRob = number + dontRob, max(dontRob, rob) } return max(dontRob, rob) }
package models import ( "bytes" "errors" "fmt" "net" "strconv" "strings" "sync/atomic" "time" ) //Room Модель чат комнаты type Room struct { //Канал обмена сообщениями MessageChannel chan []byte //Текущее количество пользователей UsersCount int64 //Максимальное количество пользователей в чате UsersLimit...
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. // See License for license information. package main import ( "os" "testing" "github.com/mattermost/mattermost-server/model" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestSlackAttachment(t *testing.T) {...
package processors import ( "bytes" "encoding/json" "fmt" "github.com/emqx/kuiper/common" "github.com/emqx/kuiper/xsql" "github.com/emqx/kuiper/xsql/plans" "github.com/emqx/kuiper/xstream" "github.com/emqx/kuiper/xstream/api" "github.com/emqx/kuiper/xstream/nodes" "os" "path" "strings" ) var log = common....
// Copyright (c) 2017 Kuguar <licenses@kuguar.io> Author: Adrian P.K. <apk@kuguar.io> // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including //...
package productCategoryModel import ( "hd-mall-ed/packages/common/database" "hd-mall-ed/packages/common/database/tableModel" ) // 售卖的商品分类 type ProductCategory tableModel.ProductCategory func (category *ProductCategory) GetList() (*[]tableModel.ProductCategoryBase, error) { list := &[]tableModel.ProductCategoryBas...
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package startstop import ( "context" "chromiumos/tast/testing" ) // Subtest defines a test runs in arc.StartStop. // Each implementation of Subtest can use the following...
// Copyright 2018 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 sheets import ( "context" "errors" "fmt" "strings" "github.com/alexizzarevalo/grades_management/src/msg" "google.golang.org/api/option" "google.golang.org/api/sheets/v4" ) type Cells struct { Grade string Carne string } type SheetsOptions struct { Id string Credentials string Cells ...
package docker import ( "fmt" "github.com/docker/docker/api/types/network" "golang.org/x/net/context" ) func (this _containerProvider) NetworkContainer( networkId string, containerId string, containerAlias string, ) (err error) { err = this.dockerClient.NetworkConnect( context.Background(), networkId, co...
// 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, ...
// 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 main import "fmt" func describe(s []int) { if s == nil { fmt.Printf("-> slice is nil\n\t") } fmt.Println("Len: ", len(s), " Cap: ", cap(s), "Values: ", s) } func main() { var primes []int // Slices are references to underlying array fmt.Printf("%T %v\n", primes, primes) if primes == nil { fmt.Prin...
package main import( "fmt" ) func main(){ fmt.Println("\nSimple if statment") fmt.Println("\n==================") fmt.Println("Enter a number:") var number int fmt.Scanln(&number) fmt.Println("\nEnter the number you are guessing") var guess int fmt.Scanln(&guess) fmt.Print("\nnumber and guess are ",number...
package main import ( "fmt" "reflect" "runtime" ) func div(a, b int) (int, int) { return a / b, a % b } func div2(a, b int) (q, r int) { return a / b, a % b } func div3(a, b int) (q, r int) { q = a / b r = a % b return } func evalWithError(a, b int, op string) (int, error) { switch op { case "+": retur...
package config import ( "fmt" "log" "os" "strconv" ) // declare port variable var ( PORT = 0 DBDRIVER = "" DBURL = "" ) // Load the variables from .env file func Load() { var err error PORT, err = strconv.Atoi(os.Getenv("API_PORT")) if err != nil { log.Println(err) PORT = 9000 } DBDRIVER = os...
package Week_07 import "sort" func relativeSortArray(arr1 []int, arr2 []int) []int { res := []int{} arr2Map := map[int][]int{} arr4 := []int{} for _, i := range arr2 { arr2Map[i] = make([]int, 0) } for _, i := range arr1 { if _, ok := arr2Map[i]; ok { arr2Map[i] = append(arr2Map[i], i) } else { ar...
// 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 health import ( "bufio" "context" "os" "strings" "chromiumos/tast/errors" "chromiumos/tast/local/croshealthd" "chromiumos/tast/local/jsontypes" "chromiumos/...
package main import ( "bufio" "flag" "io" "os" "strings" log "github.com/Sirupsen/logrus" ) var ( fdebug bool ) func init() { log.SetOutput(os.Stderr) } //Logger is the default log device, set to emit at the Error level by default func main() { flag.BoolVar(&fdebug, "debug", false, "enable debug mode (war...
package model import ( mysqlConfig "GoPass/config/mysql" "GoPass/lib/helper" "GoPass/lib/mysql" "github.com/jinzhu/gorm" ) type Cate struct { Id uint32 `json:"id"` Name string `gorm:"type:varchar(100);not null;unique_index" json:"name"` //分类名称 CreatedAt helper.JSONTime `gorm:"n...
package main import ( "strings" "testing" ) type tuple struct { p, q string } func TestStringRotation(t *testing.T) { for k, v := range map[tuple]bool{ tuple{"Hello", "lloHe"}: true, tuple{"Hello", "Hello"}: true, tuple{"Basefont", "tBasefon"}: true, tuple{"asdfasdf", "fdsa"}: false} { ...
/*------------------------------------------------------------------------- * * sar_collector.go * Sar collector * * * Copyright (c) 2021, Alibaba Group Holding Limited * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You ...
package main import ( "fmt" "os" "os/signal" "syscall" ) func main() { go signalListen() os.Exit(1) } func goexit() { os.Exit(2) } func signalListen() { c := make(chan os.Signal) signal.Notify(c, syscall.SIGUSR2) for { s := <-c fmt.Println("get signal:", s) } } /* jinlai@ubuntu:~/nbr_sysbuild/ra/to...
package main import "fmt" import "os" import "os/exec" import(. "linkcallback") import "unsafe" var head *LinkTable func help() int { ShowAllCmd(head) return 0 } func quit() int { os.Exit(1) return 0 } func add() int { var x int var y int fmt.Println("pls input two int numbers") fmt.Scanf("%d %d",&x,&y) re...
/* * @lc app=leetcode id=677 lang=golang * * [677] Map Sum Pairs * * https://leetcode.com/problems/map-sum-pairs/description/ * * algorithms * Medium (53.15%) * Likes: 506 * Dislikes: 81 * Total Accepted: 41.5K * Total Submissions: 77.5K * Testcase Example: '["MapSum", "insert", "sum", "insert", "su...
package apilifecycle import godd "github.com/pagongamedev/go-dd" // HandlerLogic Type type HandlerLogic = func(context *godd.Context, requestValidatedBody interface{}, requestValidatedParam interface{}, requestValidatedQuery interface{}) (code int, responseRaw interface{}, responsePagination *godd.ResponsePagination,...
package main import "testing" func TestHasSixDigits(t *testing.T) { a := 123456 if !SixDigitNumber(a) { t.Fail() } } func TestHasNotSixDigits(t *testing.T) { a := 12 if SixDigitNumber(a) { t.Fail() } } func isInRange(min, max, number int) bool { if number >= min && number <= max { return true } else {...
// Copyright 2021 Adobe. All rights reserved. // This file is licensed to you 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 applicab...
package leetcode type Node struct { Val int Children []*Node } func levelOrder(root *Node) [][]int { var ( ans [][]int temp []int ) if root == nil { return ans } queue := []*Node{root, nil} for len(queue) > 1 { node := queue[0] queue = queue[1:] if node == nil { queue = append(queue, ni...
package packets import ( "io" "bytes" ) type ConnlosePacket struct { FixedHeader Length byte Code byte } func (cl *ConnlosePacket) Write(w io.Writer) error { return nil } func (cl *ConnlosePacket) Unpack(b io.Reader) error { cl.Length = decode...
// Copyright 2020 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...
package generator import ( "fmt" "math" "math/rand" "time" ) // using a rand.Seed(n) function slows down all random functions // so in every function, we don't use a seed const ( // time TimeFormat = "2006-01-02 15:04:05" timeStartDate = "1970-01-01 00:00:01" timeEndDate = "2038-01-19 03:14:07" // cj...
package kmip import ( "bufio" "crypto/tls" "github.com/gemalto/kmip-go/kmip14" "github.com/gemalto/kmip-go/ttlv" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "testing" ) // clientConn returns a connection to the test kmip server. Should be closed at end ...
package main import ( "fmt" "os" "github.com/1garo/glanc/database" "github.com/spf13/cobra" ) // balancesCmd -> create balances cli command and it's configs func balancesCmd() *cobra.Command { var balancesCmd = &cobra.Command{ Use: "balances", Short: "Interact with balances (list...).", PreRunE: func(cm...
package server import ( "bufio" "fmt" "log" "net" "os" "strconv" ) func Run() { clientCount := 0 Clients := make(map[net.Conn]int) //Store number of clients Map<Conn Object, Clinet ID> // Channel into which the TCP server will push new connections. newConnections := make(chan net.Conn) // channel to push a...
package lc // Time: O(n) // Benchmark: 32ms 4.6 | 7% 20% // We remove all duplicates in a single append. func removeDuplicates(nums []int) int { for i := 0; i < len(nums)-1; i++ { if nums[i] == nums[i+1] { j := i + 1 for j < len(nums) { if nums[i] != nums[j] { break } j++ } nums = appe...
package db import ( "fmt" "log" jwt "github.com/dgrijalva/jwt-go" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" uuid "github.com/satori/go.uuid" "golang.org/x/crypto/bcrypt" ) type Credentials struct { Password string `json:"password", db:"password"` Username string `json:"username", db:"username"` } typ...
package main import ( "context" "database/sql" "errors" "net/http" "time" "github.com/dgrijalva/jwt-go" "github.com/gin-contrib/cors" "github.com/gin-contrib/pprof" "github.com/gin-gonic/gin" "github.com/rs/xid" "go.uber.org/zap" "github.com/alextanhongpin/go-microservice/api" "github.com/alextanhongpin...
package strings import ( "io/ioutil" "testing" ) func TestStrings(t *testing.T) { t.Run("TestExtractStrings", func(t *testing.T) { testCases := []struct { filename string expected []string }{ { filename: "../../testdata/eicar.com", expected: []string{`X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD...
// SPDX-License-Identifier: ISC // Copyright (c) 2014-2020 Bitmark Inc. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package transactionrecord_test import ( "bytes" "encoding/json" "reflect" "testing" "golang.org/x/crypto/ed25519" "github.com/bitmark-inc/b...
/* Links * http://brazengilbert.github.com/1.html * http://brazengilbert.github.com/2.html * http://brazengilbert.github.com/3.html * http://brazengilbert.github.com/4.html * http://brazengilbert.github.com/5.html * http://brazengilbert.github.com/6.html * http://brazengilbert.github.com/7.html * http://brazengilbert.g...
package e7 import ( "bytes" "context" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/url" "os" "strings" "testing" "time" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" ) const ( // baseURLPath is a non-empty Client.BaseURL path to use during tes...
package storage import ( "context" "time" ) const ( // Normally each op has its own timeout, but in case of buggy paths // this timeout serves as a catch-all to prevent mem leaks DefaultStorageTimeout = 5 * time.Minute ) // NewGoContext creates a new context with remaining timeout from the existing // request c...
package main import ( "fmt" ) type Person struct { name string age int8 } func zeroValue(n int) { n = 0 } func zeroPtr(n *int) { *n = 0 } func main() { var n int = 10 fmt.Println(n) zeroValue(n) fmt.Println(n) zeroPtr(&n) fmt.Println(n) fmt.Println(Person{"Bob", 20}) fmt.Println(Person{name: "Alic...