text
stringlengths
11
4.05M
package auth import ( "errors" "github.com/dgrijalva/jwt-go" "os" ) var authSecret string func SetAuthSecret(secret string) error { // set auth secret if provided as arg if secret != "" && authSecret == "" { authSecret = secret } // fallback to env variable if authSecret == "" { authSecret = os.Getenv("A...
// 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 dbusutil provides additional functionality on top of the godbus/dbus package. package dbusutil import ( "context" "fmt" "github.com/godbus/dbus/v5" "chromiu...
package odoo import ( "fmt" ) // BaseImportTestsModelsM2ORequiredRelated represents base_import.tests.models.m2o.required.related model. type BaseImportTestsModelsM2ORequiredRelated struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` CreateDate *Time `xmlrpc:"create_date,omptempty"` CreateUid ...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "time" "github.com/dgrijalva/jwt-go" "github.com/gorilla/mux" "github.com/joho/godotenv" ) type User struct { ID int64 `json:"id"` Username string `json:"username"` Password string `json:"password"` ...
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2020 Datadog, Inc. package common import ( "errors" "fmt" "strings" commonv1 "github.com/...
package queues import ( "bufio" "fmt" "io" "strconv" "strings" ) func main(r io.Reader) { // Reads from STDIN // First line is number of actions var actions int scanner := bufio.NewScanner(r) scanner.Scan() actions, _ = strconv.Atoi(scanner.Text()) var stack1, stack2 []string for i := 0; i < actions; i+...
package cmd import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" "io/ioutil" "log" ) func Secret() ([]byte, error) { key := make([]byte, 16) if _, err := rand.Read(key); err != nil { return nil, err } err := ioutil.WriteFile("key.key", key, 0644) if err != nil { log.Fatal(...
package main import ( "fmt" "github.com/galaco/KeyValues" "github.com/galaco/lambda-client/behaviour" "github.com/galaco/lambda-client/behaviour/controllers" "github.com/galaco/lambda-client/engine" "github.com/galaco/lambda-client/event" "github.com/galaco/lambda-client/input" "github.com/galaco/lambda-client...
// 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 bluez import ( "context" "github.com/godbus/dbus/v5" "chromiumos/tast/errors" "chromiumos/tast/local/dbusutil" ) // Capabilities is the SupportedCapabilities ...
// https://developer.apple.com/documentation/appstoreconnectapi package apple import ( "crypto/ecdsa" "crypto/x509" "encoding/json" "encoding/pem" "errors" "fmt" "github.com/dgrijalva/jwt-go" "github.com/valyala/fasthttp" "time" ) type Authorize struct { P8 string Iss string Kid string } type Links str...
package main import "time" func main() { for { println("Hello World") time.Sleep(500 * time.Millisecond) } }
package cache import ( "testing" "github.com/stretchr/testify/assert" "github.com/honeycombio/samproxy/logger" "github.com/honeycombio/samproxy/metrics" "github.com/honeycombio/samproxy/types" ) // TestCacheSetGet sets a value then fetches it back func TestCacheSetGet(t *testing.T) { s := &metrics.MockMetrics...
package main import ( "encoding/json" "fmt" "io/ioutil" ) type Book struct { Id string `json:"id"` Title string `json:"title"` Author string `json:"author"` Price string `json:"price"` ImageUrl string `json:"image_url"` } type Message struct { Msg string } func panicError(err error) { if err...
// Copyright 2014 Matthias Zenger. 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 appl...
package main import "fmt" type Test struct { x int y int } func main() { var a interface{} t := Test{3, 4} //空接口可以赋值任意类型 a = t fmt.Println("a=", a) b := Test{} //类型断言,人为认定a是Test结构体 // b = a.(Test) //带判断的类型断言 b,ok:=a.(Test) if ok { fmt.Println("Ok!") }else { fmt.Println("not ok") } fmt.Println...
package splunk import "time" const ( // SplunkTimeFormat is the time format splunk expects from time parameters SplunkTimeFormat = "2006-01-02T15:04:05.000-07:00" ) // FormatTime Will format a time correct to be sent as a parameter func FormatTime(time time.Time) string { return time.UTC().Format(SplunkTimeFormat...
package main import "errors" //简单的二分查找实现,存在返回数组中的下标,不存在返回错误 func BinarySearch(array []int32, n int32, value int32) (int32, error) { low := int32(0) high := n - 1 for high >= low { //mid := (low + high) / 2//可能会溢出 //mid := low + (high-low)/2 mid := low + ((high - low) >> 1) if array[mid] > value { high =...
package main import "fmt" import "sync" func main() { page := 1 wg := &sync.WaitGroup{} //ch := make(chan int, 2) // var err1 error = nil // var err2 error = nil var str1 string = "" var str2 string = "" a := make([]int, 0) ch1 := make(chan int, 1) ch2 := make(chan int, 1) if page == 1 { wg.Add(1) go...
package v0 import ( "bytes" "context" "io" "math/rand" "testing" "github.com/grafana/tempo/tempodb/backend" "github.com/grafana/tempo/tempodb/encoding/common" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDataReader(t *testing.T) { tests := []struct { readerBytes ...
package main import ( "flag" "log" "os" "os/signal" "syscall" "github.com/NotSoFancyName/SimpleWebServer/server" ) var port = flag.Int("p", 8081, "listen port number") func main() { done := make(chan os.Signal, 1) signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) errs := make(chan error) ...
// Package errors defines all the single use as well as reusable errors within preflight package errors import "errors" var ErrNoChecksEnabled = errors.New("no checks have been enabled") var ErrRequestedCheckNotFound = errors.New("requested check not found") var ErrRequestedFormatterNotFound = errors.New("requested f...
package gorm2 import ( "context" "errors" "fmt" "github.com/google/uuid" "github.com/traPtitech/trap-collection-server/src/domain/values" "github.com/traPtitech/trap-collection-server/src/repository" "github.com/traPtitech/trap-collection-server/src/repository/gorm2/migrate" "gorm.io/gorm" ) const ( gameMan...
// Copyright (c) 2018 The MATRIX Authors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php package slash import ( "encoding/json" "fmt" "math/big" "testing" "github.com/MatrixAINetwork/go-matrix/mandb" "github.com/MatrixAIN...
package main // Leetcode 152. (medium) func maxProduct(nums []int) int { if len(nums) == 1 { return nums[0] } dp_max := make([]int, len(nums)) dp_min := make([]int, len(nums)) dp_max[0], dp_min[0] = nums[0], nums[0] res := nums[0] for i := 1; i < len(nums); i++ { preMax, preMin := dp_max[i-1], dp_min[i-1] ...
package main import ( "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws...
package statsdclient const VERSION = "1.1.2"
/* ПРИЛОЖЕНИЕ: _________________________________________________________________________________________________________ 1) Определяем переменные: exceptionStringFromNumbers – текст ошибки для вывода в консоль. Ситуация: строка состоит только из чисел; exceptionEmptyString – текст ошибки для вывода в консоль. Ситуация:...
package sort import ( "fmt" "strings" ) type Comparable interface { Compare(interface{}, interface{}) int } type IntComparable struct { } func (i IntComparable) Compare(a interface{}, b interface{}) int { ia, ok := a.(int) if !ok { panic(fmt.Sprintf("data %v is not a int.", a)) } ib, ok := b.(int) if !ok {...
package main import ( "bufio" "database/sql" "fmt" "log" "os" "strings" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test") if err != nil { log.Fatal(err) } defer db.Close() b, err := os.Open("C:/Users/Mehdi/Desktop/test.txt") if err != ni...
package metrics import ( "encoding/json" "net/url" "os/exec" "github.com/cerana/cerana/acomm" "github.com/cerana/cerana/pkg/errors" ) // Hardware returns information about the hardware. func (m *Metrics) Hardware(req *acomm.Request) (interface{}, *url.URL, error) { // Note: json output from lshw is broken when...
package table import "testing" func TestNewTable(t *testing.T) { _ = new(Table) }
package data import ( "time" "gopkg.in/mgo.v2/bson" ) type GreyHost struct { Id bson.ObjectId `bson:"_id"` CreatedBy string Hostname string CreatedAt time.Time IsActive bool } type GreyMail struct { Id bson.ObjectId `bson:"_id"` CreatedBy string Type string Email strin...
package logger_test import ( "bytes" "context" "fmt" "github.com/adamluzsi/frameless/pkg/logger" "github.com/adamluzsi/frameless/pkg/teardown" "github.com/adamluzsi/testcase/assert" "github.com/adamluzsi/testcase/random" "strings" "testing" ) func ExampleStub() { var tb testing.TB buf := logger.Stub(tb) //...
package services import ( "context" "fmt" "sync" "time" "github.com/everywan/identifier" ) /* * * 1 42 52 64 * +-----------------------------------------------+------------+---------------+ * | timestamp(ms) | wo...
package commands import ( "fmt" cmdConfig "github.com/SebastianJ/elrond-cli/config/cmd" "github.com/SebastianJ/elrond-sdk/api" "github.com/pkg/errors" "github.com/spf13/cobra" ) var ( includeAddress bool includeNonce bool addresses []string ) func init() { cmdBalance := &cobra.Command{ Use: "bal...
package main import "fmt" func SliceCap() { var arr [10]int var slice = arr[5:6] fmt.Printf("cap slice=%d\n", cap(slice)) fmt.Printf("len slice=%d\n", len(slice)) } func main() { //SliceCap() Sliceprint() } func SliceRise(s []int) { s = append(s, 0) for i := range s { s[i]++ } } func Sliceprint() { s1 ...
package cryptor import ( "reflect" "testing" "time" ) func TestSame(t *testing.T) { a, err := NewAESGCM(make([]byte, 32)) if err != nil { t.Errorf("a err %v", err) return } time.Sleep(50 * time.Millisecond) b, err := NewAESGCM(make([]byte, 32)) if err != nil { t.Errorf("b err") return } enc, _ :=...
package redisearch import ( "fmt" "github.com/gomodule/redigo/redis" "log" "reflect" ) // Projection type Projection struct { Expression string Alias string } func NewProjection(expression string, alias string) *Projection { return &Projection{ Expression: expression, Alias: alias, } } func (p...
package config import ( "context" "fmt" "os" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/viper" "github.com/hellofresh/github-cli/pkg/log" ) type ( configKeyType int // Spec represents the global app configuration Spec struct { Github Github GithubTestOrg Github } // Github r...
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // //go:build e2e // +build e2e package cluster import ( "github.com/mattermost/mattermost-cloud/e2e/workflow" ) func clusterLifecycleSteps(clusterSuite *workflow.ClusterSuite, installationSuite *workflo...
package utils import ( "fmt" ) func PrintHello() { fmt.Println("Utils Print Hello!") }
package msgproc import ( "net/source/proto/defs" ) /*---------------------------控制域---------------------------------- 机房id 服务器id 时间戳 加密类型编号 协议控制类型编号 业务领域编号 业务协议体长度 <协议体可扩展> ------------------------------------------------------------------------------------ **/ //数据的上层体现,按照实际情 type BaseMsg struct { MsgId int...
package main import "golang.org/x/tour/pic" func Pic(dx, dy int) [][]uint8 { z := make([][]uint8, dy) for i := 0; i < dy; i++ { x_vals := make([]uint8, dx) for j := 0; j < dx; j++ { x_vals[j] = uint8(i*j) } z[i] = x_vals } return z } func main() { pic.Show(Pic) }
package secret import ( "errors" "fmt" "text/tabwriter" "github.com/appcelerator/amp/api/rpc/secret" "github.com/appcelerator/amp/cli" "github.com/spf13/cobra" "golang.org/x/net/context" "google.golang.org/grpc/status" ) type ListOpts struct { Filters []string Format string Quiet bool } var listOpts =...
// Copyright (C)2018 by Lei Peng <pyp126@gmail.com> // // 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,...
package handlePost import ( "fmt" "github.com/gin-gonic/gin" "net/http" "sinfor/class" "sinfor/db" "sinfor/mode" "sinfor/token" "strconv" ) //分页查询 func ReturnPage(c *gin.Context) { tokenStr := c.Request.Header.Get("token") claims, _ := token.VerifyToken(tokenStr) if claims.Code[:3] == "010" { var pageInf...
// 调用gdi32.dll中接口获取屏幕图像 // 参考http://stackoverflow.com/questions/3291167/how-to-make-screen-screenshot-with-win32-in-c // http://stackoverflow.com/questions/5069104/fastest-method-of-screen-capturing // https://github.com/lxn/win/blob/master/gdi32.go package main import ( "io/ioutil" "log" "syscall" "unsafe" ) ty...
package oidc import ( "context" "net/http" http_utils "github.com/caos/zitadel/internal/api/http" ) type key int var ( userAgentKey key ) func UserAgentIDFromCtx(ctx context.Context) (string, bool) { userAgentID, ok := ctx.Value(userAgentKey).(string) return userAgentID, ok } func UserAgentCookieHandler(coo...
package openrtb_ext import ( "fmt" "github.com/prebid/openrtb/v19/openrtb2" ) func ConvertUpTo26(r *RequestWrapper) error { if err := convertUpEnsureExt(r); err != nil { return err } // schain moveSupplyChainFrom24To25(r) moveSupplyChainFrom25To26(r) // gdpr moveGDPRFrom25To26(r) moveConsentFrom25To26(...
package abelana import ( "context" "net/url" ) // Target describes a target service. type Target struct { // Service is the name of the target service. Service string // URL is the endpoint the service listens on. URL *url.URL } // WithTarget adds the current Targer to the context.Context. func WithTarget(ctx...
// Copyright (c) 2016-2019 Uber Technologies, 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...
package main //library member (person) type Member struct { ID int64 Name string Email string } //category of book type BookCategory struct { ID int64 Name string } //book (not actual book, but the unique representation with unique ISBN number). //library can have many copies of the same book. type Book s...
package wxpay import ( "errors" ) var ( // ErrNotEqualStruct ... ErrNotEqualStruct = errors.New("参数不是Struct类型") ) // Parameter 参数 type Parameter map[string]interface{}
package main import "fmt" func main() { var a, b int fmt.Scan(&a) fmt.Scan(&b) sum := 0 for ; a <= b; { sum += a a++ } fmt.Println(sum) } // Требуется написать программу, при выполнении которой с клавиатуры считываются два натуральных числа A и B // (каждое не более 100, A < B). Вывести сумму всех чисел ...
// 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 glbench import ( "context" "path/filepath" "chromiumos/tast/common/testexec" "chromiumos/tast/errors" "chromiumos/tast/shutil" ) // CrosConfig is the config t...
// Copyright 2019 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 models import ( "github.com/LiveSocket/bot/service" ) // Admin Represents a Admin user type Admin struct { Username string `db:"username" json:"username"` Notes string `db:"notes" json:"notes"` } const getAdmin = "SELECT * FROM `admin` WHERE `username`=?" // GetAdmin Finds an admin from the database f...
// 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 metal import ( "fmt" M "github.com/ionous/sashimi/compiler/model" "github.com/ionous/sashimi/meta" "github.com/ionous/sashimi/util/ident" ) // returned by object/relation array b/c we cant mutate individual values type objectReadValue struct { panicValue currentVal ident.Id } func (p objectReadValue) G...
package gochat import ( "encoding/json" "log" "github.com/micro/go-micro/broker" ) type Hub struct { service string broker broker.Broker clients map[*Conn]bool } func NewHub(service string, broker broker.Broker) *Hub { return &Hub{ service: service, broker: broker, clients: make(map[*Conn]bool), } }...
package mesos_master import ( "encoding/json" "errors" "fmt" "github.com/kelseyhightower/envconfig" "github.com/wndhydrnt/proxym/log" "github.com/wndhydrnt/proxym/manager" "github.com/wndhydrnt/proxym/types" "github.com/wndhydrnt/proxym/utils" "io/ioutil" "math/rand" "net/http" "strconv" "strings" "sync"...
package imgd import ( "flag" "time" cache_config "github.com/minotar/imgd/pkg/cache/util/config" "github.com/minotar/imgd/pkg/mcclient" "github.com/minotar/imgd/pkg/processd" "github.com/minotar/imgd/pkg/skind" "github.com/minotar/imgd/pkg/util/log" "github.com/minotar/imgd/pkg/util/route_helpers" "github.c...
package api import ( "Backend/server" ) type API struct { srv *server.Server } func Init(srv *server.Server) { api := API{ srv: srv, } // GET Methods srv.API("GET", "/api/hostname/{hostname}", ChangeHostname) srv.API("GET", "/api/ws/{host}", api.Websocket) // POST Methods srv.API("POST", "/api/save", Sav...
package handler import ( "encoding/json" "log" "net/http" "github.com/google/uuid" "20dojo-online/pkg/http/response" "20dojo-online/pkg/server/model" ) // HandleUserCreate ユーザ情報作成処理 func HandleUserCreate() http.HandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { // リクエストBodyから更新...
// 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 firmwareupdateapp contains drivers for controlling the ui of // firmware update SWA. package firmwareupdateapp import ( "context" "time" "chromiumos/tast/erro...
// Copyright 2021 Comcast Cable Communications Management, LLC // // 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 ...
package orm import ( "database/sql" "fmt" "os" "sync" ) const defaultMaxIdle = 30 type DriverType int const ( _ DriverType = iota DR_MySQL DR_Sqlite DR_Oracle DR_Postgres ) type driver string func (d driver) Type() DriverType { a, _ := dataBaseCache.get(string(d)) return a.Driver } func (d driver) Nam...
// Copyright 2019 Liquidata, 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 coin_gecko import ( "encoding/json" "errors" "fmt" "github.com/eager7/elog" "github.com/BlockABC/eth-tokens/script/built" "github.com/ethereum/go-ethereum/common" "io/ioutil" "net/http" "net/url" ) var log = elog.NewLogger("gecko", elog.DebugLevel) const urlGecko = "https://api.coingecko.com/api/v3/...
package db import ( "context" "flag" "github.com/spotlightpa/almanack/pkg/almlog" ) func FlagFromOption(ctx context.Context, q *Queries, fl *flag.FlagSet, name string) error { l := almlog.FromContext(ctx) needsVal := true fl.Visit(func(f *flag.Flag) { if f.Name == name { needsVal = false } }) if !need...
package linqo import ( "bytes" ) type CreateOption string const ( IfNotExists CreateOption = "IF NOT EXISTS" ) type CommitOption string const ( OnCommitDelete CommitOption = "DELETE ROWS" OnCommitDrop CommitOption = "DROP" OnCommitPreserve CommitOption = "PRESERVE ROWS" ) type CommitOptions interface {...
package hangouts // NewMessage message with builder functions func NewMessage() *Message { return &Message{} } // WithText adds text to function func (m *Message) WithText(t string) *Message { m.Text = t return m } // WithSender adds a User to Message func (m *Message) WithSender(u User) *Message { m.Sender = u ...
package parser var SelectSQLs []string var SelectQueries []string func init() { SelectSQLs = append(SelectSQLs, "select id, 'name' "+ "from users where 'name' in ('joe', 'juice')") SelectSQLs = append(SelectSQLs, "select posts.*, users.name "+ "from posts left join users on users.id = posts.users_id") Select...
// 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 signinutil provides functions that help with management of sign-in restrictions package signinutil import ( "context" "strings" "chromiumos/tast/errors" "chr...
package main import ( "testing" ) func TestBencodeDecodeResponseMessage(t *testing.T) { evalResponse := "d2:id4:hurl2:ns9:boot.user7:session36:112830d1-8a29-4f55-88e9-6e7e735044c75:value17:#'boot.user/sevened2:id4:hurl7:session36:112830d1-8a29-4f55-88e9-6e7e735044c76:statusl4:doneee" output := BencodeUnmarshal(ev...
package main // Leetcode 136. (easy) func singleNumber1(nums []int) int { res := 0 for _, num := range nums { res ^= num } return res } // Leetcode 137. (medium) func singleNumber2(nums []int) int { ones := 0 twos := 0 threes := 0 for _, num := range nums { twos |= ones & num ones ^= num threes = ones...
package ravendb var _ IMoreLikeThisOperations = &MoreLikeThisBuilder{} var _ IMoreLikeThisBuilderForDocumentQuery = &MoreLikeThisBuilder{} var _ IMoreLikeThisBuilderBase = &MoreLikeThisBuilder{} type MoreLikeThisBuilder struct { moreLikeThis MoreLikeThisBase } func NewMoreLikeThisBuilder() *MoreLikeThisBuilder { r...
// Copyright (C) 2023 Storj Labs, Inc. // See LICENSE for copying information. //go:build race // +build race package leak import ( "context" "testing" "github.com/stretchr/testify/require" ) func TestRef_Ok(t *testing.T) { root := Root(0) child1 := root.Child("alpha", 0) child2 := root.Child("beta", 0) req...
//go:generate mockgen -destination mock/symlink.go . SymlinkHandler package handlers import ( "context" "github.com/k0kubun/pp" "github.com/raba-jp/primus/pkg/cli/ui" "github.com/spf13/afero" "go.uber.org/zap" "golang.org/x/xerrors" ) type SymlinkParams struct { Src string Dest string User string } func ...
package internal import ( "encoding/json" "fmt" "net/http" "sort" "github.com/tyrannosaurus-becks/vault-explorer/website" ) func NewApplication() (*App, error) { config, err := ParseConfig() if err != nil { return nil, err } app := &App{ Config:config, VaultClient: NewVaultClient(config.VaultToken, co...
package twitchbot import "fmt" type chatCommandParameter struct { name string required bool pattern string } func (p *chatCommandParameter) String() string { requiredIndicator := "" if !p.required { requiredIndicator = "?" } return fmt.Sprintf("<%s%s>", p.name, requiredIndicator) } func (p *chatComma...
package controller import ( "context" "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "reflect" "strings" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-github/v32/github" ) func TestHandleStatus(t *testing.T) { ctx := context.Background() for _, tc := range []struct { nameA...
package hanu import ( "github.com/ChrisMcKee/allot" ) // Handler is the interface for the handler function type Handler func(Convo) // CommandInterface defines a command interface type CommandInterface interface { Get() allot.CommandInterface Description() string Handle(conv ConversationInterface) } // Command ...
package log import ( "fmt" "os" "path/filepath" "sync" ) type segment struct { file *os.File firstOffset uint64 index *index mu sync.RWMutex nextOffset uint64 dir string position uint64 } func (s *segment) Write(p []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() ...
package regression import ( "testing" ) func Test(t *testing.T) { var r Regression //r.Debug = true r.SetObservedName("Distance") r.SetVarName(0, "Weight") r.SetVarName(1, "Height") r.SetVarName(2, "Blood sugar") r.AddDataPoint(DataPoint{Observed : 98, Variables : []float64{483, 343, 0.0386}...
package main import ( "fmt" "io" "log" "os" "strings" "time" ) func check(e error) { if e != nil { panic(e) } } func main() { const BufferSize = 1000 file, err := os.Open("500kb.txt") check(err) defer file.Close() buffer := make([]byte, BufferSize) var overalTime float64 = 0 for i := 0; i < 100;...
package mempool import ( "../transaction" ) var Mempool = make(map[string]transaction.Transaction) func GetTransactions() []transaction.Transaction { var result []transaction.Transaction i := 0 for _, v := range Mempool { result = append(result, v) i++ delete(Mempool, v.TxHash) if i >= 10 { break ...
package quark import ( "bytes" "encoding/json" "io/ioutil" "os" "path/filepath" "strings" ) func handlerOf(v interface{}) Handler { switch h := v.(type) { case Handler: return h case func(*Context): return HandlerFunc(h) default: panic("Can't as handler") } } func handlersOf(vs []interface{}) []Hand...
package main import ( "fmt" "github.com/liming8519/grpc-demo/consul" "github.com/liming8519/grpc-demo/helloworld" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/balancer/roundrobin" "log" "time" ) func main() { callConsulGrpc() } func callConsulGrpc() { schema, err := consul...
package im import ( "net/http" "io" "net/url" "bytes" "time" "net" "io/ioutil" "os" "mime/multipart" "path/filepath" ) type Response struct { Err error // 请求错误 Data []byte // 请求返回的字节 StatusCode int Status string } type HttpRequest struct { connectTimeout time.Duration readWriteTim...
package main import ( "database/sql" "fmt" "net/url" "os" "github.com/coopernurse/gorp" ) // データソース文字列を変換 func convert_datasource(ds string) (result string) { url, _ := url.Parse(ds) result = fmt.Sprintf("%s@tcp(%s:3306)%s", url.User.String(), url.Host, url.Path) return } func initDb() *gorp.DbMap { var da...
package main import ( "fmt" "unsafe" ) func test() *int { // ok, x will escapes to heap x := 20 return &x } func test_value() int { x := 20 return x } func main() { p := test() v := test_value() fmt.Println(p, *p, v) d := struct { s string x int }{"abc", 10} // 指针运算 p1 := uintptr(unsafe.Pointer(&...
/* * Flow CLI * * Copyright 2019-2021 Dapper Labs, 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 appl...
package entities type User struct { Id string `firestore:"id"` FamilyName string `firestore:"familyName"` FirstName string `firestore:"firstName"` }
package config type Validator interface { Validate() error } type Config struct { Kafka kafka `mapstructure:"kafka"` Logger logger `mapstructure:"logger"` Nats nats `mapstructure:"nats"` Postgres postgres `mapstructure:"postgres"` } func Validate(validators ...Validator) (err error) { for _, ...
/* Copyright 2019 Red Hat 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, software di...
package main import ( "os" "github.com/codegangsta/cli" ) func main() { app := cli.NewApp() app.Name = "Gountries Creator" app.Commands = []cli.Command{ { Name: "create", Usage: "Generates all data based on the local files", Action: createFiles, }, { Name: "import", Usage: "Imports...
package v1alpha1 import ( "testing" "time" "github.com/stretchr/testify/require" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "github.com/tilt-dev/tilt/internal/k8s" "github.com/tilt-dev/tilt/internal/tiltfile/starkit" "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1" ) fun...
package config import "github.com/spf13/viper" // InitConfig - load config from config.yml func InitConfig() error { viper.AddConfigPath("./config") viper.SetConfigName("config") return viper.ReadInConfig() }
package persistent import ( "github.com/EventStore/EventStore-Client-Go/protos/persistent" "github.com/EventStore/EventStore-Client-Go/protos/shared" ) type DeleteOptions struct { StreamName []byte GroupName string } func deleteRequestStreamProto(options DeleteOptions) *persistent.DeleteReq { return &persisten...