text
stringlengths
11
4.05M
package main import "testing" type tuple struct { n, s int } func TestSumint(t *testing.T) { for k, v := range map[tuple]int{ tuple{3, 0}: 3, tuple{23, 3}: 26, tuple{321, 26}: 347, tuple{21, 0}: 21, tuple{14, 21}: 35, tuple{35, 7}: 42} { if r := sumint(k.n, k.s); r != v { t.Errorf("faile...
package service import ( //"github.com/astaxie/beego" "webserver/common" //"webserver/controllers/hservice" "sort" "time" "tripod/timekit" "webserver/models" "webserver/models/maccount" "webserver/models/mservice" ) type CheckOfflineController struct { User *maccount.User CheckType int CheckValue...
// Copyright (c) 2020-2021 KHS Films // // This file is a part of mtproto package. // See https://github.com/xelaj/mtproto/blob/master/LICENSE for details package ige import ( "testing" "github.com/stretchr/testify/assert" ) func TestCipher_isCorrectData(t *testing.T) { tests := []struct { name string dat...
// Copyright 2018 The Cockroach Authors. // // Licensed as a CockroachDB Enterprise file under the Cockroach Community // License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // https://github.com/cockroachdb/cockroach/blob/master/li...
package datadogagent import ( "context" "testing" "github.com/DataDog/datadog-operator/apis/datadoghq/v1alpha1" "github.com/DataDog/datadog-operator/apis/datadoghq/v1alpha1/test" "github.com/DataDog/datadog-operator/pkg/kubernetes" assert "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" rbacv...
package aws import ( "encoding/base64" "errors" "log" "reflect" "testing" "time" "github.com/NYTimes/gizmo/pubsub" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/sqs" "github.com/aws/aws-sdk-go/service/sqs/sqsiface" "github.com/golang/protobuf/pr...
package model type User struct { Id uint `gorm:"primary_key;auto_increment" json:"id"` Name string `json:"name"` Password string `json:"password"` Email string `json:"email"` Status int `json:"status"` } func (u *User) TableName() string { return "user_info" }
package main import ( "flag" "log" "net" "github.com/cloudnoize/dig/dnsmsg" ) func main() { doamin := flag.String("d", "google.com", "domain") flag.Parse() udpaddr, err := net.ResolveUDPAddr("udp", "8.8.8.8:53") if err != nil { log.Fatal(err) } /* socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOC...
package stor import ( "github.com/oceanho/gw" "github.com/oceanho/gw/contrib/apps/stor/api" ) func init() { } type App struct { } func New() App { return App{} } func (a App) Name() string { return "gw.stor" } func (a App) Router() string { return "stor" } func (a App) Register(router *gw.RouterGroup) { ro...
package podlogstream import ( "context" "fmt" "sync" "time" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/util/workqueue" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/cont...
package kuma import "github.com/layer5io/meshery-adapter-library/status" func (kuma *Kuma) applyCustomOperation(namespace string, manifest string, isDel bool) (string, error) { st := status.Starting err := kuma.applyManifest(isDel, namespace, []byte(manifest)) if err != nil { return st, ErrCustomOperation(err) ...
// Copyright 2019 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 rty import ( "fmt" "github.com/gdamore/tcell" ) // Canvases hold content. type Canvas interface { Size() (int, int) SetContent(x int, y int, mainc rune, combc []rune, style tcell.Style) Close() (int, int) GetContent(x, y int) (mainc rune, combc []rune, style tcell.Style, width int) } func totalHeight...
package core import ( "github.com/cadmium-im/zirconium-go/core/models" "github.com/gorilla/websocket" ) type Session struct { wsConn *websocket.Conn connID string Claims *JWTCustomClaims } func (s *Session) Send(message models.BaseMessage) error { return s.wsConn.WriteJSON(message) } func (s *Session) Receive...
package binary_search import "testing" func TestSearch(t *testing.T) { subTests := []struct { input []int target int result int }{ { input: []int{-1, 0, 3, 5, 9, 12}, target: 9, result: 4, }, { input: []int{-1, 0, 3, 5, 9, 12}, target: 2, result: -1, }, } for _, test := range s...
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package camt_v08 import ( "reflect" "regexp" "github.com/moov-io/iso20022/pkg/utils" ) // Must be at least 1 items long type ExternalAccountIdentification1Code string ...
package cmd import ( "fmt" "strings" "github.com/spf13/cobra" ) var fetchMessagesCmd = &cobra.Command{ Use: "fetch-messages", Aliases: []string{"fetch"}, Short: "Retrieves messages from your account(s)", Long: `Connects to the BitMaelum servers and fetches new emails that are not available on your local sys...
package main import ( "bytes" "errors" "fmt" "regexp" "strings" "github.com/irfansharif/log" ) type logMode struct { m log.Mode set bool } func (l logMode) String() string { return modeToString(log.Mode(l.m)) } func (l *logMode) Set(value string) error { l.set = true m, err := modeFromString(value) ...
package main import ( "net/http" "time" "github.com/BKH7/go-client/fetch" "github.com/sirupsen/logrus" ) func main() { err := fetch.PostMsg(&http.Client{Timeout: 5 * time.Second}, &fetch.MsgStruct{ ID: 1, Sender: "Tom", Msg: "Hello", }) if err != nil { logrus.Error(err) } }
/* * Created on Thu Feb 28 2019 9:15:33 * Author: WuLC * EMail: liangchaowu5@gmail.com */ // simple solution func numRookCaptures(board [][]byte) int { result := 0 for i := 0; i < 8; i++ { for j := 0; j < 8; j++ { if board[i][j] == 'R' { directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} for _,...
package vite import ( "fmt" "testing" ) func TestWallet(t *testing.T) { Setup() mnemonic, em, err := NewMnemonicAndEntropyStore("111111") fmt.Println(mnemonic, em, err) } func TestGetPrimaryAddr(t *testing.T) { Setup() addr := GetPrimaryAddr() fmt.Println(addr) }
package mydsl import ( "gopkg.in/yaml.v2" "io/ioutil" "os" "testing" ) func TestForCoverage(t *testing.T) { f, err := os.Open("test/yamls/testsuite.yml") if err != nil { t.Fatalf("open error:%v", err) } defer f.Close() yamlInput, err := ioutil.ReadAll(f) if err != nil { t.Fatalf("read error:%v", err) ...
package routes import "github.com/labstack/echo/v4" // InitRoutes init all routes func InitRoutes(e *echo.Echo) { initAuthRoutes(e) initTodoRoutes(e) }
package rex import ( potato "github.com/rise-worlds/potato-go" ) func NewDeposit(owner potato.AccountName, amount potato.Asset) *potato.Action { return &potato.Action{ Account: REXAN, Name: ActN("deposit"), Authorization: []potato.PermissionLevel{ {Actor: owner, Permission: potato.PermissionName("active...
// 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 firmware import ( "context" "fmt" "regexp" "strconv" "time" gossh "golang.org/x/crypto/ssh" fwCommon "chromiumos/tast/common/firmware" "chromiumos/tast/com...
package util import ( "fmt" "testing" "github.com/kylelemons/godebug/pretty" ) func TestGroupNames(t *testing.T) { var names []string for i := 1; i <= 5; i++ { names = append(names, fmt.Sprintf("server%d.loadavg5", i)) } nameGroups := GroupNames(names, 2) expected := [][]string{ {"server1.loadavg5", "ser...
// Copyright The runc Authors. // Copyright The containerd Authors. // Copyright 2021 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 // // https://www.apache.org/...
package semanticanalyzer import ( "compiler/src/types" "errors" "log" ) var globalSymbolTable = map[string]types.STEntry{} var builtinSymbolTable = map[string]types.STEntry{} func SemanticAnalysis(node *types.ParseNode, parseGlobalSymbolTable map[string]types.STEntry, parseBuiltinSymbolTable map[string]types.STEn...
package main import ( "testing" ) func TestTarget(t *testing.T) { t.Run("test1", func(t *testing.T) { // t.Parallel() if target() != true { t.Fatalf("ng detara dou naru no") } }) }
package cis var ( network1 = Recommendation{ Name: "Ensure the default network does not exist in a project", CisID: "3.1", Scored: true, Level: 1, } network2 = Recommendation{ Name: "Ensure legacy networks does not exists for a project", CisID: "3.2", Scored: true, Level: 1, } network3 = R...
package main import "fmt" //给你一个整数数组 nums,请你将该数组升序排列。 /////////////////////// 冒泡排序法 ///////////////////////// func sortArray(nums []int) []int { for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { if nums[i] > nums[j] { nums[i], nums[j] = nums[j], nums[i] } } } fmt.Println(nums) r...
package stack import "testing" //对于每一个高度 求出它的左右边界 即为面积 //如果有两根柱子 j0 j1 如果j1<j0 j0会被j1挡住 //单调栈 柱状图中最大的矩形 func largestRectangleArea(heights []int) int { n := len(heights) left, right := make([]int, n), make([]int, n) monoStack := []int{} //从左往右 找出每一个位置的左边界 index for i := 0; i < n; i++ { //如果元素高度始终小于栈顶元素 入栈 ...
package pool import ( "time" "sync" "container/list" ) type PoolObject struct {} func (p *PoolObject) LongOperation() { time.Sleep(time.Millisecond * 100) } type Pool struct { sync.Mutex available *list.List unavailable *list.List } func NewPool(total int) *Pool { l := list.New() for i := 0; i < ...
package handler import ( "log" "net" "puck-server/db-server/dbservice" "puck-server/db-server/user" "puck-server/match-server/convert" "regexp" ) func HandleSetNickname(buf []byte, conn net.Conn, dbService dbservice.Db) { log.Printf("SETNICKNAME received") // Parse recvPacket, err := convert.ParseSetNickname...
package swagger import ( "github.com/go-openapi/spec" "strings" ) func NewSwagger() *Swagger { swagger := new(spec.Swagger) swagger.Swagger = "2.0" if swagger.Paths == nil { swagger.Paths = new(spec.Paths) } if swagger.Definitions == nil { swagger.Definitions = make(map[string]spec.Schema) } if swagge...
package partition import ( "gpartition/common" ) // PartitionType defines different partition type PartitionType int8 const ( //BdgPartitionType type BdgPartitionType PartitionType = iota //ShpPartitionType type ShpPartitionType //TShpPartitionType type TShpPartitionType ) // Config all type of config type ...
//go:generate mockgen -source=fs/fs.go -package fs -destination=fs/fs_mock.go package infra
// 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 iw contains utility functions to wrap around the iw program. package iw import ( "chromiumos/tast/common/network/iw" "chromiumos/tast/local/network/cmd" ) // R...
package activity import ( "context" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/bson" "errors" "fmt" "github.com/go-kit/kit/log" ) var RepoErr = errors.New("Unable to handle Repo Request") const ( database = "buddyApp" collection = "sys_activities" ) type repo struct { db *mongo.Cl...
package enums //ResponseStatus codes type ResponseStatus int type status struct { SUCCESS ResponseStatus ERROR ResponseStatus } //Status AppResonseStatus codes var Status = &status{ SUCCESS: 204, ERROR: 402, }
package model import ( "database/sql" ) // Message はメッセージの構造体です type Message struct { ID int64 `json:"id"` Body string `json:"body"` // 1-1. ユーザー名を表示しよう SenderName string `json:"sender_name"` } // MessagesAll は全てのメッセージを返します func MessagesAll(db *sql.DB) ([]*Message, error) { // 1-1. ユーザー名を表示しよう rows...
// Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc> // See LICENSE for licensing information package main import ( "encoding/json" "log" "os" ) var cmdDefaults = &Command{ UsageLine: "defaults", Short: "Reset to the default settings", } func init() { cmdDefaults.Run = runDefaults } func runDefaults(args...
package dockerfile import ( "testing" "github.com/stretchr/testify/assert" "github.com/tilt-dev/tilt/internal/container" ) func TestInjectUntagged(t *testing.T) { df := Dockerfile(` FROM gcr.io/windmill/foo ADD . . `) ref := container.MustParseNamedTagged("gcr.io/windmill/foo:deadbeef") newDf, modified, err :...
package main func foox(sl []int) { sl[0] = 9 } func fooy() string { defer println("fooy defer") panic("fooy panic") return "fooy func" } func main() { /** sl := make([]int, 10) fmt.Println(reflect.TypeOf(sl)) sl = append(sl, 1) fmt.Println(sl) foox(sl) fmt.Println(sl) */ fooy() }
package backend import ( "net/http" "github.com/goadesign/goa" "github.com/MiCHiLU/goapp-scaffold/app" ) type itemController struct { *goa.Controller } func newItemsController(service *goa.Service) *itemController { return &itemController{Controller: service.NewController("itemController")} } func (c *itemCo...
package countchars import ( "math/rand" "testing" "github.com/ninedraft/huffy" ) func TestDiv(test *testing.T) { type TestCase struct { X, Y int Expected int } huffy.Tester{ Generator: func(rnd *rand.Rand, id int) interface{} { var x = rnd.Intn(100) + 2 var y = rnd.Intn(x-1) + 1 var expecte...
package store import ( "github.com/golang/protobuf/proto" "github.com/syndtr/goleveldb/leveldb" ) // ErrNotFound ... var ErrNotFound = leveldb.ErrNotFound // Store ... type Store interface { Save(*Route) error Delete(string) error Load(string, *Route) error LoadAll() ([]*Route, error) Close() error } // Stor...
package main import ( "log" "os" ) func main() { filename := os.Args[1] f, err := os.Open(filename) if err != nil { log.Fatal(err) } parser := NewParder(f) codeWriter := NewCodeWriter(os.Stdout) codeWriter.SetFileName(filename) for parser.HasMoreCommands() { log.Printf("%s", parser.line) switch parse...
package auth import ( "errors" userModel "go_simpleweibo/app/models/user" "go_simpleweibo/config" "github.com/gin-gonic/gin" ) // SaveCurrentUserToContext : 保存用户数据到 context 中 func SaveCurrentUserToContext(c *gin.Context) { user, err := getCurrentUserFromSession(c) if err != nil { return } c.Keys[config.Ap...
package repository_test import ( "context" "fmt" "testing" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/sesha04/test_kumparan/article/repository" "github.com/sesha04/test_kumparan/domain" "github.com/stretchr/testify/assert" ) func TestStore(t *testing.T) { ar := &domain.Article{ Title: "Judul", ...
// Copyright 2017 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 bitarray implements the Sieve interface. * This is *NOT* a threadsafe package. */ package sieve import ( "fmt" "math" "math/bits" ) const ( constUint64BitCount = 64 constUint64MaxValue = math.MaxUint64 ) // bitarray is a struct that maintains state of a bit array. type bitarray struct { blks []...
package commands import ( "encoding/xml" "log" "testing" ) func TestFullCallsListParse(t *testing.T) { cmd := []byte(`<NCC from="naubuddy-17.node.domain" to="naucrm-68.node.domain"> <FullCallsList time_t="1513702855"/></NCC>`) var rs FullCallsList err := xml.Unmarshal(cmd, &rs) if err != nil { log.Fatalf(...
package middleware import ( "crud-using-chi/internal/models" "crud-using-chi/pkg/common" "fmt" "github.com/dgrijalva/jwt-go" "github.com/jmoiron/sqlx" "github.com/sirupsen/logrus" "github.com/spf13/viper" "net/http" ) type ( MiddlewareUser struct { Conf *viper.Viper Logger *logrus.Logger DB *sqlx...
package cmd import ( "sort" "github.com/object88/cprofile" ) func createGlobalsCommand(o *globalOptions) *astCmd { astSetup := &astSetup{ "globals", "Returns list of instances of global variables.", "Returns the list of global variables for a program, with file name and offsets.", func(p *cprofile.Program...
package deferTrap import "net/http" //因为在这里我们并没有检查我们的请求是否成功执行,当它失败的时候, //我们访问了 Body 中的空变量 res ,因此会抛出异常 func Do() error { res, err := http.Get("http://www.google.com") defer res.Body.Close() if err != nil { return err } // ..code... return nil } //在这里,你同样需要检查 res 的值是否为 nil ,这是 http.Get 中的一个警告。通常情况下,出错的时候,返回...
package slice import ( "fmt" "reflect" "sort" "github.com/xiagoo/gosort/consts" ) type baseSort struct { length int less func(i, j int) bool swap func(i, j int) } func (bs *baseSort) Len() int { return bs.length } func (bs *baseSort) Less(i, j int) bool { return bs.less(i, j) } func (bs *baseSo...
package overmount import ( "time" ) // ImageConfig is a portable, non-standard format used by overmount for the // generation of other configuration formats used in images. It is an attempt // to be abstract from the formats themselves. It is intentionally flat to // avoid merging problems with newer editions of ove...
package main import ( "github.com/stretchr/testify/assert" "testing" ) func TestRotationCase0(t *testing.T) { arr := []int{1, 2, 3, 4, 5} shift := 2 exp := "4 5 1 2 3 " assert.Equal(t, exp, SolveRotation(arr, shift)) } func TestRotationCase1(t *testing.T) { arr := []int{1, 2, 3, 4, 5} shift := 10 exp := "1...
package utils type Semaphore interface { Down() Up() } type semaphore struct { sem chan struct{} } func (s *semaphore) Down() { s.sem <- struct{}{} } func (s *semaphore) Up() { _ = <-s.sem } func NewSemaphore(capacity int) Semaphore { return &semaphore{ sem: make(chan struct{}, capacity), } }
package proteus import ( "context" "database/sql" ) // Executor runs queries that modify the data store. type Executor interface { // Exec executes a query without returning any rows. // The args are for any placeholder parameters in the query. Exec(query string, args ...interface{}) (sql.Result, error) } // Qu...
package store type Store interface { //Get(key) Get(string) (string, error) //Set(key, value) Set(string, string) //Delete(key) Delete(string) Close() //All() map[string]string }
package main // Leetcode 977. (easy) func sortedSquares(A []int) []int { i, j := 0, len(A)-1 res := make([]int, len(A)) k := len(A) - 1 for i <= j { if abs(A[i]) > abs(A[j]) { res[k] = A[i] * A[i] i++ } else { res[k] = A[j] * A[j] j-- } k-- } return res } func abs(a int) int { if a < 0 { ...
// SPDX-License-Identifier: MIT // Package apidoc RESTful API 文档生成工具 // // 从代码文件的注释中提取特定格式的内容,生成 RESTful API 文档,支持大部分的主流的编程语言。 package apidoc import ( "bytes" "log" "net/http" "path/filepath" "regexp" "time" "golang.org/x/text/language" "github.com/caixw/apidoc/v7/build" "github.com/caixw/apidoc/v7/core" ...
package sshd import ( "testing" "golang.org/x/crypto/ssh" ) const ( testingClientKey = `-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEArjUDq6/7ljVzoa7unbdSRMNIwfFd7S0YM931w7YstZXFvnuN eavoAxDkL0mdWxV0Pi6f+FFi31oY3YHUBaWdvkZHXCY9L3zWRKz00SRNnyeQG8tO GGhvhvgC6iGIE6A9IJlLxDm6scylp6JaN27P4CUNXy8gT0GnxvdwMGujgbMbPU2x...
// 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 vkb import ( "io/ioutil" "os" "reflect" "testing" "chromiumos/tast/local/coords" ) func TestNewStrokeGroup(t *testing.T) { want := &strokeGroup{ width: 0....
// 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 cellular import ( "context" "time" "chromiumos/tast/local/cellular" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/uiauto/ossettings" "chromiumo...
package data import ( "math/rand" "time" ) type Player struct { Name string Deck []Card } func (h *Player)AddToDeck(c Card) { h.Deck = append(h.Deck, c) } func (h *Player)GetNextCard() Card { if len(h.Deck) == 0 { return Card{ Rank: "", Suit: "", } ...
package messaging import ( "encoding/binary" "encoding/json" "fmt" "io" "log" "net/url" "os" "path/filepath" "sort" "strconv" "sync" "time" "github.com/boltdb/bolt" "github.com/influxdb/influxdb/raft" ) // DefaultPollInterval is the default amount of time a topic reader will wait // between checks for ...
package monitor import ( "time" "themis/config" "themis/database" ) const ( flagManage uint = 1 << 2 flagStorage uint = 1 << 1 flagNetwork uint = 1 << 0 // state stateTransitionInterval = 60 ) var ( flagTagMap = map[string]uint{ "manage": flagManage, "storage": flagStorage, "network": flagNetwork,...
package v1alpha1 import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // MongoClusterSpec defines the desired state o...
// Package producer implements a single partition Kafka producer. package producer import ( "fmt" "time" "github.com/mkocikowski/libkafka/api/Metadata" "github.com/mkocikowski/libkafka/api/Produce" "github.com/mkocikowski/libkafka/batch" "github.com/mkocikowski/libkafka/client" ) func parseResponse(r *Produce....
package uptime import ( "context" "encoding/json" "fmt" "net/http" "reflect" "testing" ) func TestTagList(t *testing.T) { client, mux, _, teardown := setup() defer teardown() mux.HandleFunc("/check-tags", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{"count": 1, ...
package main // type ListNode struct { // Val int // Next *ListNode // } func partition(head *ListNode, x int) *ListNode { dummy1 := &ListNode{Val: -1} cur1 := dummy1 dummy2 := &ListNode{Val: -1} cur2 := dummy2 for head != nil { if head.Val < x { cur1.Next = head cur1 = cur1.Next } else { cur2.Ne...
package modules import ( "context" "fmt" "io/ioutil" "net/http" "sync/atomic" "time" "github.com/buguang01/Logger" "github.com/buguang01/bige/messages" "github.com/buguang01/util/threads" ) //设置Web地址 func WebSetIpPort(ipPort string) options { return func(mod IModule) { mod.(*WebModule).ipPort = ipPort }...
// 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 power import ( "context" "regexp" "strings" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/dut" "chromiumos/tast/errors" "chromiumos/tast/remote/firmware...
package requests type AuthLoginOrSignupEmail struct { Email string `json:"email"` } type AuthSignupEmail struct { Email string `json:"email"` Password string `json:"password"` } type AuthLoginEmail struct { Email string `json:"email"` Password string `json:"password"` } type AuthLoginOrSignupSSO struct {...
package main func main() { { sum := 0 //for (i := 0; i < 10; i++) { for i := 0; i < 10; i++ { sum += i } println(sum) } { sum := 1 for sum < 1000 { sum += sum } println(sum) } { sum := 1 for sum < 1000 { sum += sum } println(sum) } { // IDEA detects infinite loop! //for...
package maths import ( "github.com/gonum/matrix/mat64" "github.com/gonum/stat" ) func Cov(mat *mat64.Dense) *mat64.SymDense { return stat.CovarianceMatrix(nil, mat, nil) }
package misc // IfElse 模拟三元操作符 func IfElse(condition bool, positiveVal, negativeVal interface{}) interface{} { if condition { return positiveVal } return negativeVal }
package main import ( "github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/cli/app" _ "github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/cli/autorun" _ "github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/cli/geoip" _ "github.com/ooni/probe-cli/v3/cmd/ooniprobe/internal/cli/info" _ "github.com/ooni/probe-cli/v3...
package main import ( "fmt" "github.com/humin09/demo/example" "github.com/humin09/helloworld/hello" "rsc.io/quote" ) // Hello is func of hello func Hello() { fmt.Println("demo hello begin") hello.Hello() quote.Hello() i := example.Add(1, 2) fmt.Printf("%d", i) } //World is func of world func World() { fmt...
package main //990. 等式方程的可满足性 //给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或"a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。 // //只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回true,否则返回 false。 // // // //示例 1: // //输入:["a==b","b!=a"] //输出:false //解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。 /...
// 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 main import ( "encoding/json" "net/http" "strconv" ) func reqInvalid(w http.ResponseWriter, r *http.Request) { response := &Json_decode_error{ Status: "400", Details: "Invalid TokenReview ( Json decode failed )", } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(htt...
package schema import ( "github.com/facebook/ent" "github.com/facebook/ent/schema/field" "github.com/google/uuid" ) // Users holds the schema definition for the Users entity. type Users struct { ent.Schema } // Fields of the Users. func (Users) Fields() []ent.Field { return []ent.Field{ field.UUID("id", uuid....
package utils import ( "fmt" "log" "math/rand" "net/http" "os" "sync" "time" ) var in chan string var out chan string var quit chan bool func SiegeMake(limNum int, limSec int) { wg := new(sync.WaitGroup) wg.Add(2) const worker = 12 in = make(chan string, 2*worker) out = make(chan string, 2*worker) quit ...
package dcrlibwallet func (mw *MultiWallet) AllWallets() (wallets []*Wallet) { for _, wallet := range mw.wallets { wallets = append(wallets, wallet) } return wallets } func (mw *MultiWallet) WalletsIterator() *WalletsIterator { return &WalletsIterator{ currentIndex: 0, wallets: mw.AllWallets(), } } f...
package main import ( "context" "database/sql" "encoding/json" "errors" "fmt" _ "github.com/denisenkom/go-mssqldb" "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/mongo" "github.com/mongodb/mongo-go-driver/mongo/options" "log" "strconv" "strings" "time" ) type database inter...
/* Copyright 2019 The Skaffold 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, sof...
// 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 avl_test import ( "crypto/rand" "encoding/binary" "fmt" "sort" "strings" "testing" "github.com/bitmark-inc/bitmarkd/avl" ) type st...
// Copyright 2017 Brian Starkey <stark3y@gmail.com> package rpcconn import ( "net" "net/rpc" "github.com/usedbytes/bot_matrix/datalink" ) type RPCEndpoint struct { transactor datalink.Transactor } type RPCServ struct { endpoint RPCEndpoint srv *rpc.Server } func (r *RPCEndpoint) RPCTransact(tx []datalink.Pac...
package errors type codeError struct { *baseError code int } func newCodeError(err error, code int) *codeError { return &codeError{ baseError: cause(err), code: code, } } func (e *codeError) Code() int { return e.code } func (e *codeError) Trace() string { return "" } func (e *codeError) Is(err erro...
/* MIT License Copyright (c) 2018 IBM 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 without limitation the rights to use, copy, modify, merge, publish, distribute...
package errors import ( "bytes" "errors" "fmt" "runtime" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // WithCaller sets the position at which the error was formed. If this is // false, errors will be wrapped with no location information. var WithCaller = true // WithCallerVerbose just add...
package middlewares import ( "github.com/go-playground/validator/v10" "github.com/labstack/echo/v4" "net/http" ) type CustomValidator struct { Validator *validator.Validate } func (cv CustomValidator) Validate(i interface{}) error { //if err := cv.Validator.Struct(i); err != nil { // return echo.NewHTTPError(h...
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) { for k, v := range r.Header { w.Write([]byte(fmt.Sprintf("%s = %s\n", k, v))) } w.Write([]byte(fmt.Sprintf("RemoteAddr = %s\n", r.RemoteAddr))) w.WriteHeader(http.StatusOK) ...
package main import ( "bufio" "flag" "fmt" "os" "strings" "github.com/zippy/internal/parser" "github.com/zippy/pkg/store" ) func main() { path := flag.String("path", "./log", "path of the zippy store to open") flag.Parse() store.Open(*path) fmt.Println("Welcome to zippy!") scanner := bufio.NewScanner(os...
package factogo import ( "errors" "fmt" "reflect" "time" ) /* Design ends the process to design a new Factory instance. When a Factory instance is designed then it is registered and can be produced calling the method Produce(). Example: Factory("staff").Design(&Staff{}) // Design the Factory Instance Factory(...
package marky_test import ( "github.com/serkansipahi/marky" "io/ioutil" "testing" ) func TestNewMarkdown(t *testing.T) { markdownTemplate, _ := ioutil.ReadFile("./markdown_test.md") expectedHeaders, _ := ioutil.ReadFile("./markdown_test_expected.txt") markdown := marky.NewMarkdown(string(markdownTemplate)) c...