text
stringlengths
11
4.05M
package main import ( "fmt" ) func main() { a := 2 b := 14 operation := "*" doMath(operation, a, b) } // Sending the a and b parameters as interface type so it can handle both int and float. func doMath(operation string, a, b interface{}) { switch v1 := a.(type) { case int: switch operation { case "+": ...
// Package retryx helps to retry operations package retryx import ( "context" "time" "github.com/avast/retry-go" ) var ( // Attempts is the number of attempts Attempts uint = 4 // Delay is the base interval for exponential backoff Delay = 500 * time.Millisecond ) // Do retries fn for Attempts times using ex...
package proverb func Proverb(rhyme []string) []string { newProverb := []string{} for i:=0; i<len(rhyme)-1; i++ { newProverb = append(newProverb, "For want of a "+rhyme[i]+" the "+rhyme[i+1]+" was lost.") } newProverb = append(newProverb, "And all for the want of a " + rhyme[0]+".") return newProverb }
package utils import ( "errors" "fmt" "time" "github.com/astaxie/beego" bolt "github.com/coreos/bbolt" log "github.com/sirupsen/logrus" ) var ( Db *bolt.DB Mmap map[string]string err error ) const demo string = `[{ "id": 0, "index": [0], "label": "1", "children": [{ "id": 1, "index": [0, 0], ...
package redux import ( "fmt" "sort" "github.com/goadesign/goa/design" "github.com/goadesign/goa/dslengine" ) // NewReduxStoreDefinition returns an initialized // ReduxStoreDefinition. func NewReduxStoreDefinition() *ReduxStoreDefinition { m := &ReduxStoreDefinition{ Includes: make([]string,0), Actions: mak...
package queue import ( "openreplay/backend/pkg/redisstream" "openreplay/backend/pkg/queue/types" ) func NewConsumer(group string, topics []string, handler types.MessageHandler) types.Consumer { return redisstream.NewConsumer(group, topics, handler) } func NewProducer() types.Producer { return redisstream.NewProd...
package smoothfs import ( "bytes" "io" "log" "os" "path/filepath" ) // struct Block represents one block in a CachedFile. type Block struct { OnDisk bool Loaded bool bytes []byte } // A CachedFile connects a backing file with a local cache file and memory cache. // This allows files to be read in more sensi...
package invite_test import ( "net/http" "net/http/httptest" "testing" "time" "github.com/jrapoport/gothic/config" "github.com/jrapoport/gothic/hosts/rest" "github.com/jrapoport/gothic/hosts/rest/modules/invite" "github.com/jrapoport/gothic/jwt" "github.com/jrapoport/gothic/mail/template" "github.com/jrapopo...
// +build !clustered,!gcloud package storage import ( "fmt" "strings" "github.com/janelia-flyem/dvid/dvid" ) var manager managerT // managerT should be implemented for each type of storage implementation (local, clustered, gcloud) // and it should fulfill a storage.Manager interface. type managerT struct { set...
package main import "fmt" const a int = 30 const b float64 = 30.25 const c string = "Hello World" const ( d = 31 e = 31.25 f= "Hello" ) func main() { fmt.Println(a, b ,c) fmt.Printf("%T\n", a) fmt.Printf("%T\n", b) fmt.Printf("%T\n", c) fmt.Println(d, e, f) fmt.Printf("%T\n", d) ...
package data type ArtistTrackList []ArtistTrack type ArtistTrackList2 *[]ArtistTrack func (p ArtistTrackList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p ArtistTrackList) Len() int { return len(p) } func (p ArtistTrackList) Less(i, j int) bool { return len(p[i].Tracks) < len(p[j].Tracks) }
// Copyright 2014 Dirk Jablonowski. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Collection of subscriber for the Analog Out Bricklet. package analogout const ( function_set_voltage = uint8(1) function_get_voltage = uint8(2) functio...
package cloudformation // AWSCloudFrontDistribution_CustomErrorResponse AWS CloudFormation Resource (AWS::CloudFront::Distribution.CustomErrorResponse) // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-customerrorresponse.html type AWSCloudFrontDistribution_Cu...
package main import ( "fmt" "os" "github.com/unixpickle/gocube" "github.com/unixpickle/gocube/fmc" ) var thirdF2LCorner int = -1 func main() { sc, err := gocube.InputStickerCube() if err != nil { fmt.Println("Failed to read stickers:", err) os.Exit(1) } cc, err := sc.CubieCube() if err != nil { fmt.P...
// https://programmers.co.kr/learn/courses/30/lessons/12946 package main var result [][]int func p12946(n int) [][]int { result = [][]int{} hanoi(n, 1, 2, 3) return result } func hanoi(n int, a int, b int, c int) { if n > 0 { hanoi(n-1, a, c, b) result = append(result, []int{a, c}) hanoi(n-1, b, a, c) } ...
package model type Type int const ( Drought Type = iota Rain HeavyRain OptimalTemperature Unknown ) func (t Type) String() string { switch t { case Drought: return "Drought" case Rain: return "Rain" case HeavyRain: return "Heavy Rain" case OptimalTemperature: return "Optimal Temperature" case Unkn...
// 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 ui import ( "context" "net/http" "net/http/httptest" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/mediasession" "chromiumos/tast/local/input" ...
package netxmocks import ( "context" "crypto/tls" "net" ) // TLSHandshaker is a mockable TLS handshaker. type TLSHandshaker struct { MockHandshake func(ctx context.Context, conn net.Conn, config *tls.Config) ( net.Conn, tls.ConnectionState, error) } // Handshake calls MockHandshake. func (th *TLSHandshaker) Ha...
// 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 views import ( "log" "github.com/winded/tyomaa/frontend/js/models" "github.com/winded/tyomaa/frontend/js/views" "github.com/winded/tyomaa/frontend/js/util" "github.com/gopherjs/jquery" "github.com/winded/tyomaa/frontend/js/app" "github.com/winded/tyomaa/frontend/js/dom" "github.com/winded/tyomaa/fro...
package main import ( "fmt" "reflect" ) func main() { /*var num float64 = 1.097 fmt.Println("type ", reflect.TypeOf(num)) fmt.Println("type ", reflect.ValueOf(num))*/ user := new(User) user.Name = "zhangsan" user.Age = 120 user.Id = 10 GetFiledAndMethod(user) } func GetFiledAndMethod(input interface{}) { ...
package microservice import ( "fmt" "net/http" "strings" "github.com/dolittle/platform-api/pkg/platform" "github.com/dolittle/platform-api/pkg/utils" "github.com/gorilla/mux" ) func (s *service) handleBusinessMomentsAdaptor(responseWriter http.ResponseWriter, r *http.Request, inputBytes []byte, applicationInfo...
package cmd import ( "io/ioutil" "log" "net" "net/http" "os" "path/filepath" "github.com/asdine/storm" "github.com/hacdias/fileutils" filebrowser "github.com/lzjwlt/filebrowser-cos/lib" "github.com/lzjwlt/filebrowser-cos/lib/bolt" h "github.com/lzjwlt/filebrowser-cos/lib/http" "github.com/lzjwlt/filebrows...
package main import "github.com/dieulinh/go-gorm/rest" import "log" func main(){ log.Fatal(rest.RunAPI(":8081")) }
package main import ( "fmt" "io/ioutil" "log" "path/filepath" "sort" "strconv" "strings" ) func getLastHistory(baseDir string) (*history, []byte, error) { historiesBase := filepath.Join(baseDir, "histories") histories, err := getSortedHistories(historiesBase) // todo configurable if err != nil { return n...
package config // Rules to know who win the game var Rules = map[string]string{ "rock": "scissors", "paper": "rock", "scissors": "paper", } // GameOptions representes the available options to play var GameOptions = []string{"rock", "paper", "scissors"}
package main import "fmt" func main() { obj := Constructor() obj.Push(1) obj.Push(2) param_2 := obj.Pop() param_3 := obj.Peek() param_4 := obj.Empty() fmt.Println(param_2) fmt.Println(param_3) fmt.Println(param_4) } type MyQueue struct { stack []int } /** Initialize your data structure here. */ func Const...
package context import ( "state/state" ) type CarMovingContext struct { Cs state.CarState } func (cmc *CarMovingContext) SetState(cs state.CarState) { cmc.Cs = cs } func (cmc CarMovingContext) Action() { cmc.Cs.Action() }
package deltal import ( "fmt" "io" "io/ioutil" "os" ) // Decoder of delta-l files type Decoder struct { Stream io.ReadSeeker passhash []byte Checksum []byte UseChecksum bool Offset uint64 passOffset int last uint8 } // Init initializes the decoder instance func (d *Decoder) Init() ...
package main import ( "database/sql" "fmt" "github.com/gin-gonic/gin" _ "github.com/go-sql-driver/mysql" ) //Trainee Struct type Trainee struct { Id int `json:id` Name string `json:name` Batch string `json:batch` Salary int `json:salary` State string `json:state` } const ( //DBDriver name ...
package LeetCode import "fmt" func Code203() { l1 := InitSingleList([]int{1, 2, 6, 3, 4, 5, 6}) fmt.Println(removeElements(l1, 6)) } /** 删除链表中等于给定值 val 的所有节点。 示例: 输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5 */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next ...
package rpcx import ( "fmt" "github.com/gen-iot/std" "testing" ) type exampleStruct struct { Name string `json:"name"` Age int `json:"age"` Meta map[string]interface{} `json:"meta"` } func newExampleStruct() *exampleStruct { return &exampleStruct{ Name: "suzhen", Age: ...
package fondy_api import ( "bytes" "fmt" "net/url" "testing" ) func TestReadFinalResponseFromReader(t *testing.T) { var respBuffer bytes.Buffer fmt.Fprint(&respBuffer, `{"rrn": "", "masked_card": "444455XXXXXX1111", "sender_cell_phone": "", "response_status": "success", "sender_account": "", "fee": "", "rectoke...
package main // Not relevant to Go, but heres how the flux / react model works: // https://facebook.github.io/react/blog/2014/07/30/flux-actions-and-the-dispatcher.html // And heres some stuff about ajax http://api.jquery.com/jquery.ajax/ import ( "encoding/json" "fmt" "io/ioutil" "net/http" "text/template" ) /...
package img import ( "sync" ) func ParseImg(wg sync.WaitGroup) []string { for y := 0; y < 100; y++ { rowHex := make([]string, 0, 100) go func() { wg.Add(1) for x := 0; x < 10; x++ { rowHex = append(rowHex, x) } wg.Done() }() return rowHex } }
package utils import ( "fmt" "github.com/vbauerster/mpb/v5" "github.com/vbauerster/mpb/v5/decor" "io" "net/http" "os" "runtime" "strconv" "sync" ) type Resource struct { Filename string Url string } type Downloader struct { wg *sync.WaitGroup pool chan *Resource Concurrent int HttpC...
// 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 taskmanager import ( "context" "math/rand" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/local/chrome" "chromiumos/tast/local/ch...
package v2 import ( "bytes" "encoding/json" "io" "io/ioutil" "mime/multipart" "net/http/httptest" "net/url" "os" "testing" "github.com/RTradeLtd/Temporal/mocks" "github.com/RTradeLtd/config/v2" ) func Test_Routes_Swarm(t *testing.T) { // load configuration cfg, err := config.LoadConfig("../../testenv/co...
package main import "fmt" func main() { minStack := Constructor() minStack.Push(-2) fmt.Println(minStack.stack) minStack.Push(0) fmt.Println(minStack.stack) minStack.Push(-3) fmt.Println(minStack.stack) fmt.Println(minStack.GetMin()) minStack.Pop() fmt.Println(minStack.Top()) fmt.Println(minStack.GetMin())...
package tezos_test import ( "fmt" "testing" "github.com/ecadlabs/signatory/pkg/config" "github.com/ecadlabs/signatory/pkg/tezos" "github.com/stretchr/testify/require" ) func TestValidateMessage(t *testing.T) { type Case struct { Name string Message []byte Error error } cases := []Case{ Case{Nam...
package kubernetesdiscoverys import ( "time" "github.com/tilt-dev/tilt/internal/controllers/apicmp" "github.com/tilt-dev/tilt/internal/store" "github.com/tilt-dev/tilt/internal/store/k8sconv" "github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1" "github.com/tilt-dev/tilt/pkg/model" ) func HandleKubernetesDiscovery...
package review func BinarySearchRecursive(data []int, high int, low int, value int) bool { if low > high { return false } mid := low + (high-low)/2 if data[mid] == value { return true } else if data[mid] < value { // find in the upper band return BinarySearchRecursive(data, high, mid+1, value) } else if ...
// Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in complian...
package lib2 import ( "log" ) func init() { log.Println("Package lib2 is initialized") } func IntSum(args ...int) (sum int) { for i := 0; i < len(args); i++ { sum += args[i] } return }
package spider import ( "github.com/el10savio/GoCrawler/GoSupervisor/messageBus" "github.com/streadway/amqp" ) var ( // Instantiate a shared RabbitMQ channel // variable to be shared in the package channel *amqp.Channel ) func init() { // Connect to RabbitMQ connection, err := messageBus.Connect() if err != ...
package util import ( "context" "fmt" "log" "net/http" "strconv" "sync" "time" "github.com/heptiolabs/healthcheck" ) const defaultHealthCheckPort = 5335 type healthWatcher struct { handler healthcheck.Handler isAppReady bool isAppLive bool serverInstance *http.Server } var _healthWatche...
package dcpu16 func (cpu *Dcpu) processOperand(operand Word, isAddress bool) *Word { switch operand { case 0x0: return &cpu.A case 0x1: return &cpu.B case 0x2: return &cpu.C case 0x3: return &cpu.X case 0x4: return &cpu.Y case 0x5: return &cpu.Z case 0x6: return &cpu.I case 0x7: return &cpu.J ...
package main import ( log "github.com/Sirupsen/logrus" "os" ) func init() { // log.SetFormatter(log.TextFormatter) log.SetFormatter(&log.JSONFormatter{}) file, err := os.OpenFile("./debug.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666) if err == nil { log.SetOutput(file) } else { log.Info("Failed to log to...
package AzureDevopsClient import ( "encoding/json" "fmt" "net/url" "time" ) type AgentQueueList struct { Count int `json:"count"` List []AgentQueue `json:"value"` } type AgentQueue struct { Id int64 `json:"id"` Name string `json:"name"` Pool struct { Id int64 Scope string Name ...
package main import ( "encoding/json" "fmt" "time" ) const ( defaultWGDeviceMTU = 1420 defaultWGListenPort = 51820 ) // https://stackoverflow.com/questions/48050945/how-to-unmarshal-json-into-durations/54571600#54571600 type Duration struct { time.Duration } func (d Duration) MarshalJSON() ([]byte, error) { ...
// 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 fingerprint import ( "context" "strconv" "strings" "time" "chromiumos/tast/dut" "chromiumos/tast/errors" "chromiumos/tast/remote/firmware" "chromiumos/tast/...
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( "fmt" ) func findUnsortedSubarray(nums []int) int { if len(nums) == 0 || len(nums) == 1 { return 0 } // 1. start, end := 0, len(nums)-1 for start < end && nums[start] <= nums[start+1] { start++ } for start < end && nums[end-1] <= nums[end] { end-- } // 2. 在end和start之间的最大值和最小值 ...
package main import ( "fmt" ) func blah(stuff string) bool { return true } func main() { fmt.Println("hi") fmt.Println(blah("stuff")) fmt.Println(blah("otherstuff")) }
package config import ( "io/ioutil" "os" "path/filepath" "testing" "github.com/spf13/pflag" "github.com/spf13/viper" "github.com/stretchr/testify/assert" ) type fakeConfig struct { *Config Letter string Number int } func (cfg *fakeConfig) write() error { return Write(cfg) } func (cfg *fakeConfig) load(v...
package helper import ( "database/sql/driver" "fmt" //"strconv" "strings" "time" ) // JSONTime format json time field by myself type JSONTime struct { time.Time } // MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S func (t JSONTime) MarshalJSON() ([]byte, error) { //formatted := fmt.Sprintf("\...
package handler import ( "github.com/gin-gonic/gin" "net/http" "fmt" "github.com/cworsnup13/golang-gin/models" ) const dateFormat = "2006-01-02T15:04:05Z" func CalendarHandler(c *gin.Context) { c.Header("Content-Type", "application/json") val := c.PostForm("password") g := CheckPassword(val) if g == nil { ...
package dynamic_programming import "testing" //买卖股票的最佳时机 买入和卖出一支股票一次 func maxProfit1(prices []int) int { if len(prices) < 2 { return 0 } profit := 0 buy := prices[0] for i := 1; i < len(prices); i++ { //先看 买是否合适 if buy > prices[i] { buy = prices[i] } else if prices[i]-buy > profit { //利润必须要先买后卖 ...
package main import ( "JsGo/JsAliPay/alipay" "JsGo/JsHttp" "fmt" "io/ioutil" "log" "time" ) var ( appID = "2017082408349309" partnerID = "2088221180975634" // // RSA2(SHA256) // aliPublicKey = []byte(`-----BEGIN PUBLIC KEY----- // MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqBFkVdN/quRFMGq0yQKpFTcCU...
package storage import ( "fmt" "k8s-pv-provisioner/cmd/provisioner/config" "path" "regexp" "strings" core_v1 "k8s.io/api/core/v1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/klog" ) const hostnamePattern = `^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0...
package operator import ( "strings" "time" "github.com/pingcap/monitoring/pkg/common" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/pkg/rulefmt" "github.com/youthlin/stream" streamtypes "github.com/youthlin/stream/types" "gopkg.in/yaml.v2" ) const ( ALERT_FOR_CONFIG = "5m" ) var ( ...
// 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-present Datadog, Inc. package merger import ( "strings" commonv1 "github.com/DataDog/datado...
package solutions func maxProduct(nums []int) int { if nums == nil || len(nums) == 0 { return 0 } result, lastMax, lastMin := nums[0], 1, 1 for i := 0; i < len(nums); i++ { if nums[i] < 0 { lastMax, lastMin = lastMin, lastMax } lastMax, lastMin = max(lastM...
package main import ( "fmt" "math" ) func reverse(x int) int { var sign = 1 if x < 0 { sign := -1 x *= sign } result := 0 for x > 0 { remainder := x % 10 result *= 10 result += remainder x /= 10 } value := result * sign if value > math.MaxInt32 || value < math.MinInt32 { r...
package graph // This file will be automatically regenerated based on the schema, any resolver implementations // will be copied through when generating and any unknown code will be moved to the end. import ( "BackEnd/graph/generated" "BackEnd/middleware" "BackEnd/models" "context" "encoding/json" "errors" "fm...
package cryptocore import ( "github.com/transmutate-io/cryptocore/block" "github.com/transmutate-io/cryptocore/tx" "github.com/transmutate-io/cryptocore/types" ) type ( BlockFunc = func() (block.Block, error) TransactionFunc = func() (tx.Tx, error) CloseFunc = func() BlockGenerator interface { G...
package set1 import ( "bytes" "testing" ) func TestDecryptSingleByteXOR(t *testing.T) { input := "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" expected := "Cooking MC's like a pound of bacon" inputDecoded := decodeHex(input) actual, _, _ := DecryptSingleByteXOR(inputDecoded, nil) if ...
// 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 msgsend import ( "encoding/json" "github.com/MatrixAINetwork/go-matrix/common" "github.com/MatrixAINetwork/go-matrix/mc" "githu...
package main func main() { } type simpleHandler struct { } func (h * simpleHandler) HandleMessage(data []byte) error { return nil }
package main import ( "context" "fmt" "net/http" "os" "github.com/engelsjk/faadb/rpc/reserved" ) func main() { addr := "http://localhost:8084" // reserved server client := reserved.NewReservedProtobufClient(addr, &http.Client{}) GetAircraft(client, "138SS", "") // GetAircraft(client, "", "NATIONAL AERONA...
// ===================================== // // author: gavingqf // // == Please don'g change me by hand == // //====================================== // /*you have defined the following interface: type IConfig interface { // load interface Load(path string) bool // clear interface Clear() }...
// 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 removesubcommands import ( "fmt" "os" snmpsimclient "github.com/inexio/snmpsim-restapi-go-client" "github.com/rs/zerolog/log" "github.com/spf13/cobra" "github.com/spf13/viper" ) // UserFromEngineCmd represents the userFromEngine command var UserFromEngineCmd = &cobra.Command{ Use: "user-from-engine"...
/* * Copyright 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 to i...
package parse import ( "io/ioutil" "strconv" "sync" ) const ( INT string = "int" STR string = "string" FLO string = "float" SSB string = "sub-square-brackets" SBR string = "sub-brace" ) var ( // Addon包括addon, reporter, analyzer, conner Addons = make(map[string] Addon) Scripts = make(map[string] *Script) ...
// Copyright 2015 com 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 ...
package acceptance import ( "context" "testing" "github.com/databrickslabs/terraform-provider-databricks/common" "github.com/databrickslabs/terraform-provider-databricks/internal/acceptance" "github.com/databrickslabs/terraform-provider-databricks/workspace" "github.com/stretchr/testify/assert" ) func TestAccW...
// Copyright 2019 The gVisor Authors. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package sync provides synchronization primitives. // // +checkalignedignore package sync
package core // Cart represents a Moltin cart: https://docs.moltin.com/api/carts-and-checkout/carts type Cart struct { ID string `json:"id,omitempty"` Type string `json:"type"` Links *Links `json:"links,omitempty"` Meta *CartMeta `json:"meta,omitempty"` } // CartMeta represents the Meta object for a...
package message // FreeMessageIn is a example about payload with non-protobuf message type FreeMessageIn struct { Msg string `json:"msg"` } // FreeMessageOut is a example about payload with non-protobuf message type FreeMessageOut struct { Msg string `json:"msg"` }
package service import ( "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/s3iface" ) type S3Client struct { svc s3iface.S3API } func NewS3Client() *S3Client { return &S3Client{ svc: s3.New(session.New(), aws.N...
package udwSqlite3Test import ( "github.com/tachyon-protocol/udw/udwFile" "github.com/tachyon-protocol/udw/udwSqlite3" "github.com/tachyon-protocol/udw/udwTest" ) func TestMustTableCopy() { const dbPath = "/tmp/test_sqlite3.db" udwFile.MustDelete(dbPath) defer udwFile.MustDelete(dbPath) db := udwSqlite3.MustNe...
package datafile import ( "bufio" "os" "strconv" ) // первый аргументы функции это то что функция будет принимать // вторые скобки это то что функция будет возвращать func GetFloats(filename string) ([3]float64, error) { /*Нахождение среднего значение чисел из файла с числами*/ var numbers [3]float64 file, er...
package key import ( "bytes" "fmt" "github.com/lleo/go-functional-collections/key/hash" ) type ByteSlice []byte func (bsk ByteSlice) Less(okey Sort) bool { var obsk, ok = okey.(ByteSlice) if !ok { panic("okey is not a key.String") //return false } var lobsk = len(obsk) for i, b := range bsk { if lobsk...
package healthsrv import ( "net/http" "github.com/teamhephy/builder/pkg/controller" hephy "github.com/teamhephy/controller-sdk-go" ) // GetClient is an (*net/http).Client compatible interface that provides just the Get cross-section of functionality. // It can also be implemented for unit tests. type GetClient in...
package controllers import ( "net/http" ) // HelloController return say hello type HelloController interface { Hello(c Context) } // Resp is respose body type Resp struct { Msg string `json:"msg"` } // SayHello return hello for you func SayHello(c Context) error { m := Resp{ Msg: "Hello Workd!", } return c....
package arquivei import ( "encoding/json" "go-nfe-repeater/configuration" "go-nfe-repeater/nfe" "log" "net/http" ) type NfeData struct { AccessKey string `json:"access_key"` Xml string `json:"xml"` } type StatusData struct { Code uint8 `json:"code"` Message string `json:"message"` } type NfeReceivedRespons...
package main import ( "bufio" "fmt" "math" "os" "strconv" "strings" ) func main() { var n int fmt.Scanf("%d", &n) reader := bufio.NewReader(os.Stdin) temps, _ := reader.ReadString('\n') tokens := strings.Split(temps, " ") if len(tokens) == 0 { fmt.Println("0") os.Exit(0) } var c int = 1e5 for i ...
package main import ( "flag" "fmt" "io/ioutil" "log" "github.com/IMQS/pgparser/generator" "github.com/IMQS/pgparser/parser" ) func main() { s := flag.String("sql", "", "SQL Statement") f := flag.String("file", "", "File Containing SQL") p := flag.Bool("print", true, "Print SQL") g := flag.Bool("generate", ...
// 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 memory import ( "context" "encoding/json" "fmt" "io/ioutil" "path" "path/filepath" "strconv" "strings" "chromiumos/tast/common/perf" "chromiumos/tast/erro...
package oauthsdk import ( "encoding/json" "errors" "io/ioutil" "log" "net/http" ) type MicrosoftoAuth2Keys struct { Keys []struct { Kty string `json:"kty"` Use string `json:"use"` Kid string `json:"kid"` X5T string `json:"x5t"` N string `json:"n"` E string `json:"e"` X5C []string `...
package models import ( "context" "corona/helpers" "database/sql" "fmt" "github.com/lib/pq" uuid "github.com/satori/go.uuid" "time" ) type ( UserModel struct { Id uuid.UUID SubscriptionId uuid.UUID Name string Email string Password string IsActive bool ...
/* Copyright 2021 The KodeRover 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, s...
// 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 instanttether import ( "context" "regexp" "strings" "time" "chromiumos/tast/common/testexec" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/...
func firstUniqChar(s string) int { cache := [26]int{} for _, l := range s { cache[l-'a']++ } for i := range s { if cache[s[i]-'a'] == 1 { return i } } return -1 }
// 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 lacrosfixt import ( "io/ioutil" "os" "strings" "chromiumos/tast/errors" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/lacros" ) // Option is t...
package request import ( "net/http" "time" ) // TODO: Document c_tors func NewRequestBuilder() RequestBuilder { return &requestBuilder{ auth: newAuthNone(), headers: make(map[string]string), method: defaultMethod, timeout: defaultTimeout, } } func newHttpClient(timeout time.Duration) *http.Client { ...
package main import ( "testing" ) func TestCode(t *testing.T) { var tests = []struct { p int q int output string }{ {1, 100, "1 9 45 55 99"}, {100, 300, "297"}, {400, 700, ""}, } for _, test := range tests { if got := modifiedKaprekarNumber(test.p, test.q); got != test.output { t.Error...
package math import "testing" type testpair struct{ values[] float64 average float64 sum float64 } var tests = []testpair{ { []float64{1, 2}, 1.5, 3}, { []float64{1,2,3,4,5,6}, 21.0/6.0, 21}, { []float64{0}, 0, 0}, { []float64{1,1,1,1}, 1, 4}, } func TestAverage(t *testing.T){ for _,...
package gorm import ( "github.com/porter-dev/porter/internal/models" "github.com/porter-dev/porter/internal/repository" "gorm.io/gorm" ) // SessionRepository uses gorm.DB for querying the database type SessionRepository struct { db *gorm.DB } // NewSessionRepository returns pointer to repo along with the db func...