text
stringlengths
11
4.05M
/* Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Example 1: Input: pattern = "abba", s = "dog cat cat dog" Output: true Example 2: Input: pattern = "abba", s = "dog cat cat fi...
package api type RobotMessage struct { ID int `json:"id" sqlite:"id,INTEGER PRIMARY KEY autoincrement"` // 消息ID, 自动递增 RobotID string `json:"robotId" sqlite:"robotId,VARCHAR(64)"` // 机器人ID Process string `json:"process" sqlite:"process,VARCHAR(64)"` // 机器人流程名称 Level string `json:"l...
func hIndex(citations []int) int { sort.Ints(citations) n:=len(citations) for i,v:=range citations{ if n-i<=v{ return n-i } } return 0 }
package base import ( "errors" "fmt" "gengine/context" "reflect" ) type RuleEntity struct { RuleName string Salience int64 RuleDescription string RuleContent *RuleContent Vars map[string]reflect.Value //belongs to current rule,rule execute finish, it will be clear } func (r *Rul...
package mail_relay import ( "fmt" "errors" "strings" "bytes" "net/http" "io/ioutil" "encoding/json" log "github.com/sirupsen/logrus" apis "texas_real_foods/pkg/utils/api_accessors" ) var ( // generate new event channel to process requests eventChannel = make(chan MailRela...
package perfect import ( "errors" ) type Classification string const ClassificationDeficient Classification = "Deficient" const ClassificationAbundant Classification = "Abundant" const ClassificationPerfect Classification = "Perfect" const ClassificationUndefined Classification = "Undefined" var ErrOnlyPositive = ...
package cmd import ( "fmt" "github.com/alewgbl/fdwctl/internal/config" "github.com/alewgbl/fdwctl/internal/logger" "github.com/alewgbl/fdwctl/internal/util" "github.com/spf13/cobra" ) var ( rootCmd = &cobra.Command{ Use: "fdwctl", Short: "A management CLI for PostgreSQL postgres_fdw Foreign Data Wrapper",...
package lintcode /** * @param nums: The integer array. * @param target: Target to find. * @return: The first position of target. Position starts from 0. */ func binarySearch(nums []int, target int) int { if len(nums) == 0 { return -1 } start := 0 end := len(nums) - 1 for end-start > 1 { mid := (start + en...
package 动态规划 func waysToStep(n int) int { const mod = 1000000007 ways := make([]int, n+3) ways[0], ways[1], ways[2] = 1, 1, 2 for i := 3; i <= n; i++ { ways[i] = ways[i-1] + ways[i-2] + ways[i-3] ways[i] %= mod } return ways[n] } /* 题目链接: https://leetcode-cn.com/problems/three-steps-problem-lcci/submiss...
package main import ( "github.com/gin-gonic/gin" "fmt" "net/http" "time" ) func main() { // gin based on net/http and each request handled by individual goroutine router := gin.Default() router.GET("/async/:id", func(context *gin.Context) { contextCopy := context.Copy() go func() { id := contextCopy.Par...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //633. Sum of Square Numbers //Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. //Ex...
package main import ( "os" "reflect" "testing" ) func TestNewDeck(t *testing.T) { d := newDeck() if len(d) != 52 { t.Errorf("Expected size of deck to be 52, but got [%v]", len(d)) } if d[0] != "Ace of Diamonds" { t.Errorf("Expected first card to be Ace of Diamonds, but got [%v]", d[0]) } if d[len(d) -...
package utils func ErrToString(err error) string { if err != nil { return err.Error() } return "<clean>" }
package main import ( "container/heap" "errors" "fmt" ) type Project struct { profit int capital int } type Projects []Project func (h Projects) Len() int { return len(h) } func (h Projects) Less(i, j int) bool { if h[i].profit == h[j].profit { return h[i].capital < h[j].capital } return h[i].profit > h[...
package main import ( "fmt" "os" "github.com/codegangsta/cli" "github.com/EverythingMe/meduza/mdzctl/codegen" ) var langs = []string{"py", "go"} var genCommand = cli.Command{ Name: "gen", Usage: "Generate models from a schema file", Flags: []cli.Flag{ cli.StringFlag{ Name: "lang, l", Usage: "langua...
package im import ( "encoding/json" "log" "strings" "github.com/astaxie/beego/context" "github.com/wst-libs/wst-sdk/errors" "github.com/wst-libs/wst-sdk/im/sdk" "github.com/wst-libs/wst-sdk/utils" ) func SetOutPutHeader(ctx *context.Context) { ctx.Output.Header("Connection", "close") ctx.Output.Header("Cont...
// Copyright 2015 PingCAP, 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...
//go:build integration // +build integration package msgbuzz import ( "os" "testing" "time" "github.com/stretchr/testify/require" ) func TestRabbitMqClient_Publish(t *testing.T) { t.Run("ShouldPublishMessageToTopic", func(t *testing.T) { // Init rabbitClient := NewRabbitMqClient(os.Getenv("RABBITMQ_URL"),...
package handlers import ( "github.com/olivetree123/coco" "github.com/olivetree123/river/pocket" ) func AckHandler(c *coco.Coco) coco.Result { msgID := c.Params.ByName("msgID") node := pocket.ConsumingPool.Load(msgID) pocket.GarbageList.Push(node) return coco.APIResponse(nil) }
package app import ( "errors" "github.com/go-chi/chi" "github.com/go-chi/render" "net/http" ) // The list of error types returned from account resource. var ( ErrUserValidation = errors.New("user validation error") ) // AccountStore defines database operations for account. type UserStore interface { Get(id int...
package _12_Integer_to_Roman func intToRoman(num int) string { return intToRomanGreedy(num) } func intToRomanGreedy(num int) string { var ( str string values = []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1} symbols = []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", ...
package commands import ( "fmt" "github.com/luckywinds/rshell/options" "github.com/luckywinds/rshell/pkg/checkers" "github.com/luckywinds/rshell/pkg/crypt" "github.com/luckywinds/rshell/types" "strconv" "strings" ) func getGroupAuthbyHostinfo(hostinfo string) (types.Hostgroup, types.Auth, error) { if hostinfo...
package gaodeMap // get the route type StructRoute struct { Status string `json:"status"` Message string `json:"info"` Result *StructResult `json:"route"` } type StructResult struct { Origin string `json:"orign"` Destination string `json:"destination"` Routes []*StructRoutes `json:"paths"` } type StructRoutes ...
package main import ( "fmt" "sort" "strings" "github.com/Nerzal/gocloak/v13" ) type Username string // User is the definition of an user in excel state type User struct { niveau string email Username prenom string nom string segment string fonction...
package app import ( "github.com/RichardKnop/machinery/v1" // "github.com/aws/aws-sdk-go/aws/session" // "github.com/casbin/casbin/v2" gormadapter "github.com/casbin/gorm-adapter/v2" "github.com/jinzhu/gorm" "github.com/qor/media" "github.com/qor/oss" log "github.com/sirupsen/logrus" "github.com/spf13/viper" ...
package handlers import ( "net/http" "github.com/cloudfoundry-incubator/notifications/metrics" "github.com/cloudfoundry-incubator/notifications/models" "github.com/cloudfoundry-incubator/notifications/web/params" "github.com/cloudfoundry-incubator/notifications/web/services" "github.com/dgrija...
package main import ( "fmt" "godistributed-rabbitmq/coordinator" _ "godistributed-rabbitmq/storage" "log" ) var dbConsumer *coordinator.StorageConsumer var webConsumer *coordinator.WebappConsumer func main() { log.Println("Starting sensor listener...") aggregator := coordinator.NewAggregator() dbConsumer = co...
package db import "gorm.io/gorm" // 단일 로그 저장 type ApiLog struct { gorm.Model Api string Status string Latency string Method string } // 서비스 호출 횟수 저장 type ApiCount struct { gorm.Model Api string Count uint Method string }
package galaxy import ( "../basic" "math" "github.com/lucasb-eyer/go-colorful" ) type star struct { Current *basic.Point prev *basic.Point mass float64 force *basic.Point number int } const VertexCount = 10 func newStar(p *basic.Point, v *basic.Point, mass float64, n int) *star { return &star{ Current: p...
package main import ( "fmt" "net/http" ) func index1_handler(w http.ResponseWriter, r *http.Request) { //we can write anything like html in this fmt.Fprintf(w, "<h1 align=\"center\" style=\"color:red\">This is web</h1>") fmt.Fprintf(w, "<p align=\"center\">Making different text appear</p>"+ "<p align=\"cente...
package auth0 import ( "bytes" "context" "errors" "github.com/jpurdie/authapi" "github.com/jpurdie/authapi/pkg/utl/redis" "github.com/segmentio/encoding/json" "log" "net/http" "os" "strings" "time" ) var ctx = context.Background() var ( ErrUnableToReachAuth0 = errors.New("unable to reach authentication s...
package main import "fmt" func main() { fmt.Println(minNumberInRotateArray([]int{3, 4, 5, 1, 2})) } /** * * @param rotateArray int整型一维数组 * @return int整型 */ func minNumberInRotateArray(rotateArray []int) int { // write code here if len(rotateArray) == 0 { return 0 } min := rotateArray[0] for i := 0; i < l...
package p import ( "fmt" "go/ast" "go/parser" "go/token" "regexp" "runtime" "strings" _ "unsafe" "github.com/Kretech/xgo/astutil" ) // VarName 用来获取变量的名字 // VarName(a, b) => []string{"a", "b"} func VarName(args ...interface{}) []string { return varNameDepth(1, args...) } func varNameDepth(skip int, args ....
package types import ( "errors" "fmt" "testing" sptypes "github.com/bluele/interchain-simple-packet/types" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/exported" c...
// Copyright 2021 Google LLC. 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 applica...
// SPDX-License-Identifier: Unlicense OR MIT package headless import "github.com/gop9/olt/gio/app/internal/gl" /* #cgo CFLAGS: -DGL_SILENCE_DEPRECATION -Werror -Wno-deprecated-declarations -fmodules -fobjc-arc -x objective-c #include <CoreFoundation/CoreFoundation.h> #include "headless_darwin.h" */ import "C" type...
package main import "fmt" // Operasi Boolean func main() { var ( ujian = 80 absensi = 88 ) fmt.Println(ujian >= 80 && absensi >= 80) }
package server import ( "log" "net/http" ) // LogMiddleware returns handler decorated with log statement. func LogMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer log.Printf("[HTTP] %s %s", r.Method, r.RequestURI) h.ServeHTTP(w, r) }) }
package trie import ( "fmt" "github.com/openacid/low/bitmap" ) // levelInfo records node count upto every level(inclusive). // Slim has a slice []levelInfo to track node counts. // These nodes count info helps to speed up in finding out the original position // of a key in the creating key value array, with the he...
package sdk import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "strconv" "testing" "time" rmTesting "github.com/brigadecore/brigade/sdk/v3/internal/restmachinery/testing" // nolint: lll "github.com/stretchr/testify/require" ) func TestNewLogsClient(t *testing.T) { client, ok := NewLog...
package cmd import ( "github.com/benjlevesque/task/pkg/db" "github.com/benjlevesque/task/pkg/tasks" "github.com/benjlevesque/task/pkg/util" "github.com/spf13/cobra" ) var doCmd = &cobra.Command{ Use: "do", Short: "Marks a task as done", ValidArgsFunction: util.GetTaskListValidArgs(db....
package common const ( MaxEditctBits = 11 IndexMask = ((1 << MaxEditctBits) - 1) ) const weaponPrefix = "weapon_" /* */ type ( RoundMVPReason byte Hitgroup byte RoundEndReason byte Team byte EquipmentElement int EquipmentClass int ) /* */ const ( MVPReasonMostEliminations Ro...
package pkg import ( "bytes" "crypto/tls" "github.com/wonderivan/logger" "io" "io/ioutil" "mime/multipart" "net/http" "net/url" "os" "path" "strings" ) type HarborCfg struct { URL string UserName string Password string } // GetUserAgent returns a user agent for user with an HTTP client func userAg...
package ddtracer import ( "context" "fmt" stdlog "log" "math/rand" "os" "time" "github.com/DataDog/dd-trace-go/tracer" opentracing "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" "github.com/opentracing/opentracing-go/log" ) func init() { rand.Seed(time.Now().UnixNano()...
package io import ( "encoding/binary" "io" "strings" "testing" ) func TestReadFull(t *testing.T) { var b [4]byte bufMsgLen := b[:2] reader := strings.NewReader("hello") if n, err := io.ReadFull(reader, bufMsgLen); err != nil { t.Log(err) } else { t.Log(n) } msgLen := uint32(binary.BigEndian.Uint16(bu...
package templateresolution import ( "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" apierr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo/errors" wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" "github.com/argoproj/argo/pkg/...
// Copyright 2018 Google Inc. 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...
package api import ( "github.com/blang/semver/v4" v "github.com/go-playground/validator/v10" ) var validate *v.Validate func init() { validate = v.New() validate.SetTagName("binding") validate.RegisterValidation("version", func(fl v.FieldLevel) bool { version, ok := fl.Field().Interface().(string) if ok { ...
package main import ( "fmt" "github.com/kavenegar/kavenegar-go" ) func main() { api := kavenegar.New(" your apikey ") messageid := []string{"", ""} if res, err := api.Message.Select(messageid); err != nil { switch err := err.(type) { case *kavenegar.APIError: fmt.Println(err.Error()) case *kavenegar.HT...
package vpx import ( "fmt" "image" ourcodec "github.com/trevor403/gostream/codec" "github.com/edaniels/golog" "github.com/trevor403/mediadevices/pkg/codec" "github.com/trevor403/mediadevices/pkg/codec/vpx" "github.com/trevor403/mediadevices/pkg/prop" ) type encoder struct { codec codec.ReadCloser img i...
// Copyright 2022 Google LLC. 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 applica...
package main import "fmt" type Test interface { Print() //Write() } type Student struct { name string age int score int } //go中,任何类型 只要实现了某个接口中的所有方法,就实现了该接口 func (p *Student) Print() { fmt.Println("name:", p.name) fmt.Println("age:", p.age) fmt.Println("score:", p.score) } func main() { var t Test var ...
package powerdns import "testing" func TestBool(t *testing.T) { source := true if *Bool(source) != source { t.Error("Invalid return value") } } func TestBoolValue(t *testing.T) { source := true if BoolValue(&source) != source { t.Error("Invalid return value") } if BoolValue(nil) != false { t.Error("Unex...
package bitmap // BitMap 位图 type BitMap struct { bytes []byte size int } // NewBitMap 新建位图 func NewBitMap(size int) *BitMap { return &BitMap{bytes: make([]byte, size/32), size: size} } func (m *BitMap) set(k int) { if k > m.size { return } byteIndex := uint(k / 8) bitIndex := uint(k % 8) m.bytes[byteIndex...
package main import ( "github.com/garyburd/redigo/redis" "fmt" ) var pool *redis.Pool func init() { pool = &redis.Pool{ MaxIdle:16, MaxActive:1024, IdleTimeout:300, Dial: func() (redis.Conn, error) { return redis.Dial("tcp", "localhost:6379") }, } } func main() { connect := pool.Get() defer conn...
package circuit type Gate interface { AddConnection(Connection) Evaluate() Signal } type SignalGate struct { Connections []Connection Signal Signal } func (gate *SignalGate) AddConnection(connection Connection) { gate.Connections = append(gate.Connections, connection) } func (gate SignalGate) Evaluate() S...
package main import ( "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" "github.com/aws/aws-sdk-go/aws/session" "fmt" "github.com/aws/aws-sdk-go/service/dynamodb" "encoding/json" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" ) type DynamoDb struct { Configuration *Configuration ApiCl...
/* Your job is to figure out why Daniel likes Wendy, and some other girls. If you look at the Tests tab you'll notice that Daniel doesn't like many girls. Create a function that returns whether he likes her true, or not false. Examples danielLikes("Imani") ➞ false danielLikes("Margo") ➞ true danielLikes("Sandra")...
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this fi...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obta...
// Copyright 2009 The Go 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 x509 parses X.509-encoded keys and certificates. package bitx509 import ( "crypto" "encoding/asn1" "errors" "math/big" "time" "github.com/njo...
package controller import ( "dmicro/common/log" "dmicro/pkg/context" passport "dmicro/srv/passport/api" "dmicro/web/dd/internal/client" ) // 这里定义了 Passport Controller 模块,包含了各个处理函数。 // PassportController ... type PassportController struct { } // context.DmContext 内部 gin.Context 对象,因为 dmicro 用了 gin http 框架。 // gin...
package eyas_forage import ( "time" "context" "github.com/ricky1122alonefe/hawkEye-go/module" "go.etcd.io/etcd/clientv3" "go.etcd.io/etcd/mvcc/mvccpb" ) // 任务管理器 type ForageManager struct { client *clientv3.Client kv clientv3.KV lease clientv3.Lease watcher clientv3.Watcher } var ( // 单例 forageMgr *Fora...
package antminer import ( "time" "github.com/ka2n/masminer/sshutil" "golang.org/x/crypto/ssh" ) var ( sshDialer sshutil.TimeoutDialer ) // NewSSHClient returns *ssh.Client with default setting func NewSSHClient(host string) (*ssh.Client, error) { return NewSSHClientTimeout(host, 0) } // NewSSHClientTimeout re...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package azurestack import ( "context" "fmt" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2018-05-01/resources" "github.com/Azure/go-autorest/autorest" log "github.com/sirupsen/logrus" ) // DeployTempla...
package zapdefaults import ( "fmt" "os" "strings" "github.com/mattn/go-isatty" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // Preset is an option that specifies a default configuration. type Preset int32 const ( Invalid Preset = iota // Development uses a console encoder, colored output, and more friendly...
package passbook import ( "crypto/rand" "fmt" "io/ioutil" "os" ) // PassBook - type passbook type PassBook struct { blocks uint16 loadData []byte exportData []byte } // NewPassBook - func NewPassBook(blocks uint16) *PassBook { return &PassBook{ blocks: blocks, } } // getters // GetLoadData - func (...
// +build load package main import ( "flag" "fmt" "strconv" "sync" "time" ) // func makeConnection(wg *sync.WaitGroup, times int, msg string) { // conn, err := net.Dial("tcp", ":1774") // oks := 0 // notoks := 0 // PanicOnError(err) // defer conn.Close() // defer wg.Done() // for i := 0; i < times; i++...
package main import ( "fmt" "unsafe" ) func InspectSlice(slice []string) { // Capture the address to the slice structure address := unsafe.Pointer(&slice) addrSize := unsafe.Sizeof(address) // Capture the address where the length and cap size is stored lenAddr := uintptr(address) + addrSize capAddr := uintptr...
func GO() { fmt.Println("我是GO,现在没有发生异常,我是正常执行的。") } func PHP() { defer func() { if err := recover(); err != nil { fmt.Println("终于捕获到了panic产生的异常:", err) // 这里的err其实就是panic传入的内容 fmt.Println("我是defer里的匿名函数,我捕获到panic的异常了,我要recover,恢复过来了。") } }() panic("我是PHP,我要抛出一个异常了,等下defer会通过recover捕获这个异常,捕获到我时,在PHP里是不会输...
package sqlconnector import "github.com/jinzhu/gorm" func Connect() (*gorm.DB, error) { db, err := connectCloudSql() if err != nil { return nil, err } if db != nil { return db, nil } return connectLocalSql() }
package goSolution func leastBricks(wall [][]int) int { f := make(map[int]int) n := len(wall) for i := 0; i < n; i++ { w := wall[i] k := 0 for j := 0; j < len(w) - 1; j++ { k += w[j] f[k] += 1 } } r := 0 for _, value := range f { r = max(r, value) } return n - r }
// Copyright 2016 Kranz. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package base import ( "crypto/sha1" "encoding/hex" "encoding/json" ) // Encode string to sha1 hex value. func EncodeSha1(str string) string { h := sha1.New() h.Wri...
// Copyright (C) 2020 VMware, Inc. // SPDX-License-Identifier: Apache-2.0 package common import ( "github.com/sirupsen/logrus" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) type BaseSuite struct { suite.Suite Name string CreateFlags []string } func (s *BaseSuite) SetupTest(...
package gogacap import ( "testing" ) func TestChanZeroToNumber(t *testing.T) { aa := [][]int{ []int{}, } c := ChanZeroToNumber(-1) for _, a := range aa { b := <-c if !sliceEq(a, b) { t.Errorf("%v != %v", a, b) } } aa = [][]int{ []int{}, []int{0}, } c = ChanZeroToNumber(0) for _, a := range...
package main import ( "bufio" "container/heap" "container/list" "fmt" "log" "math" "os" "regexp" "strconv" ) type point struct { x int y int z int radius float64 } const ( input = "day23/input.txt" //input = "day23/test.txt" //input = "day23/test2.txt" ) // An Item is something we man...
// Copyright 2021 PingCAP, 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 response import ( "net/http" "github.com/GoAdminGroup/go-admin/context" "github.com/GoAdminGroup/go-admin/modules/auth" "github.com/GoAdminGroup/go-admin/modules/config" "github.com/GoAdminGroup/go-admin/modules/db" "github.com/GoAdminGroup/go-admin/modules/errors" "github.com/GoAdminGroup/go-admin/mod...
//go:build darwin // +build darwin package envoy import ( "context" "syscall" "github.com/pomerium/pomerium/internal/log" ) var sysProcAttr = &syscall.SysProcAttr{ Setpgid: true, } func (srv *Server) runProcessCollector(_ context.Context) {} func (srv *Server) prepareRunEnvoyCommand(ctx context.Context, share...
package ionic import ( "bytes" "encoding/json" "fmt" "net/url" "github.com/ion-channel/ionic/pagination" "github.com/ion-channel/ionic/products" "github.com/ion-channel/ionic/responses" ) // GetProducts takes a product ID search string and token. It returns the product found, // and any API errors it may enc...
package loadbalancer_api import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func prepareRequest(body interface{}) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { bodyBuf = &bytes.Buffer{} } err = json.NewEncoder(bodyBuf).Encode(body) return } func GetPathListAll(client *http.Client, ...
// Copyright 2014 The Sporting Exchange Limited. All rights reserved. // Use of this source code is governed by a free license that can be // found in the LICENSE file. // Package config implements shared configuration-related routines. package config import ( "bytes" "crypto/tls" "encoding/json" "expvar" "fmt" ...
package node import ( "reflect" "babyboy-dag/rpc" "babyboy-dag/event" "babyboy-dag/accounts" "errors" ) type Service interface { APIs() []rpc.API } type ServiceConstructor func(ctx *ServiceContext) (Service, error) type ServiceContext struct { Services map[reflect.Type]Service // Index of the already c...
package bydefine type ProductModel struct{ Name string `json:"name"` //设备型号 SerialNo string `json:"serial_no"` //序列号 }
package main import ( "fmt" "io" "strconv" "time" ) // Point wraps a single data point. It stores database-agnostic data // representing one point in time of one measurement. // // Internally, Point uses byte slices instead of strings to try to minimize // overhead. type Point struct { MeasurementName []byte Ta...
package LongSteps type Operand interface { Evaluate(environment Environment) (Operand, Environment) Int(Environment) int Bool(Environment) bool } type IntNumber int func (i IntNumber) Evaluate(environment Environment) (Operand, Environment) { return i, nil } func (i IntNumber) Int(Environment) int { return int(...
package main import ( "encoding/json" "fmt" "net/http" "github.com/graphql-go/graphql" "github.com/graphql-go/graphql/examples/todo/schema" ) type postData struct { Query string `json:"query"` Operation string `json:"operationName"` Variables map[string]interface{} `json:"...
package lingua import ( "bytes" "testing" ) func TestSummary(t *testing.T) { testCases := []struct { description, want string input Summary }{ { description: "It outputs a proper definition", input: Summary{ Word: "jejune", Pronunciation: "/jay-june/", Definitions: []D...
/* Package params contains implementation for QueryParameters api interface. */ package params import ( "net/http" "github.com/go-chi/chi/v5" ) // Chi implements QueryParameters api interface for // chi router. // // You can safely use new bulit-in function to allocate // new Chi instace. type Chi struct{} func (...
package escaping import ( "testing" ) func Test_EscapeString_UnescapeString(t *testing.T) { mapping := map[string]string{ // spaces "": "", " ": " ", " ": " ", // doublequotes `\"`: "\"", `\" \"`: "\" \"", // newlines `\n`: "\n", `\n \n`: "\n \n", // backslashes `\\`: "\\...
package config import ( "database/sql" "fmt" "testing" "github.com/DemoHn/obsidian-panel/pkg/dbmigrate" // init migrations _ "github.com/DemoHn/obsidian-panel/app/migrations" // import sqlite3 _ "github.com/mattn/go-sqlite3" ) func TestConfigDBLoad(t *testing.T) { // TODO: add testcase db, _ := sql.Open("s...
package mockingjay import ( "fmt" "regexp" ) // RegexYAML allows you to work with regex fields in YAML type RegexYAML struct { *regexp.Regexp } // UnmarshalYAML will unhmarshal a YAML field into regexp func (r *RegexYAML) UnmarshalYAML(unmarshal func(interface{}) error) error { var stringFromYAML string err := ...
package run import ( "reflect" "sync" ) // LazyRunner run Run only when there is at least one supervisor type LazyRunner struct { Run func(stopCh <-chan struct{}) Locker interface { sync.Locker RLock() RUnlock() } // protect supervisorStopChs, running, stoppedCh supervisorStopChs []<-chan struct{} run...
package main import ( "fmt" ) func main() { var a int = 2 switch a { case 0: fmt.Println("a = 0") case 1: fmt.Println("a = 1") case 2: fmt.Println("a = 2") default: fmt.Println("a != 0, 1 or, 2") } }
package day12 import ( "testing" "github.com/stretchr/testify/require" ) func TestRotation(t *testing.T) { f := NewFerry() require.Equal(t, "E", f.Direction) require.NoError(t, f.MoveNormal("R90")) require.Equal(t, "S", f.Direction) require.NoError(t, f.MoveNormal("L90")) require.Equal(t, "E", f.Direction) ...
package main import "fmt" // Functional Programming func Adder() func(int) int { // internal state sum := 0 // return function which has access to internal state return func(x int) int { sum += x return sum } } func main() { // init the function sum := Adder() for i := 0; i < 10; i++ { // modify state ...
package gobyexample import ( "fmt" ) func Make() { fmt.Println("go make keyword") x := make([]int, 0, 10) fmt.Println("x:", x) fmt.Printf("x: %v\n", x) fmt.Printf("type: %T", x) }
package main import ( "fmt" "time" "os" "errors" endPoint "go_chat/src/core" "flag" ) func getGreeting(hour int) (string, error) { var message string if hour < 7 { err := errors.New("Too early, we're closed!") return message, err } else if hour < 12 { message = "Good Morning" } else if hour < 18 { ...
package core type Evaluation struct { Id string `json:"id"` JobKind string `json:"job_kind"` JobId string `json:"job_id"` Priority int `json:"priority"` Status string `json:"status"` } type NodeAllocationState struct { NodeId string `json:"node_id"` AllocationId str...
package bot import ( "log" "fmt" ) type contextLogger struct { Account *BotAccount Context *Context } func newContextLogger(account *BotAccount, context *Context) *contextLogger { log.Println("Bot::newContextLogger") return &contextLogger{Account: account, Context: context } } func (l *contextLogger) debug(ms...