text
stringlengths
11
4.05M
package main import ( "fmt" "math" "os" "github.com/Raytracer/src" ) func panicIf(err error) { if err != nil { panic(err) } } func hit_sphere(center utils.Vector, radius float64, r *utils.Ray) float64 { oc := utils.Subtract(r.Origin(), center) a := utils.Dot(r.Direction(), r....
// Copyright 2019 Kuei-chun Chen. All rights reserved. package analytics import ( "time" ) // PRIMARY - primary node const PRIMARY = "PRIMARY" // SECONDARY - secondary node const SECONDARY = "SECONDARY" // MemberDoc stores replset status type MemberDoc struct { Name string `json:"name" bson:"name"` Optim...
package config import ( "github.com/egnis/server/router/apis/handlers" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "github.com/labstack/gommon/log" "time" ) func InitDB() gorm.DB { db := initializeDatabase() initializeTable(db) createMockData(db) return db } func initializeDatabase() gorm.DB...
// Package azure generates Machine objects for azure. package azure import ( "fmt" "sort" "strings" "github.com/pkg/errors" "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" v1 "github.com/openshift/api/config/v1" machin...
package game import ( "errors" "fmt" "github.com/conest/ebby/game/def" "github.com/conest/ebby/game/scene" "github.com/conest/ebby/system" ) // SceneMap : Scene 列表映射 map type SceneMap map[string]*scene.Scene // loadScenes : 加载 Scene 列表 func loadScenes(sceneMap SceneMap, gamedata *def.GameData) SceneMap { for ...
package main import ( "fmt" "time" "github.com/aws/aws-sdk-go/aws" "github.com/prometheus/client_golang/prometheus" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/keikoproj/aws-sdk-go-cache/cache" ) const pageSize = 10 fu...
package manager import ( "bytes" "net/http" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/upload-image-service/data" ) var ( awsScretKey = os.Getenv("S3_SECRET_ACCESS_KEY") token ...
package main import ( "os" "fmt" "flag" "util" "path/filepath" "log" "os/exec" "io/ioutil" ) var cmakeBuild string var ProjectName string var MainFile string func init() { flag.StringVar(&ProjectName, "p", "-", "-p project_name") flag.StringVar(&MainFile, "f", "main", "-f main.c/c++") } func main() { fl...
package day11 import "testing" func Test_countOccupiedSightLines(t *testing.T) { type args struct { row int col int seating [][]rune } tests := []struct { name string args args wantAdjacent int }{ { name: "full house, middle", args: args{ row: 20, col: 2, se...
package dependency import ( "bytes" "fmt" "os" "github.com/devspace-cloud/devspace/pkg/devspace/build" "github.com/devspace-cloud/devspace/pkg/devspace/config/generated" "github.com/devspace-cloud/devspace/pkg/devspace/config/loader" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest" "gi...
package main import "sync" type containerClient struct { dict map[string]*client rw *sync.RWMutex } func newContainerClient() *containerClient { return &containerClient{ dict: make(map[string]*client), rw: new(sync.RWMutex), } } func (ctc *containerClient) add(key string, c *client) { if c == nil { p...
package model import () /* Model that represent database 'products' table and REST json for 'product' */ type Product struct { ProductId int64 `gorm:"primary_key;AUTO_INCREMENT"` ProductName string `gorm:"size:50" json:"productName"` Description string `gorm:"size:255" json:"description"` Price float...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-06-17 09:50 # @File : loop_linked_list.go # @Description : 循环单链表 # @Attention : */ package linked_list import ( "errors" ) type CircleLinkedList struct { head *listNode size int } func (this *CircleLinkedList) Add(data interface{}) { newNode := NewLis...
package wire import "github.com/Secured-Finance/dione/blockchain/types" type GetRangeOfBlocksArg struct { From uint64 To uint64 } type GetRangeOfBlocksReply struct { Blocks []types.Block FailedBlockHeights []uint64 // list of block heights the node was unable to retrieve }
package arrys func Sum(arr []int) (sum int) { for _, v := range arr { sum += v } return } func SumAll(numbersToSum ...[]int) (sums []int) { lengthOfNumbers := len(numbersToSum) sums = make([]int, lengthOfNumbers) for i, numbers := range numbersToSum { sums[i] = Sum(numbers) } return }
package main import ( "strconv" "strings" ) type ListNode struct { Val int Next *ListNode } // 输入:"[3,2,0,-4]" // 输出:ListNode单向链表 func buildLinkedList(str string) *ListNode { str = strings.Replace(str, " ", "", -1) str = str[1 : len(str)-1] // 去除[]中括号 if str == "" { return nil } items...
package auto import ( "github.com/xeha-gmbh/homelab/iso/auto/api" . "github.com/xeha-gmbh/homelab/shared" "github.com/lithammer/dedent" "github.com/spf13/cobra" flag "github.com/spf13/pflag" "os" "strings" ) const ( noDefault = "" ) var ( output MessagePrinter ) type Payload struct { ExtraArgs Flavor ...
package wallet import ( "testing" ) func Test_Wallet(t *testing.T) { AssertEquals := func(t *testing.T, want Bitcoin, got Bitcoin) { t.Helper() if got != want { t.Errorf("Got %s, but wanted %s", got, want) } } t.Run("Deposit tests", func(t *testing.T) { wallet := Wallet{} wallet.Deposit(10) got...
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package p03 func intersect(nums1 []int, nums2 []int) []int { if nums1 == nil || nums2 == nil || len(nums1) == 0 || len(nums2) == 0 { return nil } h := map[int]int{} for _, v := range nums1 { h[v]++ } i := 0 for _, v := range nums2 { if n, ok := h[v]; ok && n > 0 { nums1[i] = v h[v]-- i++ } } ...
package web import( "os" "io/ioutil" //"log" ) func include(L *lua.State)int{ x := L.ToLString(1) file,err := os.Open(x) if err != nil { panic(err) } defer file.Close() fd,err := ioutil.ReadAll(file) L.PushString(string(fd)) return 1 } func parseHtm...
package errorcode // ValidationError represents validation error returns from the service layer type ValidationError struct { Err error } // Unwrap returns the underlying error func (e ValidationError) Unwrap() error { return e.Err } func (e ValidationError) Error() string { return e.Err.Error() } // DBError repres...
// Package passgen is an opinionated random password generator package for go // applications. Creates a random password that: // * is not based on a time event // * has at least 8 characters // * does not contain a complete word // * contains at least one character from each of these types: // - ` ~ ! @ # $ % ^ & * ( ...
package auth import ( "net/url" "testing" "github.com/GoAdminGroup/go-admin/modules/config" "github.com/GoAdminGroup/go-admin/plugins/admin/models" "github.com/stretchr/testify/assert" ) func TestCheckPermissions(t *testing.T) { config.Initialize(&config.Config{ UrlPrefix: "admin", }) user := models.User...
package main import "fmt" func main() { fmt.Println("go by example") }
// Copyright 2022 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 mqtt import ( "errors" "io" "log" ) // errors var ( InclompleteHeader = errors.New("incomplete header") MaxMessageLength = errors.New("message length exceeds server maximum") MessageLengthInvalid = errors.New("message length exceeds maximum") IncompleteMessage = errors.New("incomp...
// Copyright 2023 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 onlineserving import ( "testing" "github.com/stretchr/testify/assert" "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/timestamppb" "github.com/feast-dev/feast/go/internal/feast/model" "github.com/feast-dev/feast/go/protos/feast/core" "github.com/feast-dev/fe...
/* A connected graph is a graph that contains a path between any two vertices. Challenge Build a [2-input NAND-gate] circuit that determines whether a 4-vertex graph is connected. (A gate's 2 inputs can be the same input bit or other gate.) Output True if the graph is connected, and False otherwise. Input The six po...
package collector_test import ( "context" "strings" "testing" "github.com/fabric8-services/fabric8-notification/auth" authApi "github.com/fabric8-services/fabric8-notification/auth/api" "github.com/fabric8-services/fabric8-notification/collector" "github.com/fabric8-services/fabric8-notification/testsupport" ...
package file import ( "github.com/Highway-Project/highway/pkg/service" "github.com/Highway-Project/highway/pkg/service/provider" ) type FileProvider struct { FilePath string } func (f FileProvider) Provide() ([]service.Service, error) { return nil, nil } func (f FileProvider) Watch(messageChan chan<- provider.M...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //714. Best Time to Buy and Sell Stock with Transaction Fee //Your are given an array of integers prices, for which the i-th element is the price of a ...
package dapr import ( "context" "encoding/json" "errors" dapr "github.com/dapr/go-sdk/client" "github.com/jybbang/go-core-architecture/core" ) type adapter struct { client dapr.Client settings DaprSettings } type DaprSettings struct { StoreName string PubsubName string } var daprClient dapr.Client fu...
package config import "os" type cfg struct { sentry string redis string postgres string log_file string log_level string } func GetConfig() *cfg { return &cfg{ sentry: os.Getenv("SENTRY_DSN"), redis: os.Getenv("REDIS"), postgres: os.Getenv("DATABASE_URL"), log_file: os.Getenv("APP_LOG_FILE"), log_le...
package utils import ( "bytes" "io" "net" "net/http" "net/url" "strings" ) func GetAuthTokenFromHeader(header http.Header) string { if authHeaderVal := header.Get("Authorization"); authHeaderVal != "" { return strings.TrimPrefix(authHeaderVal, "Bearer ") } if authHeaderVal := header.Get("Auth-Token"); auth...
// built with goldie // if golden files in fixture dir are manually verified, you can update with // go test -update package dandler import ( "html/template" "io/ioutil" "log" "net/http" "net/http/httptest" "testing" "github.com/sebdah/goldie" "github.com/stretchr/testify/assert" ) func init() { goldie.Fix...
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "os/exec" "strings" "github.com/gobuffalo/packr" ) const ( primaryServerModsFile = "/srv/games/servers/arma3_common/SOCOMD_mods.load" secondaryServerModsFile = "/srv/games/servers/arma3_common/SECONDARY_mods.load" startCMD ...
package controller import ( //"fmt" "net/http" "net/url" "../entity" "../utils" "log" ) //show quote of product func GetQuoteInfo(w http.ResponseWriter, r *http.Request) { q,_ := url.ParseQuery(r.URL.Path) pname := q["/GetQuoteInfo/projectName"][0] uname := q["investor"][0] log.Println(pname + uname) ...
package leetcode /*According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neig...
package main import ( "bytes" "context" "errors" "flag" "fmt" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" "io/ioutil" "log" "os" "os/exec" "path" "strconv" "strings" "syscall" "time" ) var objectSuffixes = make(map[string]uint64) var bucketName = "" func initMinioCli...
package common import ( "net/http" "fmt" "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) // NewRouter add all routes func NewRouter(routesAsk Routes, servicename string) *mux.Router { histogram := prometheus.NewHistogramVec...
package user type User struct { Id int64 `json:"id"` NickName string `json:"nickname"` FistName string `json:"firstname"` LastName string `json:"lastname"` Gender string `json:"gender"` Pass string `json:"pass"` Status uint8 `json:"status"` }
// Copyright Bombwhale // Package schoolmeal gets menu of Korean schools // schoolmeal 패키지는 대한민국의 유치원, 초중고 학교의 급식을 크롤링한 결과를 리턴하는 함수를 제공합니다. // 예제를 보고 싶으시면 이 패키지의 Github의 README.md를 봐 주세요. // package schoolmeal
package models import ( "github.com/cabernety/boxci/utils" "gopkg.in/mgo.v2" "github.com/google/go-github/github" "golang.org/x/crypto/bcrypt" "golang.org/x/oauth2" "gopkg.in/mgo.v2/bson" "time" log "github.com/Sirupsen/logrus" ) type ( AuthToken struct { Token string `orm:"auth_token"` UserAgent stri...
package cli import ( flag "github.com/spf13/pflag" randomtypes "github.com/irisnet/irismod/modules/random/types" ) const ( FlagReqID = "request-id" FlagBlockInterval = "block-interval" FlagOracle = "oracle" FlagServiceFeeCap = "service-fee-cap" FlagQueueHeight = "queue-height" ) var ( FsReq...
package stream import ( "context" "math" ) func Sinewave(ctx context.Context, bufferLen int, amplitude, frequency, phase float64, sampleRate int) chan Sample { sampleCh := make(chan Sample, bufferLen) radsPerSec := 2 * math.Pi * frequency phaseRadians := phase * 2 * math.Pi / 360 amplitude = amplitude * float64...
package models //Response is a struct for transmited JSON type Response struct { FoundAtSite string `json:"foundAtSite"` }
package parser /* Let us try to parse this grammar, using a Backtracking parser: stat : expr ';' ; binop : '+' | '-' | '*' | '/' | '^' | '++' | '--' ; unaryop : '-' | '++' | '--' ; expr : assign | unaryop expr | expr binop expr | '(' expr ')' | INT | ID ; assign : ID '=' expr | '(' assign ...
package utils import ( "net/http" "github.com/gin-gonic/gin" ) func CorsHandler() gin.HandlerFunc { return func(context *gin.Context) { context.Writer.Header().Set("Access-Control-Allow-Origin", "*") context.Header("Access-Control-Allow-Methods", "*") context.Header("Access-Control-Allow-Headers", "*") co...
package main import ( "crypto/rsa" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" "sync" "github.com/dgrijalva/jwt-go" ) func main() { pubKey, _ := ioutil.ReadFile("public-key.pem") publicKey, err := jwt.ParseRSAPublicKeyFromPEM(pubKey) if err != nil { log.Fatal(err) } api := &api{ P...
package hit import ( "math" "math/rand" "github.com/GuillaumeTech/3dgo/internal/geom" ) type Dielectric struct { RefractionIndex float64 } func (d Dielectric) Scatter(rayIn geom.Ray, hitRecord *HitRecord, attenutaion *geom.Vec3d, scattered *geom.Ray) bool { *attenutaion = geom.Vec3d{1, 1, 1} var etaTOverEtaI ...
package weather import ( "github.com/pkg/errors" ) var ErrNotFound = errors.New("not found") var urlWeather = "http://t.weather.sojson.com/api/weather/city/" type weatherInfo struct { Value1 string `json:"value1"` Value2 string `json:"value2"` }
package main import ( "bytes" "context" "crypto/md5" "encoding/hex" "errors" "flag" "image" "image/gif" "image/jpeg" "image/png" "io" "io/ioutil" "log" "mime/multipart" "net/http" "os" "os/signal" "path/filepath" "strconv" "strings" "syscall" "github.com/DDHax/sis/graphics" ) //文件大小上限,此参数将设置为接收...
package util import ( "net/url" ) func MakeURL(rawURL string) (string, error) { u, err := url.Parse(rawURL) if err != nil { return "", err } return u.String(), nil }
package main import "fmt" /** * 找出数组中和为给定值的两个元素的下标,例如数组[1,3,5,8,7],找出两个元素之和等于8的下标分别是(0,4)和(1,2) */ func myTest(a [5]int, target int) { for i := 0; i < len(a); i++ { other := target - a[i] for j := 0; j < len(a); j++ { if a[j] == other { fmt.Printf("(%d,%d)\n", i, j) } } } } func main() { a := [...
package gravatar import ( "strings" "crypto/md5" "os" ) type G struct { size int defaultImg string rating string } var ( errBadParm = os.NewError("bad parameter") errInvalidRating = os.NewError("invalid rating") ) func md5sum(s string) string { h := md5.New() h.Write([]byte(s)) sum := h.S...
package redisz import ( "Common/logger" "github.com/garyburd/redigo/redis" ) //set string func (r *RedisPool) Set(key string, value interface{}) error { conn := r.pool.Get() defer conn.Close() _, err := conn.Do("SET", key, value) if err != nil { logger.Warn("SET ", r.server, " ", r.name, " ", err.Error()) ...
package main /** 除自身以外数组的乘积 给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。 示例1: ``` 输入: [1,2,3,4] 输出: [24,12,8,6] ``` 提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。 说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。 进阶: 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。) */ /** 不能用除...
package models import "gopkg.in/mgo.v2/bson" // Foodtruck - Represents a Foodtruck type Foodtruck struct { ID bson.ObjectId `bson:"_id" json:"id"` Name string `bson:"name" json:"name"` ImageURL string `bson:"image_url" json:"image_url"` Phone string `bson:"phone" json...
package controlflow import "fmt" func Flow() { // IF else flow if true { fmt.Println("It is true") } else { fmt.Println("It is false") } // For loop for i := 0; i < 10; i++ { } j := 10 // while loop for j > 0 { j-- } data := []int{1, 2, 3, 4} for _, d := range data { fmt.Println(d) } }
// Copyright (C) 2015 Scaleway. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE.md file. package cli import "github.com/scaleway/scaleway-cli/pkg/commands" var cmdProducts = &Command{ Exec: runProducts, UsageLine: "products [OPTIONS] P...
package server import ( "fmt" "text2voice/xf" "github.com/dyike/log" ) type Server struct { opts *Options } type Options struct { OutDir string Level int TTSParams string LoginParams string Speed int } func New(opts *Options) *Server { return &Server{ opts: opts, } } // TODO func (...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-05-21 08:29 # @File : main.go # @Description : # @Attention : */ package main import ( "flag" "github.com/SebastiaanKlippert/go-wkhtmltopdf" "myLibrary/go-library/go/utils" ) var ( templatePath = flag.String("template", "/Users/joker/Desktop/fabric-ca...
package clickhousespanstore import ( "testing" "github.com/stretchr/testify/assert" ) func TestTableName_AddDbName(t *testing.T) { assert.Equal(t, TableName("database_name.table_name_local"), TableName("table_name_local").AddDbName("database_name")) } func TestTableName_ToLocal(t *testing.T) { tableName := Tabl...
package findMinArrowShots import ( "sort" ) type interval [][]int func (i interval) Len() int { return len(i) } func (i interval) Less(x, y int) bool { if i[x][0] < i[y][0] { return true } else if i[x][0] > i[y][0] { return false } else { return i[x][1] < i[y][1] } } func (i interval) Swap(x, y int) { i...
package main import "fmt" func goroutine(s []string, ch chan string) { defer close(ch) sum := "" for _, v := range s { sum += v ch <- sum } } func main() { words := []string{"test1", "test2", "test3", "test4"} ch := make(chan string) go goroutine(words, ch) for w := range ch { fmt.Println(w) } }
// Copyright 2023 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...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-16 14:29 * Description: *****************************************************************/ package gcontext import ( "fmt" "github.com/go-xe2/x/t...
package transfersh import ( "io/ioutil" "main/utils" "strings" ) const uploadUrl = "https://transfer.sh/" func upload(uploadUrl, path string, size, byteLimit int64) (string, error) { respBody, err := utils.MultipartUpload(uploadUrl, path, "file", size, byteLimit, nil, nil, nil) if err != nil { re...
package main import ( "net/http" "github.com/gin-gonic/gin" "../gchat/lib/auth" "../gchat/lib/websocket" ) const ( listenAddr = "localhost:9876" privateToken = "VerySecretToken" ) func RootHandler(c *gin.Context) { c.HTML(http.StatusOK, "chat.tmpl", gin.H{"host": listenAddr}) } func main() { router := gin.D...
package slave import ( "github.com/stretchr/testify/assert" "testing" ) func TestSetUp(t *testing.T) { port, slaveName, masterURL, proxyURL, OS := SetUp() assert.Equal(t, DEFAULT_LOCALHOST_PORT, port) assert.Equal(t, "SLAVE NAME UNSPECIFIED", slaveName) assert.Equal(t, "http://localhost:5000", masterURL) asse...
package levenshtein // based on https://raw.githubusercontent.com/julesjacobs/levenshtein/master/levenshtein.py // http://julesjacobs.github.io/2015/06/17/disqus-levenshtein-simple-and-fast.html // https://news.ycombinator.com/item?id=9737554 type Automaton struct { Text string MaxEdits int } type State struct...
package entity import ( "database/sql" "time" ) type UmsAdmin struct { ID int64 `json:"id" db:"id"` Username string `json:"username" db:"username"` SecretCode string `json:"secret_code" db:"secret_code"` Icon string `json:"icon" db:"icon"` Email string `json:...
package gorut import ( "errors" "testing" ) func TestIsValid(t *testing.T) { // Testing valid RUT rut := Rut{"14696787", "6"} actual, err := rut.IsValid() expected := true if actual != expected { t.Errorf("Got %v, expected %v", actual, expected) } if err != nil { t.Errorf("Got %v, expected %v", err, ni...
package main func main() { } func mctFromLeafValues(arr []int) int { //n := len(arr) // //var travel func(left, right int) int // //travel = func(left, right int) int { // // for k := left; k <= right; k++ { // //travel(left, k) + travel(k+1, right) // } // //} // //travel(0, n-1) return 0 }
package main import ( "flag" "fmt" "project/common/file" mycasbin "project/pkg/casbin" "project/utils" "project/common/database/mysql" "project/common/database/redis" "project/common/logger" "project/common/run" _ "project/docs" "project/utils/config" "go.uber.org/zap" ) // @title go-sword项目接口文档 // @ver...
package consumer import ( "log" "github.com/streadway/amqp" "github.com/vdntruong/rabbitmq/util" ) func WorkerQueue(ch *amqp.Channel, stop chan bool) { q, err := ch.QueueDeclare("queue01", false, false, false, false, nil) util.FailOnError(err, "Failed to declare a queue") msgs, err := ch.Consume(q.Name, "01 O...
package ilock type IUnLock interface { /* 解锁 强制解锁 key string 所需要加锁的Key 成功返回true 失败返回false */ Do(Key string) bool }
package main import ( "os" "strconv" "time" "github.com/bwmarrin/snowflake" "github.com/jmoiron/sqlx" _ "github.com/go-sql-driver/mysql" "github.com/labstack/echo" "github.com/labstack/echo/middleware" cache "github.com/patrickmn/go-cache" "github.com/Tayu0404/file-sync-system-server/api/handler" "github....
package stage import ( "context" "github.com/werf/werf/pkg/build/builder" "github.com/werf/werf/pkg/config" "github.com/werf/werf/pkg/container_runtime" ) func GenerateBeforeInstallStage(ctx context.Context, imageBaseConfig *config.StapelImageBase, baseStageOptions *NewBaseStageOptions) *BeforeInstallStage { b ...
package cmd import ( "fmt" "github.com/bitmaelum/bitmaelum-suite/internal/container" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/spf13/cobra" ) // uninviteCmd represents the uninvite command var uninviteCmd = &cobra.Command{ Use: "uninvite", Short: "Removes the invitation for the given addr...
package cron import ( "github.com/spf13/cobra" "github.com/wish/ctl/pkg/client" ) // Cmd returns the cron subcommand given a client to operate on func Cmd(c *client.Client) *cobra.Command { cron := &cobra.Command{ Use: "cron", Short: "A tool for cron on kubernetes", Long: "A subcommand for managing and re...
package top import ( "github.com/therecipe/qt/quick" "github.com/therecipe/qt/internal/examples/showcases/wallet/view/top/controller" ) func init() { lockTemplate_QmlRegisterType2("TopTemplate", 1, 0, "LockTemplate") } type lockTemplate struct { quick.QQuickItem _ func() `constructor:"init"` _...
package main import ( "go_package/Architecture" ) func main() { list := &Architecture.LinkedList{} list.AddNode(10) list.AddNode(20) list.AddNode(30) list.PrintNode() list.PrintReverseNode() list.AddNode(10000) list.AddNode(20000) list.AddNode(30000) list.PrintNode() list.PrintReverseNode() list.RemoveNo...
package handlers import ( "InkaTry/warehouse-storage-be/internal/http/admin/dtos" "InkaTry/warehouse-storage-be/internal/pkg/errs" "InkaTry/warehouse-storage-be/internal/pkg/stores" "context" "log" ) const logListInventories = "[ListInventories]" func (h *Handler) ListInventories(ctx context.Context, p *dtos.Li...
// Package session contains protobuf types for sessions. package session import ( context "context" "fmt" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" "github.com/pomerium/pomerium/internal/identity" "github.com/pomer...
package main import ( "fmt" ) func unique(strs []string) []string { i,j:=0,1 for j<len(strs){ if strs[i]==strs[j]{ j++ }else{ i++ strs[i]=strs[j] } } return strs[:i+1] } func main() { s:=[]string{"a","a","a","b","b","c","c"} s=unique(s) fmt.Printf("%v",s) }
package article import ( "github.com/go-jar/goerror" "blog/errno" ) func (ac *ArticleController) CreateAction(context *ArticleContext) { if err := ac.VerifyToken(context.ApiContext); err != nil { context.ApiData.Err = goerror.New(errno.EUserUnauthorized, err.Error()) return } articleEntity, tagIds, e := ac...
package oidc import ( "context" "crypto/ecdsa" "crypto/rsa" "crypto/sha256" "crypto/subtle" "encoding/base64" "errors" "fmt" "net/http" "net/url" "regexp" "strings" "time" "github.com/go-crypt/crypt" "github.com/go-crypt/crypt/algorithm" "github.com/go-crypt/crypt/algorithm/plaintext" "github.com/gol...
package nbt import "reflect" const ( tagEnd = 0 tagByte = 1 tagShort = 2 tagInt = 3 tagLong = 4 tagFloat = 5 tagDouble = 6 tagByteArray = 7 tagString = 8 tagList = 9 tagCompound = 10 ) // C is a wrapper for map[string]interface{} type C map[string]interface{} fun...
// Copyright 2017 Jeff Foley. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. package sources import ( "bufio" "encoding/json" "strings" "time" "github.com/OWASP/Amass/amass/core" "github.com/OWASP/Amass/amass/utils" ) // Robtex is data so...
package mppay import ( "encoding/json" //"github.com/satori/go.uuid" "strconv" //"strings" "time" ) type Wx struct { cfg *wxConfig } type PrePayResponse struct { PrePayID string `json:"prepay_id"` OriginPrePayID string `json:"origin_prepay_id"` Sign string `json:"sign"` TimeStamp strin...
package itertools import ( "container/list" ) type ListIter struct { items *list.List item *list.Element } func New(items *list.List) *ListIter { iter := new(ListIter) iter.Init(items) return iter } func (l *ListIter) Init(items *list.List) { l.items = items } func (l *ListIter) Item() *list.Element { ret...
package utils func DepartmentExist(department string) int { for k, v := range [...]string{"Marketing", "Design", "Development"} { if department == v { return k } } return -1 }
// Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. package external import ( "fmt" "os" "os/exec" "strings" "time" "github.com/fsouza/go-dockerclient" "github.com/wercker/wercker/util" ) // RunnerParams are the parameters that drive the control of Docker // containers where the externa...
package twitter import ( "net/http" "net/url" "errors" "github.com/firefirestyle/engine-v01/oauth/sns" "google.golang.org/appengine" m "github.com/firefirestyle/engine-v01/prop" "golang.org/x/net/context" "google.golang.org/appengine/log" ) const ( UrlOptCallbackUrl = "cb" UrlOptErrorNotFoun...
package bot import ( "context" "os" "strings" "sync" "time" "github.com/danielkvist/botio/client" "github.com/danielkvist/botio/proto" "github.com/sirupsen/logrus" "github.com/yanzay/tbot/v2" ) // Telegram is a wrapper for a yanzay/tbot client // that satifies the Bot interface. type Telegram struct { tcl...
package main import ( "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" ) type Connection struct { DB *gorm.DB } func Connect() Connection { cfg := mysql.Config{ Addr: Cfg.Host, User: Cfg.User, Passwd: Cfg.Pwd, DBName: Cfg.DbName, Net:...
package handlers import ( "fmt" "github.com/EgorLyutov/Inventor/models" "github.com/EgorLyutov/Inventor/tools" "github.com/gorilla/context" "gopkg.in/mgo.v2" "html/template" "log" "net/http" "strings" "time" ) func HandleNetworkHardware(args map[string]interface{}, id string, w http.ResponseWriter, r *http....