text
stringlengths
11
4.05M
package mowa import ( "context" "net/http" "net/http/httptest" "net/http/httputil" "testing" ) var testC *Context func init() { req, _ := http.NewRequest("Get", "http://localhost:1234/hello/world?name=chen&age=25&name=yun", nil) testC = &Context{ Request: req, } } func handle1(c *Context) (int, interface{...
package main import ( "runtime" "fmt" "time" ) func main() { //设置可以执行的cpu的最大数量 runtime.GOMAXPROCS(2) ch1 := make(chan int) ch2 := make(chan int) go pump1(ch1) go pump2(ch2) go suck(ch1, ch2) fmt.Println(runtime.NumCPU(),"================") time.Sleep(1e9) } func pump1(ch chan int) { for i := 0; ; ...
package settings import ( "Golang-Echo-MVC-Pattern/constant" "Golang-Echo-MVC-Pattern/utils" "context" "fmt" "github.com/jackc/pgx/v4/pgxpool" "github.com/joho/godotenv" "os" ) var db *pgxpool.Pool type Database struct{} func init() { err := godotenv.Load() if err != nil { println(constant.MessageEnviron...
package stemsrepo_test import ( "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/bosh-io/web/stemcell/stemsrepo" ) var _ = Describe("NewS3Stemcell", func() { type ExtractedPieces struct { Version string Name string InfName string HvName string DiskFormat string ...
package utils import ( "bytes" "encoding/json" "io/ioutil" "net/http" "os" "strings" "github.com/kardianos/osext" uuid "github.com/satori/go.uuid" "github.com/sirupsen/logrus" "golang.org/x/crypto/bcrypt" ) func Digest(password string) (string, error) { hashedPassword, err := bcrypt.GenerateFromPassword([...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //796. Rotate String //We are given two strings, A and B. //A shift on A consists of taking string A and moving the leftmost character to the rightmost...
package compress import ( "bytes" ) const ( x855595167=`HttpURLConnection httpConn = (HttpURLConnection) myURL.openConnection(); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setUseCaches(false); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/json;charse...
package aes import ( "crypto/aes" "crypto/cipher" ) type Encrypter struct { Key Key Nonce []byte } func (e Encrypter) EncryptAES(plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(e.Key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err }...
package slack import ( "encoding/json" "net/http" "reflect" "testing" "github.com/stretchr/testify/assert" "github.com/slack-go/slack/internal/errorsx" ) var dummySlackErr = errorsx.String("dummy_error_from_slack") type viewsHandler struct { rawResponse string } func (h *viewsHandler) handler(w http.Respon...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //575. Distribute Candies //Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each n...
package infrastructure import ( "context" "errors" "reflect" "strconv" "testing" "time" "github.com/jybbang/go-core-architecture/core" "github.com/jybbang/go-core-architecture/infrastructure/leveldb" ) func Test_leveldbStateService_Has(t *testing.T) { ctx := context.Background() leveldb := leveldb.NewLeve...
package main import ( "fmt" "strconv" ) func possibleIPs(rawIP []rune, start int, dotOffsets []int, results []string) []string { if len(dotOffsets) > 3 { return results } if start >= len(rawIP) { return results } if len(dotOffsets) == 3 && dotOffsets[len(dotOffsets)-1] < len(rawIP)-1 { // Form string, ...
/* * Minio Client (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
package main import ( "fmt" "testing" ) func TestMultiply(t *testing.T) { //fmt.Println(Multiply("123", "456")) //fmt.Println(Multiply("2", "3")) fmt.Println(Multiply("98", "9")) }
package i3 import ( "bytes" "encoding/binary" "encoding/json" "errors" "io" "log" "net" "os/exec" "strconv" "strings" ) var ( magicStringBytes = []byte("i3-ipc") magicStringBytesLen = len(magicStringBytes) messageSize = binary.Size(ipcMessage{}) ) func (c *Conn) Listen() (err error) { defer ...
package main import "fmt" func (gr *Graph) Mst() (mst []Edge) { var edgeToAdd, groupID uint64 mst = []Edge{} // Using union-find algorithm to detect cycles sort.Sort(byWeight(gr.RawEdges)) vertexByGroup := make(map[uint64][]uint64) vertexGroups := make(map[uint64]uint64) connect := make([]uint64, 2) lastUsedG...
package models type OutputRequest struct { RawRequest []byte `json:"request"` RawResponse []byte `json:"response"` }
package hpke import ( "crypto" "crypto/elliptic" "crypto/rand" "testing" "github.com/stretchr/testify/require" ) func randomBytes(size int) []byte { out := make([]byte, size) rand.Read(out) return out } func TestKEMSchemes(t *testing.T) { schemes := []KEMScheme{ &dhkemScheme{group: x25519Scheme{}}, &dh...
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "time" ) var _FilterTextSearchRecords_colmap = map[string]string{ "Id": `u."id"`, "Email": `u."email"`, "FullName": `u."full_name"`, "CreatedAt": `u."created_at"`, } func (f *FilterTextSearchRecords) Init()...
package main import ( "fmt" "log" "os" "os/exec" ) type makeVM struct { RHOSTemplate string datacenter string datastore string vmName string folder string memory int cpu int disksize int mac string ignitionbase64 string } func (mv *makeVM) ...
package main import "fmt" func main() { x, y := 10, 20 a := [...]*int{ &x, &y, } p := &a fmt.Printf("%T, %v\n", a, a) fmt.Printf("%T, %v\n", p, p) }
package main import ( "flag" "fmt" log "github.com/Sirupsen/logrus" "github.com/gorilla/mux" "github.com/k0kubun/pp" "github.com/satori/go.uuid" "io" "net" "net/http" "os" "reflect" "strconv" "strings" "sync" "time" ) var ( config *Config tokens *Tokens failedIP *FailedIP ) func init() { toke...
package orm import ( "database/sql" "gorm.io/driver/mysql" "gorm.io/gorm" "time" ) var db *gorm.DB var err error var sqlDB *sql.DB func init() { dsn := "aitifen:aitifen@tcp(10.16.4.250:3310)/gsvip_crm?charset=utf8mb4&parseTime=True&loc=Local" db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) sqlDB, err = d...
package main const sizeOfSlice = 1000000 const pi float64 = 3.141592653589793238462643 const eulerNum float64 = 2.718281828459045235360287 const bigFloat float64 = 10987654321.123456789 func fpBenchmark(i int) { multiples := make([]float64, sizeOfSlice) results := make([]float64, sizeOfSlice) // initializes slic...
package filter import ( "fmt" "strings" "fxkt.tech/bj21/internal/pkg/ffmpeg/math" ) type Stream string const ( StreamAudio Stream = "a" StreamVideo Stream = "v" ) func SelectStream(idx int, s Stream, must bool) string { var qm string if !must { qm = "?" } return fmt.Sprintf("%d:%s%s", idx, s, qm) } typ...
package main import ( "log" "net/http" "github.com/gorilla/mux" mgo "gopkg.in/mgo.v2" ) func main() { session, err := mgo.Dial("localhost") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) database := session.DB("golang") controller := NewController(database) rou...
package plik import ( "crypto/tls" "encoding/json" "io" "net/http" "runtime" "github.com/root-gg/plik/server/common" ) // Client manage the process of communicating with a Plik server via the HTTP API type Client struct { *UploadParams // Default upload params for the Client. Those can be overridden per uploa...
package cmd import ( "github.com/steviebps/realm/utils" ) type RealmConfig struct { Client ClientConfig `json:"client,omitempty"` Server ServerConfig `json:"server,omitempty"` } type ServerConfig struct { StorageType string `json:"storage"` StorageOptions map[string]string `json:"options"` Port ...
package base const ( // The username of the special "GUEST" user GuestUsername = "GUEST" ISO8601Format = "2006-01-02T15:04:05.000Z07:00" //kTestURL = "http://localhost:8091" kTestURL = "walrus:" ) func UnitTestUrl() string { return kTestURL }
package v040_test import ( "encoding/json" "fmt" "testing" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/legacy/v039" v039 "github.com/provenance-io/pr...
package maintChain import ( sdk "github.com/cosmos/cosmos-sdk/types" "time" ) // Record is a struct that contains all the metadata of a maintenance record type Record struct { Id string `json:"id"` Time time.Time `json:"time"` Vin sdk.AccAddress `json:"vin"` Org sdk.AccAddress `jso...
package main import "fmt" const ( a11 = 454 b11 string = "b11" ) const ( x = 2017 + iota y = 2017 + iota z = 2017 + iota ) func main() { a := 42 fmt.Printf("%d\t%b\t#x", a, a, a) b := (42 >= 45) fmt.Println(b) fmt.Println(a11) fmt.Println(b11) fmt.Println(x) fmt.Println(y) }
package token import ( "camp/lib" "camp/week2/api" "time" ) func (t *TokenModel) Add(user *api.User) (token string, err error) { c := t.GetC() defer c.Database.Session.Close() now := time.Now() str := now.String() + "-+-" + user.Password token = lib.HashSha256(str) aHour, _ := time.ParseDuration("24h") tim...
package user import ( "camp/lib" "camp/week2/api" "camp/week2/service" "encoding/json" "github.com/simplejia/clog/api" "net/http" ) type LoginReq struct { Email string `json:"email"` Password string `json:"password"` } func (l *LoginReq) Register() (ok bool) { if l == nil || l.Email == "" || l.Password ==...
package ssh import ( "testing" ) func TestSsh(t *testing.T) { addr := "x3.tc" alive := Ssh(addr, 50) t.Log("[%v]:[%v]\n", addr, alive) }
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { reader := bufio.NewReaderSize(os.Stdin, 100009) l, _, _ := reader.ReadLine() t, _ := strconv.Atoi(string(l)) for ; t > 0; t-- { s, _, _ := reader.ReadLine() removed := -1 for i := 0; i < len(s)/2; i++ { a := s[i] b := s[len(s)-1-...
// Copyright (c) 2018 Palantir Technologies. 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 require...
package interfaces import ( "github.com/georgerapeanu/CP-Crawlers/generic" "time" "errors" ) type GenericCrawler interface { GetSubmissions(handle string, beginTime time.Time, //the begin time point endTime time.Time) ([]generic.Submission,err error) // the end time point GetSubmissionsForTask(handle string,...
package main import ( "devbook-api/src/config" "devbook-api/src/router" "fmt" "log" "net/http" ) func init() { // loads values from .env into the system config.Load() } func main() { fmt.Printf("Running api in %d\n", config.ApiPort) r := router.Generate() log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", ...
package clients import ( "net/url" ) func UrlBasePath(u *url.URL) string { return u.Scheme + "://" + u.Host + "/" }
// Copyright 2019 John Papandriopoulos. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package zydis /* #cgo CFLAGS: -I./lib/include #include <Zydis/Zydis.h> #include <stdlib.h> #define __paster2(a, b) a ## b #define __evaluator2(a, b) _...
package model import ( "time" ) type PlayerVersion struct { // Id of the resource Id string `json:"id,omitempty"` // Version of the Player Version string `json:"version,omitempty"` // URL of the specified player CdnUrl string `json:"cdnUrl,omitempty"` // Download URL of the specified player package DownloadUr...
package dynamic_programming import ( "fmt" "testing" ) func Test_minimumTotal(t *testing.T) { nums := [][]int{ {2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}, } res := minimumTotal(nums) fmt.Println(res) }
package store import ( "sync" "github.com/nikunjgit/crypto/event" ) type MemoryStore struct { memory map[string]event.Messages ttl int mutex *sync.Mutex } func NewMemoryStore(ttl int) *MemoryStore { return &MemoryStore{make(map[string]event.Messages), ttl, &sync.Mutex{}} } func (m *MemoryStore) Set(key st...
import "sort" func singleNumber(nums []int) int { return sol1(nums) } // using Sort.sort (quicksort or heapsort) // time: O(n*log(n)), space: O(1) func sol1(nums []int) int { sort.Ints(nums) for i := 0; i < len(nums); i = i + 2 { if i+1 < len(nums) && nums[i] != nums[i+1] { return nums[i] } } return nums[...
package main import ( "database/sql" "fmt" "html/template" "log" "net/http" _ "github.com/mattn/go-sqlite3" ) type brand struct { Company string Ltp string Change string Volume string Buy_price string Sell_price string Buy_qty string Sell_qty string } type Var struct { temp ...
package main import ( "flag" "fmt" "log" "math" "os" "sort" ) var ( wins = [][]int{ {1, 2, 3}, {1, 4, 7}, {1, 5, 9}, {2, 5, 8}, {3, 5, 7}, {3, 6, 9}, {4, 5, 6}, {7, 8, 9}} turn, count, total int win bool = false stat string ) type Game struct { board [][]st...
package easy import ( "fmt" "testing" ) func Test20(t *testing.T) { a := "()[]{]}" isValid(a) } func fan(s string) string { switch s { case "{": return "}" case "(": return ")" case "[": return "]" case "}": return "{" case ")": return "(" case "]": return "[" } return "" } func isValid(s...
package daemons import ( "fmt" "docktor/server/middleware" "docktor/server/types" "github.com/labstack/echo/v4" ) // AddRoute add route on echo func AddRoute(e *echo.Group) { daemons := e.Group("/daemons") // Basic daemon request daemons.GET("", getAll) daemons.GET("/rundeck", getAllRundeck, middleware.Wit...
// 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 saml import ( "bytes" "encoding/base64" "encoding/xml" "log" "net/http" "text/template" ) var redirectFormTemplate = `<!DOCTYPE html> <html> <head></head> <body> <form id="redirect" method="POST" action="{{.FormAction}}"> <input type="hidden" name="RelayState" value="{{.RelayState}}" /> <input...
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package hashing import ( "crypto/sha256" "testing" "github.com/stretchr/testify/require" ) const algSHA256 = 5 func TestHash(t *testing.T) { t.Run("success", func(t *testing.T) { test := []byte("hello world"...
package routers import ( "github.com/astaxie/beego" "sago/controllers" ) func init() { beego.Router("/", &controllers.MainController{}) beego.AutoRouter(&controllers.UserController{}) // beego.Router("/user/test", &controllers.UserController{}, "*:Test") // beego.Router("/user/:id", &controllers.UserController{...
package dcmdata import ( "github.com/grayzone/godcm/ofstd" ) type DcmElement struct { DcmObject /// current byte order of attribute value in memory fByteOrder E_ByteOrder /// required information to load value later fLoadValue DcmInputStreamFactory /// value of the element fValue uint16 } /** get a pointer...
package main import "moriaty.com/cia/cia-common/auth" func main() { auth := auth.NewAuth("memory") auth.RemoveToken("1") }
package service import ( "errors" "fmt" "github.com/linxlib/logs" "github.com/robfig/cron/v3" "sync" ) func Init() { logs.Error(fmt.Errorf("Test Error: %+v",errors.New("error example"))) } type WeatherJob struct { mtx sync.Mutex running bool } func (w *WeatherJob) Run() { if !w.SetRun() { logs.Warn(...
package libpq import ( "fmt" "github.com/yydzero/mnt/executor" "io" "net" "github.com/yydzero/mnt/executor/fake" "log" ) // ErrSSLRequired is returned when a client attemps to connect to a // secure server in clear text. const ErrSSLRequired = "cleartext connections are not permitted" const ( version30 = 0x3...
package main import ( "fmt" "strings" ) type opmap map[int]int type opcoderesult struct { opcode int matches map[int]bool } func getMatchIndexes(s state, ops []operation, om opmap, results chan opcoderesult) { count := map[int]bool{} for i, op := range ops { result := op.fn(s.beforeregs, s.inputreg1, s.inp...
package main import ( "net/http" ) type fileHandler string func FileHandler(config map[string]string) http.Handler { return fileHandler(mustGet(config, "path")) } func (f fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, string(f)) }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //513. Find Bottom Left Tree Value //Given a binary tree, find the leftmost value in the last row of the tree. //Example 1: //Input: // 2 // / \ /...
package golify type golifyBooleanObject struct { Value bool Err *golifyErr }
package goidc import ( "encoding/json" "fmt" "net/http" "strconv" "github.com/golang-jwt/jwt" "github.com/lyokato/goidc/authorization" "github.com/lyokato/goidc/bridge" "github.com/lyokato/goidc/flow" "github.com/lyokato/goidc/id_token" "github.com/lyokato/goidc/io" "github.com/lyokato/goidc/log" "github....
package awsupload import ( "fmt" "log" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "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/aws/aws-sdk-go/service/s3" "github.com/aws/aws-s...
/* * randmat: random number generation * * input: * nrows, ncols: the number of rows and columns * s: the seed * * output: * martix: a nrows x ncols integer matrix * */ package main import ( "flag" "fmt" "runtime" "bufio" "os" ) // #include <time.h> // #include <stdio.h> import "C" type ByteMa...
package utils import ( "crypto/rand" "fmt" "io" "golang.org/x/crypto/bcrypt" ) // HashPassword - hashes given password string func HashPassword(input string) (string, error) { bytes, err := bcrypt.GenerateFromPassword([]byte(input), 15) return string(bytes), err } // CheckPasswordHash - Checks password has fu...
package day6 import ( "fmt" "github.com/kdeberk/advent-of-code/2019/internal/utils" "strings" ) type node struct { name string parent *node children []*node depth int } func makeNode(name string) *node { return &node{name, nil, []*node{}, 0} } func (self *node) addChild(child *node) { child.parent...
package TF2RconWrapper import ( "github.com/stretchr/testify/assert" "testing" ) var logs []string = []string{ `"Sk1LL0<2><[U:1:198288660]><Unassigned>" joined team "Red"`, `"Sk1LL0<2><[U:1:198288660]><Red>" changed role to "scout"`, `"Sk1LL0<2><[U:1:198288660]><Red>" changed role to "soldier"`, `"Sk1LL0<2><[U:...
package compiler import ( "os" "strings" "github.com/go-task/task/v2/internal/taskfile" ) // GetEnviron the all return all environment variables encapsulated on a // taskfile.Vars func GetEnviron() taskfile.Vars { var ( env = os.Environ() m = make(taskfile.Vars, len(env)) ) for _, e := range env { key...
// Copyright © 2018 Inanc Gumus // Learn Go Programming Course // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // // For more tutorials : https://learngoprogramming.com // In-person training : https://www.linkedin.com/in/inancgumus/ // Follow me on twitter: https://twitter.com/inancgumus package main ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-11-13 09:32 # @File : lt_978_Longest_Turbulent_Subarray.go # @Description : # @Attention : */ package slide_window import ( "fmt" "testing" ) func Test_maxTurbulenceSize(t *testing.T) { // A := []int{9, 4, 2, 10, 7, 8, 8, 1, 9} A := []int{9, 4, 2, 10, 7,...
package rc import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "strings" "github.com/ncw/rclone/cmd" "github.com/ncw/rclone/fs" "github.com/ncw/rclone/fs/fshttp" "github.com/ncw/rclone/fs/rc" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) var ( noOutput = fa...
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file 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/li...
package metric import ( "bytes" "encoding/binary" "fmt" "metric/win" "net" ) // 获取tcp连接表 func GetTcpTable() (tt *TcpTable, err error) { var ptb *win.MIB_TCPTABLE = &win.MIB_TCPTABLE{} var size uint32 if win.GetTcpTable(ptb, &size, 1) != win.ERROR_INSUFFICIENT_BUFFER { return tt, fmt.Errorf("call native Get...
package graphql_test import ( "testing" "github.com/graphql-go/graphql" "github.com/graphql-go/graphql/gqlerrors" "github.com/graphql-go/graphql/testutil" ) func TestValidate_NoUnusedVariables_UsesAllVariables(t *testing.T) { testutil.ExpectPassesRule(t, graphql.NoUnusedVariablesRule, ` query ($a: String,...
package cluster import ( "fmt" "github.com/KubeOperator/KubeOperator/pkg/util/ssh" "testing" "time" ) func TestGetClusterToken(t *testing.T) { client, err := ssh.New(&ssh.Config{ User: "root", Host: "172.16.10.184", Port: 22, Password: "Calong@2015", PrivateKey: nil, PassPhra...
package g2db import ( "fmt" "reflect" "strings" "github.com/pkg/errors" "xorm.io/xorm" "github.com/atcharles/gof/v2/g2util" ) type ( //MysqlQueryRowsParams ... MysqlQueryRowsParams struct { Page int `json:"page,omitempty"` PageCount int `json:"page_count,omitempty"` Conditions []st...
package main import ( "fmt" "math/rand" ) func main() { arr := rand.Perm(11) fmt.Println(arr) arr = mergeSort(arr) fmt.Println(arr) } func mergeSort(arr []int) []int { if len(arr) < 2 { return arr } middle := len(arr) / 2 left, right := arr[:middle], arr[middle:] return merge(mergeSort(left), mergeSor...
package main import ( "fmt" "strconv" "strings" ) func asInt(txt string) int { if val, err := strconv.Atoi(txt); err == nil { return val } else { panic("bad input, expected number, got : " + txt) } } func processLine(line string, currentTotal int) int { line = strings.TrimSpace(line) if line != "" { if...
package advent06 import ( "strings" ) type Body struct { Id string Orbiters []*Body Orbiting *Body } func ParseBodyTree(input string) (*Body, map[string]*Body) { bodies := make(map[string]*Body) for _, line := range strings.Split(input, "\n") { parts := strings.Split(line, ")") orbited, orbiter := p...
package multipart import ( "io" "os" ) type File struct { name string io.ReadCloser } func (f *File) FileName() string { return f.name } func (f *File) Close() error { return f.ReadCloser.Close() } type IOFile struct { name string *os.File } func (f *IOFile) Close() error { var err error err = f.File.Cl...
package models import ( "fmt" mapStructure "github.com/mitchellh/mapstructure" uuid "github.com/nu7hatch/gouuid" apiResponse "github.com/alexhornbake/go-crud-api/lib/api_response" sql "github.com/alexhornbake/go-crud-api/lib/datastore" log "github.com/alexhornbake/go-crud-api/lib/logging" ) type Post struct { ...
package dao import ( "coffeebeans-people-backend/models" "context" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type KafkaService struct { conn string } func (k KafkaService) CreateUser(ctx context.Context, user models.User) error { retur...
// Package route53 implements a DNS provider for solving the DNS-01 challenge // using AWS Route 53 DNS. package aws import ( "fmt" "log" "math/rand" "os" "strings" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-s...
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "regexp" "time" "github.com/confluentinc/confluent-kafka-go/kafka" ) var newsSummary map[string][]StdNews var newsContent map[string][][]string //WangYiNewsRaw contains a raw material form API type WangYiNewsRaw map[string][]struct { L...
package Problem0313 // 解题思路可以参考 264 题 func nthSuperUglyNumber(n int, primes []int) int { if n == 1 { return 1 } pos := make([]int, len(primes)) candidates := make([]int, len(primes)) copy(candidates, primes) res := make([]int, n) res[0] = 1 for i := 1; i < n; i++ { res[i] = min(candidates) for j := 0...
package 一维子串问题 /* 给定一个未经排序的整数数组,找到最长且连续的的递增序列。 */ // 原始dp (空间没有优化) // dp[i] 表示: 以nums[i]结尾的最长连续递增序列长度 // 状态转移方程: // 初始 : dp[i] = 1。 // i > 0 && nums[i] > nums[i-1]: dp[i] = dp[i-1] + 1 func findLengthOfLCIS(nums []int) int { dp := make([]int, len(nums)+1) maxLength := 0 for i := 0; i < len(nums); i++ { i...
package routers import ( "encoding/json" "net/http" "github.com/rodzy/flash/db" "github.com/rodzy/flash/models" ) //Register func to create an user in our MongoDB func Register(w http.ResponseWriter,r *http.Request) { var t models.User //Streaming the json file err:=json.NewDecoder(r.Body).Decode(&t) if err ...
package service import ( "github.com/Tanibox/tania-core/src/growth/domain" "github.com/Tanibox/tania-core/src/growth/query" "github.com/Tanibox/tania-core/src/growth/storage" "github.com/gofrs/uuid" ) type CropServiceInMemory struct { MaterialReadQuery query.MaterialReadQuery CropReadQuery query.CropReadQue...
package shader import ( "fmt" "image" _ "image/jpeg" _ "image/png" "io/ioutil" "os" "strings" wrapper "github.com/akosgarai/opengl_playground/pkg/glwrapper" ) func textureMap(index int) uint32 { switch index { case 0: return wrapper.TEXTURE0 case 1: return wrapper.TEXTURE1 case 2: return wrapper.TE...
package k8s import ( appmesh "github.com/aws/aws-app-mesh-controller-for-k8s/apis/appmesh/v1beta2" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "testing" ) func TestNamespacedName(t *testing.T) { tests := []struct { name string obj metav...
/* Copyright 2021. The KubeVela 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 writ...
package data import ( "github.com/google/uuid" ) // Account represents a bank account, its structure follows https://api-docs.form3.tech/api.html#organisation-accounts-resource. // Fake account service does not implement "private_identification" and "relationships". type Account struct { Type RecordType `...
package main import ( "database/sql" ) func main() { injectionTest("Nottingham") } func injectionTest(city string) { db, err := sql.Open("postgres", "postgresql://test:test@test") if err != nil { // return err } var count int row := db.QueryRow("SELECT COUNT(*) FROM t WHERE city=" + city...
package commands import ( "github.com/cloudfoundry/bosh-bootloader/storage" "github.com/cloudfoundry/bosh-bootloader/terraform" ) type up interface { CheckFastFails([]string, storage.State) error ParseArgs([]string, storage.State) (UpConfig, error) Execute([]string, storage.State) error } type terraformManager ...
package accumulate import ( "reflect" "runtime" "strings" ) func GetFunctionName(i interface{}) string { return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() } func Accumulate(listOfString []string, converter func(string) string) []string { var currentFuncName = GetFunctionName(converter) var funcNameE...
package main import ( "github.com/tidwall/gjson" "io/ioutil" "net/http" "testing" ) func TestGetPrice(t *testing.T) { go startServer(false) resp, _ := http.Get("http://localhost:8080/categories/MLA5726/price") resp_body, _ := ioutil.ReadAll(resp.Body) data := string(resp_body) max, min, sg := gjson.Get(data,...
package main import ( "sync" "gopkg.in/cheggaaa/pb.v1" ) type ProgressBar struct { //totalPb *pb.ProgressBar okPb *pb.ProgressBar errorPb *pb.ProgressBar pool *pb.Pool } func NewProgressBar() *ProgressBar { //totalPb := makeProgressBar(options.FilePathTotalLines, "TOTAL") okPb := makeProgressBar(optio...
package main import "fmt" func help2() { fmt.Println("helper function 2 called") }
package main import ( "fmt" "time" ) func say() { time.Sleep(100 * time.Millisecond) fmt.Println("Hello world!") } func main() { go say() fmt.Println("Goodbye world! Or?") time.Sleep(200 * time.Millisecond) }
package sqle import ( "context" "fmt" ) // MySQL extends sqle.Std with MySQL specific functions type MySQL struct { Std *Std } // UnsafeExists checks whether the statement defined by the `query` and `args` // would return a result. // // This method IS NOT SAFE AGAINST SQL-INJECTION. Use it only with trusted // i...