text
stringlengths
11
4.05M
package roles // User represents a single user type User struct { ID uint Registry *Registry `json:"-"` rights []Right } // Check returns true if user has all of provided rights func (u *User) Check(rights ...Right) bool { return intersection(u.rights, rights) } // Guard stops process if user has not any ...
package main import "fmt" func main() { results := make([]string, 0) results = append(results, "111") results = append(results, "333") results = append(results, "222") results = append(results, "111") results = append(results, "444") results = append(results, "111") results = append(results, "333") mvKeys :=...
package main import ( "github.com/oceanho/gw/contrib/cmder/gwcli" "os" ) func main() { app := gwcli.App() app.Run(os.Args) }
package model type ConfigInfo struct { JavaHome string `json:"java_home"` ApkTool string `json:"apk_tool"` KeyStore string `json:"key_store"` StoreAlias string `json:"store_alias"` StorePwd string `json:"store_password"` }
// 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...
package sandbox import ( "github.com/regclient/regclient/regclient/types" lua "github.com/yuin/gopher-lua" ) func setupReference(s *Sandbox) { s.setupMod( luaReferenceName, map[string]lua.LGFunction{ "new": s.newReference, "__tostring": s.referenceString, }, map[string]map[string]lua.LGFunctio...
package kmgo import "net/http" import "net/url" func NewKM(key string) *KM { return &KM{api_key: key} } func (km KM) NewEvent(event string, person string, properties url.Values) *KMEvent { event_struct := KMEvent{km, person, event, properties, 0} return &event_struct } func (ev *KMEvent) SetTimestamp(time int) *...
package sanity import ( "github.com/go-gorp/gorp" "github.com/ovh/cds/sdk" ) // LoadAllWarnings loads all warnings existing in CDS func LoadAllWarnings(db gorp.SqlExecutor, al string) ([]sdk.Warning, error) { // TODO return nil, nil } // LoadUserWarnings loads all warnings related to Jobs user has access to fun...
package translated import "github.com/stephens2424/php/passes/togo/internal/phpctx" func Echo(ctx phpctx.PHPContext) { ctx.Echo.Write("test") }
package connector import ( "common" "logger" "rankclient" "rpc" ) const ( RANK_PROFIT = 1 RANK_COIN = 2 RANK_EXP = 3 ) const ( RANK_CNT = 50 ) func (cn *CNServer) GetRanking(conn rpc.RpcConn, msg rpc.ReqRankList) error { logger.Info("GetRanking called") p, exist := cn.getPlayerByConnId(conn.GetId()) ...
// 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 windowarrangementcuj import ( "context" "time" "chromiumos/tast/common/action" "chromiumos/tast/errors" "chromiumos/tast/local/chrome" "chromiumos/tast/local/...
package perfect import ( "errors" "math" ) // Classification structure type Classification string const ( ClassificationAbundant Classification = "ClassificationAbundant" ClassificationDeficient Classification = "ClassificationDeficient" ClassificationPerfect Classification = "ClassificationPerfect" ) var (...
// Package broker implementation from https://stackoverflow.com/a/49877632 package broker type Broker struct { stopCh chan struct{} publishCh chan interface{} subCh chan chan interface{} unsubCh chan chan interface{} } func New() *Broker { return &Broker{ stopCh: make(chan struct{}), publishCh: m...
// Copyright 2013, Bryan Matsuo. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // service.go [created: Sun, 18 Aug 2013] package main import ( "bytes" "crypto/sha1" "encoding/base64" "errors" "fmt" "io" "io/ioutil" "time" ) var E...
package main import ( "fmt" ) //declare a object type Rect struct { x, y float64 width, height float64 } //realize the func of the object func (r *Rect) Area() float64 { return r.width * r.height } // golang has no construct func // 对象的创建通常交由一个全局的创建函数 NewXXX 来命名 表示构造函数 func newRect(x, y, width, height flo...
package bus import ( "context" "time" "github.com/stretchr/testify/mock" ) type mockDriver struct { mock.Mock itd *internalDriver } func (m *mockDriver) CreateQueue(name string, delay time.Duration) error { err := m.Called(name, delay).Error(0) if err == nil { err = m.itd.CreateQueue(name, delay) } retur...
package requests import ( "encoding/json" "fmt" "net/url" "strings" "time" "github.com/google/go-querystring/query" "github.com/atomicjolt/canvasapi" "github.com/atomicjolt/string_utils" ) // SubmitAssignmentSections Make a submission for an assignment. You must be enrolled as a student in // the course/sec...
//pb-17 package main import( "fmt" "time" "strconv" "strings" ) var try = []map[string]int{ {"1": 3, "2": 3, "3": 5, "4": 4, "5": 4, "6": 3, "7": 5, "8": 5, "9": 4}, {"2": 6, "3": 6, "4": 5, "5": 5, "6": 5, "7": 7, "8": 6, "9": 6, "10": 3, "11": 6, "12": 6, "13": 8, "14": 8, "15": 7, "16": 7, "17": 9, "18"...
package main import ( "encoding/json" "fmt" ) type Preson struct { Name string `json:"name"` Age int `json:"age"` Gender string `json:"gender"` City []string `json:"city"` } func main() { p1 := &Preson{Name: "Sumeet", Age: 22, Gender: "Male", City: []string{"Chennai", "TN"}} data, _ := json....
package eventstore import ( "context" "fmt" "os" "github.com/machinebox/graphql" ) func sendRequest(ctx context.Context, req *graphql.Request, data interface{}) error { URL := os.Getenv("EVENT_STORE_URL") if URL == "" { return fmt.Errorf("Missing required environment variable EVENT_STORE_URL") } client :...
package csblob import ( "bytes" "crypto/x509" "encoding/asn1" "encoding/binary" ) type reqBuilder struct { out bytes.Buffer err error } func DefaultRequirement(identifier string, certs []*x509.Certificate) ([]byte, error) { leaf := certs[0] b := new(reqBuilder) b.putUint32(1) items := []func(){ b.identif...
package userModel import ( "hd-mall-ed/packages/common/database" "hd-mall-ed/packages/common/database/tableModel" ) type User tableModel.User // 创建用户 func (user *User) CreateUser() (err error) { err = database.DataBase.Create(&user).Error return } // 查找user func (user *User) FindUser() User { database.DataBase...
package reverse_words_in_a_string_iii func reverseWords(s string) string { arr := []byte(s) for i := 0; i < len(arr); { for i < len(arr) && arr[i] == ' ' { i++ } j := i + 1 for j < len(arr) && arr[j] != ' ' { j++ } reverseWord(arr[i:j]) i = j + 1 } return string(arr) } func reverseWord(ar...
package controllers import ( "encoding/json" "github.com/astaxie/beego" beeLogger "github.com/beego/bee/logger" "hello/business" ) type PayControllers struct { beego.Controller } func (pay *PayControllers) ActionFunc() { logger := beeLogger.Log action := pay.Ctx.Input.Param(":action") data := pay.Ctx.Input.R...
package debug import ( "os" "os/user" "path/filepath" "runtime/pprof" "strings" "github.com/cosmos/cosmos-sdk/server" "github.com/tendermint/tendermint/libs/log" ) // isCPUProfileConfigurationActivated checks if cpuprofile was configured via flag func isCPUProfileConfigurationActivated(ctx *server.Context) bo...
package sej import ( "reflect" "testing" ) func TestWriteFlush(t *testing.T) { tt := Test{t} path := newTestPath(t) messages := []string{"a", "bc"} w := newTestWriter(t, path) defer closeTestWriter(t, w) writeTestMessages(t, w, messages...) if err := w.Flush(); err != nil { t.Fatal(err) } tt.VerifyMess...
package main import ( "fmt" "strconv" "strings" "github.com/mit-dci/utreexo/utreexo" ) type TxoTTL struct { utreexo.Hash ExpiryBlock int32 } // plusLine reads in a line of text, generates a utxo leaf, and determines // if this is a leaf to remember or not. func plusLine(s string) ([]utreexo.LeafTXO, error) { ...
package paypal_fee_computer // import "src.techknowlogick.com/paypal-fee-computer" import ( "testing" ) func TestCompute(t *testing.T) { cases := []struct{ amount, percentage, fixed, want float64 }{ {0.01, 2.9, 0.3, 0.32 }, {0.1, 2.9, 0.3, 0.41 }, {1.0, 2.9, 0.3, 1.34 }, {10.0, 2.9, 0.3, 10.61 }, {25.0, ...
// Copyright 2016 Albert Nigmatzianov. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package ui import ( "bufio" "fmt" "os" "strings" "time" colorable "github.com/mattn/go-colorable" ) var Output = colorable.NewColorableStdout() f...
package server import ( "context" "encoding/json" "fmt" "net/http" "github.com/go-chi/chi" "github.com/meso-org/meso/repository" "github.com/meso-org/meso/workers" ) type workerHandler struct { s workers.Service } func (h *workerHandler) router() chi.Router { r := chi.NewRouter() r.Route("/worker", func(...
package _4_Chain_of_Responsibility_Pattern //步骤 1 //创建抽象的记录器类。 const ( INFO = 1 DEBUG = 2 ERROR = 3 ) type AbstractLogger interface { logMessage(int, string) string } //步骤 2 //创建扩展了该记录器类的实体类。 type ConsoleLogger struct { nextLogger AbstractLogger level int } func (receiver *ConsoleLogger) logMessage(leve...
// 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 matchs import ( "sync" "testing" ) func TestNewAcMatcher(t *testing.T) { w := []string{ "a", "b", } m := NewAcMatcher(w) c := []string{ "aaa", "bbb", "aabab", "vc", "ccsad", "aasd", } r := make([]interface{}, len(c)) wg := sync.WaitGroup{} for i := range c { wg.Add(1) go func(i int) { def...
package cmd import ( "os" "time" "github.com/0xTanvir/pp/contest" "github.com/0xTanvir/pp/db" "github.com/0xTanvir/pp/home" "github.com/0xTanvir/pp/server" "github.com/0xTanvir/pp/users" "github.com/gin-gonic/contrib/ginrus" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "github.com/spf13/cobra" ...
package book import ( "github.com/gofiber/fiber" )
package main import ( "fmt" "grpc_api/api" "grpc_api/database" "grpc_api/proto" "log" "net" "google.golang.org/grpc" ) func main() { fmt.Println("running grpc server on port 7777") lis, err := net.Listen("tcp", fmt.Sprintf(":%d", 7777)) if err != nil { log.Fatalf("failed to listen: %v", err) } s := a...
// Copyright 2023 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...
package gowhere import ( "fmt" ) // RuleSet holds a group of Rules to be applied together type RuleSet struct { rules []Rule } func (rs *RuleSet) firstMatch(target string, verbose bool) *Match { if verbose { fmt.Printf("\nfirstMatch '%s'\n", target) } for _, r := range rs.rules { if verbose { fmt.Printf...
package email_test import ( "os" "strconv" "testing" "github.com/mylxsw/adanos-alert/pkg/messager/email" "github.com/stretchr/testify/assert" ) func TestEmailSend(t *testing.T) { host := os.Getenv("EMAIL_HOST") port := os.Getenv("EMAIL_PORT") user := os.Getenv("EMAIL_USER") password := os.Getenv("EMAIL_PASS...
package hub import ( "github.com/exitcodezero/picloud/message" "github.com/pborman/uuid" "time" ) // Connection maintains info about the connected device // and subscribed events type Connection struct { ID string ClientName string IPAddress string ConnectedAt time.Time Subscribed []string Out ...
package usecases import ( "context" "errors" "github.com/landistas/badulaque/pkg/entities" ) type ProductUseCase interface { CreateProduct(ctx context.Context, product entities.Product) (*entities.Product, error) GetProduct(ctx context.Context, productID string) (*entities.Product, error) } type ProductStorage...
// 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 wifipeer builds and controls peer ChromeOS devices for Wi-Fi tests. package wifipeer import ( "context" "chromiumos/tast/dut" "chromiumos/tast/errors" "chrom...
package main import ( "fmt" "strconv" ) // Unlike in C, in Go assignment between items of // different type requires an explicit conversion. func main() { var a int = 65 // The expression T(v) converts the value v to the type T. b := string(a) // Itoa is equivalent to FormatInt(int64(i), 10). c := strconv.I...
// Difficult: Medium // Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) // Output: 7 -> 0 -> 8 // Explanation: 342 + 465 = 807. package main import "fmt" // ListNode is a struct for linked List type ListNode struct { Val int Next *ListNode } func main() { item1 := &ListNode{2, nil} item2 := &ListNode{4, nil} item3 := &...
package modifiers import ( dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1" "github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/activegate/consts" "github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/activegate/internal/statefulset/builder" "github.com/Dynatrace...
// 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 wpaeap import ( "chromiumos/tast/common/crypto/certificate" "chromiumos/tast/common/wifi/security/eap" "chromiumos/tast/common/wifi/security/wpa" ) // Option is ...
package main import ( "fmt" ) func fact(n int) int { if n > 1 { return n * fact(n - 1) } return 1 } func play_with_array() { fmt.Println("### play_with_array ###") var a [3]int // all set to 0 fmt.Println(a) fmt.Printf("a[0] == %d\n", a[0]) fmt.Printf("len(a) == %d\n", len(a)) // Array literals a...
package simple import ( "fmt" ) // BasicPointer tbd func BasicPointer() { fmt.Println("\nBasicPointer") a := 42 fmt.Println(a) // address fmt.Println(&a) fmt.Printf("%T\n", a) fmt.Printf("%T\n", &a) b := &a fmt.Println(b) // value stored at an address fmt.Println(*b) fmt.Println(*&a) *b = 43 fmt.Pr...
package cmd import ( "context" "encoding/json" "fmt" "net/http" "net/http/httputil" "os" "os/signal" "syscall" "time" "github.com/gorilla/mux" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) var scheme, key, cert string var returnStatusCode, port int type responseYesSir struct { Message st...
package storage import ( "btcnetwork/common" "btcnetwork/p2p" "context" "encoding/binary" "encoding/hex" "errors" "github.com/syndtr/goleveldb/leveldb" "reflect" "sync" ) var ( LatestBlockKey = []byte("latestblock") ErrOphanBlock = errors.New("ophan block") ) type blockMgr struct { newBlock chan p...
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package main import ( "fmt" "strconv" "strings" "time" "github.com/gosuri/uilive" "github.com/mattermost/mattermost-cloud/model" "github.com/olekukonko/tablewriter" "github.com/pkg/errors" "git...
package dashboard import ( "net/http" "github.com/gorilla/mux" "services" "middleware/auth" "models" "controllers/viewmodels" "repository" "github.com/satori/go.uuid" "strconv" ) type CategoriesController struct { r *mux.Router s *services.CategoryService } func NewCategoriesController(r *mux.Router) *Ca...
package leetcode_go func reverseVowels(s string) string { res := []byte(s) for i, j := 0, len(s)-1; i < j; { for !isVowel(s[i]) { i++ } for !isVowel(s[j]) { j-- } res[i], res[j] = res[j], res[i] i++ j-- } return string(s) } func isVowel(c byte) bool { if c == 'a' || c == 'e' || c == 'i' || c ...
package main import ( "fmt" "net" "time" ) type Transaction struct { Conn *net.TCPConn Ctx interface{} Req InRequest Rsp OutRespose Time time.Time Err error ClientMsg string SvrMsg string } func NewTrans(c *net.TCPConn, ctx interface{}) *Transaction { t := new(Transac...
package dlstream import ( "errors" "io" "net" "syscall" ) // shouldRetryRequest analyzes a given request error and determines whether its a good idea to retry the request func shouldRetryRequest(err error) bool { if err == nil { return false } if errors.Is(err, io.ErrUnexpectedEOF) { return true } var ...
package main import ( "fmt" "log" "os" "strings" "github.com/codegangsta/cli" "github.com/libgit2/git2go" ) func main() { commands := []cli.Command{ { Name: "status", ShortName: "s", Usage: "./gobetween s", Description: "Get Status of current directories dependencies, based on gli...
package metrics import "fmt" const namespaceSeparator = "." type namespaced struct { namespace string adapted Metrics } // NewNamespaced returns the metrics with the metrics names with a namespace or prefix. func NewNamespaced(m Metrics, namespace string) Metrics { return &namespaced{namespace, m} } func (n *...
package usersync import ( "fmt" "sort" "strings" "github.com/prebid/prebid-server/config" ) type namedSyncerConfig struct { name string cfg config.Syncer } // SyncerBuildError represents an error with building a syncer. type SyncerBuildError struct { Bidder string SyncerKey string Err error } //...
package main import ( "strconv" "testing" ) func TestDigitsTwo(t *testing.T) { sum := FilterDigits(59) if sum != 14 { t.Error("Error on filtering digits ") } } func TestDigitsThree(t *testing.T) { sum := FilterDigits(111) if sum != 3 { t.Error("Error on filtering digits") } } // Checks whether the absol...
package main import ( "bufio" "github.com/thoj/go-ircevent" "log" "os" "regexp" "strings" ) var Icseh map [string] []string func stampaIcse (icsamelo string) []string { lines := []string{"", "", "", "", "", "", ""} for _, letter := range icsamelo { for idx, line := range Icseh...
package main import "fmt" type person struct { first string last string } type secretAgent struct { person license bool } // func (r receiver) identifier(parameter(s)) (return(s)) { ... } // All instances of secretAgent now have access to the speak method func (s secretAgent) speak() { fmt.Println("I am", s.f...
package isom import ( "bytes" "encoding/hex" "testing" ) func TestReadElemStreamDesc(t *testing.T) { debugReader = true debugWriter = true var err error data, _ := hex.DecodeString("03808080220002000480808014401500000000030d400000000005808080021210068080800102") t.Logf("elemDesc=%x", data) t.Logf("length=%...
package main import ( "fmt" "net/http" ) func cat(res http.ResponseWriter, req *http.Request) { fmt.Fprintf(res, "<h1>Handles %v</h1>\n%v\n", "/catOnly", req.URL.Path) } func dog(res http.ResponseWriter, req *http.Request) { fmt.Fprintf(res, "<h1>Handles %v</h1>\n%v\n", "/dog/", req.URL.Path) } func home(res ht...
/* Copyright 2022 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...
package main import ( "os" "text/template" ) func main() { repoRoot, _ := os.Getwd() dir := repoRoot + "/Chapter 2/Video 10" tpl, _ := template.ParseGlob(dir + "/onur.gohtml") tpl.Execute(os.Stdout, "Onur") }
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package v1alpha1 import ( "time" coreV1Api "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. // AdminConsoleSpec defines the des...
package blurhash import "math" func signPow(val, exp float64) float64 { sign := 1.0 if val < 0 { sign = -1 } return sign * math.Pow(math.Abs(val), exp) } func sRGBToLinear(val int) float64 { v := float64(val) / 255 if v <= 0.04045 { return v / 12.92 } return math.Pow((v+0.055)/1.055, 2.4) } func linearT...
package postgres import ( "github.com/google/uuid" "github.com/orbis-challenge/src/models" ) func (q DBQuery) SaveHolding(holding *models.Holding) (models.Holding, error) { _, err := q.Model(holding). Returning("*"). Insert() return *holding, err } func (q DBQuery) DeleteHoldingByID(id uuid.UUID) (err error...
package reserve import ( "github.com/yosisa/arec/command" "io" "log" "os" "os/signal" "syscall" "time" ) type RecorderItem interface { Info() *RecordInfo io.WriteCloser } type Engine struct { Scheduler *Scheduler reserved map[string]*RecordInfo } func NewEngine(gr, bs int) *Engine { e := new(Engine) e...
// 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 usecase import ( "github.com/jerolan/slack-poll/domain/port" "github.com/jerolan/slack-poll/domain/service" ) type UseCase struct { pollService service.PollService uuid port.UUIDPort } func NewUseCase(pS service.PollService, uuid port.UUIDPort) *UseCase { return &UseCase{ pollService: pS, uui...
package view import ( proj_model "github.com/caos/zitadel/internal/project/model" "github.com/caos/zitadel/internal/project/repository/view" "github.com/caos/zitadel/internal/project/repository/view/model" "github.com/caos/zitadel/internal/view/repository" ) const ( applicationTable = "management.applications" )...
// Copyright 2018 Saferwall. All rights reserved. // Use of this source code is governed by Apache v2 license // license that can be found in the LICENSE file. package drweb import ( "context" "fmt" "regexp" "strings" "time" multiav "github.com/saferwall/saferwall/internal/multiav" "github.com/saferwall/safer...
package helpers import ( "encoding/binary" "image" "image/color" "io" ) func ReadByte(r io.Reader) byte { b := make([]byte, 1) r.Read(b) return b[0] } func ReadInt(r io.Reader) int { b := make([]byte, 8) r.Read(b) i64, _ := binary.Varint(b) return int(i64) } func ReadInt64(r io.Reader) int64 { b := make...
package modules import ( "bytes" "context" "fmt" "io" "net/http" "sync/atomic" "time" "github.com/buguang01/Logger" "github.com/buguang01/bige/messages" "github.com/buguang01/util/threads" "golang.org/x/net/websocket" ) func WebSocketSetIpPort(ipPort string) options { return func(mod IModule) { mod.(*W...
/* Copyright 2015 All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
package q3 import ( "runtime" "testing" ) func BenchmarkGetPrimes(b *testing.B) { for i := 0; i < b.N; i++ { GetPrimes(1000) } } func TestMaxProcs(t *testing.T) { println(runtime.GOMAXPROCS(0)) }
// 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 ( "os" "testing" ) //test handler 't' func TestNewDeck(t *testing.T) { d := newDeck() if len(d) != 16 { t.Errorf("Expected the deck length to be 16, but got %v", len(d)) } if d[0] != "Ace of Spades" { t.Errorf("Expected the first card to be 'Ace of Spades', but got %v", d[0]) } if d[l...
package main import ( "encoding/gob" "log" "os" "github.com/diamondburned/cchat/repository" ) const output = "repository.gob" func main() { f, err := os.Create(output) if err != nil { log.Fatalln("Failed to create file:", err) } defer f.Close() if err := gob.NewEncoder(f).Encode(repository.Main); err !=...
package graphqlorm import ( "context" "fmt" "strings" "github.com/iancoleman/strcase" "github.com/jinzhu/inflection" "github.com/machinebox/graphql" ) // FetchResponse ... type FetchResponse struct { Result interface{} `json:"result"` } // GetEntityOptions ... type GetEntityOptions struct { Entity string ...
// @APIVersion 0.1.0 // @Title GR社区RESTful API // @Description 基于Beego API实现的GR社区API,使用依赖注入提供多个存储的支持 // @Contact tiannianshou@gmail.com // @TermsOfServiceUrl http://github.com/go-react // @License Apache 2.0 // @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html package routers import ( "github.com/astaxie/be...
package config import ( "encoding/json" "fmt" "os" ) func LoadSpec(cPath string) (spec *Spec, err error) { cf, err := os.Open(cPath) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("JSON specification file %s not found", cPath) } return nil, err } defer cf.Close() if err = json.NewDeco...
/* It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. */ package main import ( "reflect" "sort" ) // returns sorted list of digits of an argument...
package main import ( "fmt" "math/big" "os" "strings" "syscall" "github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/usbwallet" "github.com/ethereum/go-ethereum/common" ethcmn "github.com/ethereum/go-ethereum/common" ethtyp...
package odoo import ( "fmt" ) // IrFieldsConverter represents ir.fields.converter model. type IrFieldsConverter struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` DisplayName *String `xmlrpc:"display_name,omptempty"` Id *Int `xmlrpc:"id,omptempty"` } // IrFieldsConverters represents arra...
package gae import ( "github.com/ahmadmuzakki/gae/internal" "golang.org/x/net/context" "google.golang.org/appengine" ) func Namespace(ctx context.Context, ns string) (context.Context, error) { ctx = internal.WithNamespace(ctx, ns) return appengine.Namespace(ctx, ns) }
package user import ( "errors" uuid "github.com/satori/go.uuid" ) // ErrUserNotFound is returned when the user can't be found. var ErrDidNotComplete = errors.New("database operation did not complete") var ErrUserNotFound = errors.New("user not found") var ErrUserAlreadyExists = errors.New("user already exists") va...
package main import ( "os" "log" "fmt" "flag" "sort" "io/ioutil" "encoding/base64" "github.com/steakknife/hamming" ) type Key struct { length int hamming int } type Candidate struct { plaintext []byte score float64 key []byte length int } type Keys []Key type Candidates []Candidate func ...
package gooob import ( "net" "strconv" ) type OOBConnection struct { addr *net.UDPAddr password string } func newConnection(raddr *net.UDPAddr, password string) (*OOBConnection, error) { return &OOBConnection{raddr, password}, nil } func (conn *OOBConnection) Send(cmd string) (response string, err error) {...
// 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 main import ( "errors" "fmt" "os" "github.com/hlfstr/flagger" ) func main() { f := flagger.New() f.AddHelp("Show this help", "Testing Flags:") f.AddVersion("Show version", flagger.Info()) //Bool flag b := f.Bool("Test Bool", "-b", "--bool") //int flag i := f.Int(8, "Test Int", "-i", "--integer")...
package structures type Tone struct { Tonic PitchName ScoreFlatNum int ScoreSharpNum int } func NewTone(tonic PitchName) *Tone { tone := &Tone{Tonic: tonic} return tone } //func Tonic() String { // //} //func main() { // _ = NewTone(C) //}
package tests import ( "testing" "reflect" . "github.com/go-dash/slice/tests/types" "github.com/go-dash/slice/_string" "github.com/go-dash/slice/_int" "github.com/go-dash/slice/_Person" // github.com/go-dash/slice/tests/types ) var tableReverseString = []struct { input []string output []string }{ {nil, []st...
package roomserver import ( conn "centerclient" cmn "common" "logger" "rpc" "strconv" "sync" "time" ) const ( JieSanRoomName = "JieSanRoomName" ) type CustomRoom struct { //id int32 //ID owner string //房间的拥有者(当前的房主) creatingPlayer string //房间的创建者(扣他的房卡) //name string //名字 //pw...
package server import ( "encoding/json" "github.com/gorilla/mux" pet "goAPI/pkg" "net/http" ) type api struct { router http.Handler repository pet.PetRepository } type Server interface { Router() http.Handler } func New(repo pet.PetRepository) Server { a := &api{repository: repo} r := mux.NewRouter() ...
package main import ( "log" "net/http" "github.com/julienschmidt/httprouter" ) func main() { router := httprouter.New() router.POST("/calculate", Calculate) log.Fatal(http.ListenAndServe(":8989", router)) }
package main import ( "fmt" "testing" ) var f []float64 func init() { f = make([]float64, 5) } func TestInCircle(t *testing.T) { for k, v := range map[string]bool{ "Center: (2.12, -3.48); Radius: 17.22; Point: (16.21, -5)": true, "Center: (5.05, -11); Radius: 21.2; Point: (-31, -45)": false, "Cent...
package redis_test import ( "fmt" "math/rand" "os/exec" "strings" "testing" "time" "github.com/farzadrastegar/simple-cab/driver_location" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/spf13/viper" ) var port string var paramsReady bool var randSeed = time.Date(2019, 01, 01, 02, 00, 00,...