text
stringlengths
11
4.05M
package validator import ( "errors" "fmt" "net/http" "time" "github.com/gin-gonic/gin" ) const maxTimeGap = 30 * time.Second // 30 secs func newPublicError(msg string) *gin.Error { return &gin.Error{ Err: errors.New(msg), Type: gin.ErrorTypePublic, } } // ErrDateNotInRange error when date not in accept...
package main import ( "fmt" "io/ioutil" "log" "os" "strings" ) func main() { orbits := readFile() f, b := parseMap(orbits) d := map[string]int{} findDistanceFrom("COM", 0, f, d) totalOrbits := 0 for _, distance := range d { totalOrbits += distance } // Part 1 solution fmt.Println("Total orbis", to...
package imap import ( "context" "crypto/tls" "fmt" "regexp" "strings" "time" "golang.org/x/exp/slices" "github.com/mitchellh/mapstructure" "github.com/ovh/venom" "github.com/pkg/errors" "github.com/yesnault/go-imap/imap" ) const ( // Name for test imap Name = "imap" // imapClientTimeout represents the...
package request import "quan/model" type SysOperationRecordSearch struct { model.SysOperationRecord PageInfo }
package sudokuhistory import ( "errors" "github.com/jkomoros/sudoku" "github.com/jkomoros/sudoku/sdkconverter" "time" ) //Digest is an object representing the state of the model. Consists primarily //of a list of MoveGroupDigests. Suitable for being saved as json. type Digest struct { //Puzzle is the puzzle, enc...
package twitter import ( "crypto/hmac" "crypto/sha256" "encoding/base64" ) func (c *TwitterClient) CreateCRCToken(crcToken string) string { mac := hmac.New(sha256.New, []byte(c.envConfig.ConsumerSecret)) mac.Write([]byte(crcToken)) return "sha256=" + base64.StdEncoding.EncodeToString(mac.Sum(nil)) }
package cmd_test import ( "io/ioutil" "os" "path" "code.cloudfoundry.org/cfdev/cmd" "code.cloudfoundry.org/cfdev/config" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) type MockUI struct { WasCalledWith string } func (m *MockUI) Say(message string, args ...interface{}) { m.WasCalledWith = message ...
package vx /* #cgo CFLAGS: -std=c11 #cgo LDFLAGS: -lm #include <stdlib.h> */ import "C" import ( "math" "reflect" "unsafe" ) func AlignedAlloc(size int) []float32 { size_ := size size = align(size) ptr := C.aligned_alloc(32, (C.size_t)(C.sizeof_float*size)) hdr := reflect.SliceHeader{ Data: uintptr(unsafe.P...
/* ================================================================================== Copyright (c) 2019 AT&T Intellectual Property. Copyright (c) 2019 Nokia 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 co...
package main import ( "bytes" "encoding/binary" "fmt" ) //整形转换成字节 func IntToBytes(n int) []byte { x := int32(n) bytesBuffer := bytes.NewBuffer([]byte{}) binary.Write(bytesBuffer, binary.BigEndian, x) return bytesBuffer.Bytes() } //字节转换成整形 func BytesToInt(b []byte) int { bytesBuffer := bytes.NewBuffer(b) va...
package classic // Merge two sorted linked lists and return it as a new list func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { var head, p, np *ListNode p1, p2 := l1, l2 for p1 != nil && p2 != nil { if p1.Val < p2.Val { np = p1 p1 = p1.Next } else { np = p2 p2 = p2.Next } if p == nil ...
package main import ( "log" "os" "phonebook_rest_api/config" "phonebook_rest_api/routes" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/logger" "github.com/joho/godotenv" ) func setupRoutes(app *fiber.App) { api := app.Group("/api") rou...
package linter import ( "context" "testing" "github.com/suzuki/go-cmnt-eol-lint/src/env" ) func Test_Linter_LintFile(t *testing.T) { tests := map[string]struct { filename string expectedComments []string }{ "01_no_problem": { filename: "01_no_problem.go", expectedComments: []string{}...
package search import ( "testing" "math" "fmt" ) func TestSearch(t *testing.T) { x := []float64{0.1} direction := []float64{1} var eps float64 = 0.03 var min_y float64 test_cost_func := func(x []float64) (float64) { var y float64 y = math.Pow(x[0], 4) - 14 * math.Pow(x[0], 3) + 60 * math.Pow(x[0], 2)...
package pdns_api import ( "net/http" "github.com/jinzhu/gorm" "github.com/labstack/echo/v4" "github.com/pir5/pdns-api/model" ) // getRecords is getting records. // @Summary get records // @Description get records // @Security ID // @Security Secret // @Accept json // @Produce json // @Param id query int false ...
package handlers import ( "fmt" "net/url" "strings" "github.com/authelia/authelia/v4/internal/duo" "github.com/authelia/authelia/v4/internal/middlewares" "github.com/authelia/authelia/v4/internal/model" "github.com/authelia/authelia/v4/internal/session" "github.com/authelia/authelia/v4/internal/utils" ) // D...
package controllers import ( "sdrms/models" "encoding/json" ) type SystemLoginLogController struct { BaseController } func (c *SystemLoginLogController) Prepare() { //先执行 c.BaseController.Prepare() //如果一个Controller的多数Action都需要权限控制,则将验证放到Prepare c.checkAuthor("DataGrid") //如果一个Controller的所有Action都需要登录验证,则将验证...
package server import ( "encoding/json" "fmt" "net/http" "net/url" colly "github.com/gocolly/colly/v2" "github.com/guschnwg/player/pkg/shared" ) const baseURL = "https://www.beatport.com" // TestBeatport ... func TestBeatport(w http.ResponseWriter, r *http.Request) { enableCors(&w, r) query := r.URL.Query(...
package types import "encoding/json" type Result struct { Result []json.RawMessage `json:"result"` Count int `json:"count"` Cached bool `json:"cached"` HasMore bool `json:"hasMore"` Error bool `json:"error"` Code int `json:"code"` } ty...
package stage import "github.com/werf/werf/pkg/config" func GenerateImportsAfterSetupStage(imageBaseConfig *config.StapelImageBase, baseStageOptions *NewBaseStageOptions) *ImportsAfterSetupStage { imports := getImports(imageBaseConfig, &getImportsOptions{After: Setup}) if len(imports) != 0 { return newImportsAfte...
package logs import ( "github.com/profiralex/go-bootstrap-redis/pkg/config" log "github.com/sirupsen/logrus" ) func Init(cfg config.Config) { debugLevel, err := log.ParseLevel(cfg.AppConfig.DebugLevel) if err != nil { log.Warnf("Unknown debug level %s defaulting to warning level", cfg.AppConfig.DebugLevel) de...
package user import "errors" type UserId struct { value string } func NewUserId(value string) (*UserId, error) { for _, v := range []bool{ len(value) < 4, len(value) > 32, } { if v { return nil, errors.New("assertion error") } } return &UserId{value}, nil } func (u *UserId) Value() string { return ...
package main func distributeCandies(candies []int) int { candyKinds := 0 candyCount := make(map[int]int) for i := 0; i < len(candies); i++ { candyCount[candies[i]]++ if candyCount[candies[i]] == 1 { candyKinds++ } } if candyKinds > len(candies)>>1 { candyKinds = len(candies) >> 1 } return candyKinds ...
package main import ( "fmt" "github.com/stretchr/testify/require" "log" "strings" "testing" "time" ) func Test_Nas_Error(t *testing.T) { runOnlyInIntegrationTest("TEST_CLOUDFERRO") ferroTearDown() defer ferroTearDown() brokerd_launched, err := isBrokerdLaunched() if !brokerd_launched { fmt.Println("Thi...
package main import ( "fmt" "time" ) func main() { var ch = make(chan bool) go func() { select { case <-ch: fmt.Println("2 ") } }() fmt.Println("1 ") time.Sleep(2 * time.Second) ch <- true fmt.Println("3 ") }
package main type config struct { ip string port int }
/* * @lc app=leetcode.cn id=18 lang=golang * * [18] 四数之和 */ // @lc code=start package main import ( "fmt" "sort" ) func fourSum(nums []int, target int) [][]int { sort.Ints(nums) n := len(nums) res := [][]int{} for first := 0 ; first < n - 3 ; first++ { if first > 0 && nums[first] == nums[first-1] { co...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03400108 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.034.001.08 Document"` Message *CorporateActionInstructionStatusAdviceV08 `xml:"CorpActnInstrSt...
package problem0476 func findComplement(num int) int { mask := 1 << 30 for (num & mask) == 0 { mask >>= 1 } mask = mask<<1 - 1 return num ^ mask }
package main import "fmt" func main() { fmt.Println("f1") fmt.Println("f2") fmt.Println("f3") goto f6 fmt.Println("f4") fmt.Println("f5") f6: fmt.Println("f6") // loop: // for i := 0; i < 10; i++ { // fmt.Println(i) // if i == 2 { // goto loop // 这种直接goto到for循环 相当于重新开始循环 i :=0,而不像cotinue一样会从迭代循环变...
package coinswap import ( "fmt" "time" sdk "github.com/irisnet/irishub/types" ) // NewHandler returns a handler for "coinswap" type messages. func NewHandler(k Keeper) sdk.Handler { return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { switch msg := msg.(type) { case MsgSwapOrder: return HandleMsgSwapOrd...
package main import ( "encoding/json" "fmt" "html/template" "log" "net/http" "sort" "github.com/luno/moonbeam/resolver" "github.com/luno/moonbeam/storage" ) func render(t *template.Template, w http.ResponseWriter, data interface{}) { if err := t.Execute(w, data); err != nil { log.Printf("template error: %...
package _interface import ( "fmt" "testing" "time" ) type Programmer interface { WriteHelloWorld() string } type GoProgrammer struct { } func (g *GoProgrammer) WriteHelloWorld() string { return "fmt.Println(\"Hello World\")" } func TestClient(t *testing.T) { var p Programmer p = new(GoProgrammer) t.Log(p.W...
package riak import ( "errors" "github.com/cupcake/go-riak/pb" ) // A Riak link type Link struct { Bucket string Key string Tag string } // An object van have siblings that can each have their own content type Sibling struct { ContentType string Data []byte Links []Link Meta map[s...
package types import ( "math/big" sdk "github.com/irisnet/irishub/types" ) const RandPrec = 20 // the precision for generated random numbers // RNG is a random number generator type RNG interface { GetRand() sdk.Rat // interface which returns a random number between (0,1) } // PRNG represents a pseudo-random nu...
package main /** 面试题64. 求1+2+…+n 求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。 示例1: ``` 输入: n = 3 输出: 6 ``` 示例2: ``` 输入: n = 9 输出: 45 ``` 限制: - `1 <= n <= 10000` */ /** 一直想着递归时返回和,绕进去了没出来,其实还真是,在递归函数里面计算,在外部用个全局变量累加就可以了 */ func SumNums(n int) int { ans := 0 var sumR func(int) bool ...
package main import ( "bufio" "bytes" "log" "net/http" "os" "strconv" "strings" "time" "fmt" "flag" "errors" "github.com/BurntSushi/toml" "github.com/mattn/go-encoding" "golang.org/x/net/html" ) type Config struct { BaseUrl string FirstYear int SavePlace string } var ( sl = flag.Bool("...
package protobuf //Status should be in all responses. type Status struct { Error error }
package actions import ( "errors" "github.com/barrydev/api-3h-shop/src/factories" "github.com/barrydev/api-3h-shop/src/model" ) func GetCategoryById(categoryId int64) (*model.Category, error) { category, err := factories.FindCategoryById(categoryId) if err != nil { return nil, err } if category == nil { ...
// Copyright (c) 2012 The Gocov Authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, pub...
package main var dx []int var dy []int // DFS时判断访问坐标是否合法 func judge(A [][]int, x, y int) bool { if len(A) == 0 { return false } m, n := len(A), len(A[0]) if x < 0 || y < 0 || x >= m || y >= n { return false } if A[x][y] == 0 || A[x][y] == 2 { return false } return true } // 把第一个岛屿赋值为2 func DFS(A [][]in...
package main import "fmt" type Person struct { int string height float32 } func main() { p := Person{23, "Evan", 1.75} fmt.Println(p.int, p.string, p.height) fmt.Println(p) }
package models import ( "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func init() { beego.SetLogger("console", "") beego.SetLogFuncCall(true) beego.BeeLogger.SetLogFuncCallDepth(4) beego.Trace("init()") orm.Debug = true orm.RegisterDriver("mysql", o...
package main import ( "fmt" "log" "net/http" "os" "strings" "github.com/c-bata/go-prompt" "github.com/doctori/music-migrator/deezer" ) var s Spotify var d deezer.Deezer func mainCompleter(d prompt.Document) []prompt.Suggest { s := []prompt.Suggest{ {Text: "spotify", Description: "spotify related stuff"}, ...
package haproxyctl import ( "fmt" "reflect" "strconv" "strings" ) var ( truth_list = []string{"true", "1", "yes", "y", "on"} false_list = []string{"false", "0", "no", "n", "off"} bool_map map[string]bool ) func init() { bool_map = make(map[string]bool, 0) for _, k := range truth_list { bool_map[k] = tru...
package handlers import ( "log" "net/http" "github.com/rest_service_task/impl/errors" "github.com/rest_service_task/impl/structs" ) //swagger:parameters CreateUser type CreateUserParams struct { // Required: true // in: body Body structs.User } // swagger:route POST /create user CreateUser // Method for crea...
// Copyright 2015 The Chromium 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 bf import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestBitField(t *testing.T) { Convey("BitField", t, func() { bf :...
package cmd import ( "errors" "fmt" zabbix "github.com/canghai908/zabbix-go" _ "github.com/go-sql-driver/mysql" "github.com/google/uuid" _ "github.com/lib/pq" "github.com/manifoldco/promptui" "github.com/urfave/cli/v2" "gopkg.in/ini.v1" "os" "strconv" "strings" ) const qrencode = `########################...
package db_test import ( "testing" "bitbucket.org/matchmove/go-database" _ "github.com/erikstmartin/go-testdb" "github.com/jmoiron/sqlx" "github.com/stretchr/testify/assert" ) func TestNewDB(t *testing.T) { d, err := db.New("testdb", "") assert.Nil(t, err) assert.Equal(t, d.Driver, "testdb") assert.Equal(t...
package main import ( "fmt" "sort" "strconv" "strings" "github.com/bwmarrin/discordgo" ) // process commands that can only be run in dms func dmCommand(s *discordgo.Session, m *discordgo.MessageCreate, command string) { switch command { case "help": dmHelpCommand(s, m) case "ping": pingCommand(s, m) cas...
package cmd import ( "log" "net/http" ) func NewServer() *Server { return &Server{ mux: http.NewServeMux(), server: &http.Server{ Addr: ":8000", }, } } type Server struct { server *http.Server mux *http.ServeMux } func (s *Server) ListenAndServe() { s.routes() s.server.Handler = s.mux log.Fatal...
package main import ( "net" "fmt" // "path/filepath" ) func echoServer(c net.Conn) { for { // buf := make([]byte, 512) // nr, err := c.Read(buf) // if err != nil { // return // } // addr := filepath.Base(c.LocalAddr().String()) // extension := filepath.Ext(addr) // proc := addr[0 : len(addr)-len(extension...
package config import ( "html/template" "io" "net/http" "time" "github.com/gorilla/securecookie" "github.com/labstack/echo" "golang.org/x/crypto/bcrypt" ) type M map[string]interface{} type Renderer struct { template *template.Template debug bool location string } //secureCookie var sc = securecookie....
/* Copyright 2019 The Knative 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, soft...
/* package server когда нажали ентер клиент посылает сигнал серверу о том, что один игрок подключился. Тем временем на клиенте создаётся поле, но змеек ещё нет. Ждём ответ от сервера. Сервер принимает подключение, добавляет его в свой пул подключений и начинает ждать 30сек что бы подключился хотя бы ещё один чел. Тем в...
package cart type PromotionDiscount func(Cart) float64 func PriceWithPromotions(cart Cart, promotions []func(Cart) float64) float64 { total := PriceWithoutPromotions(cart) discount := 0.0 for _, f := range promotions { discount += f(cart) } return total - discount } func BeltAre15PercentOffIf2OrMoreTrouser...
/* Copyright 2015 Google Inc. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd */ package main import ( "flag" "fmt" "os" "os/signal" "syscall" "time" "github.com/google/cups-conne...
package main func convert(s string, numRows int) string { str := []byte(s) res := "" if numRows == 1 { return s } cycle := 2*numRows - 2 for i := 0; i < numRows; i++ { for j := 0; j+i < len(str); j += cycle { res += string(str[j+i]) if i != 0 && i != numRows-1 && j+cycle-i < len(str) { res += stri...
/* Copyright 2020 The SuperEdge 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...
/* package core модуль globals хранит объекты для общего доступа */ package game import ( "github.com/JoelOtter/termloop" ) // GameScreen глобальная переменная которая хранит основные объекты уровня // в начале игры мы передаём эту переменную в termloop и меняя сзначеия этой // переменной мы можем менять происходящ...
package payment import ( "github.com/gucastiliao/special-case-pattern/pkg/charge" "github.com/gucastiliao/special-case-pattern/pkg/model" ) type PaymentReceiver struct{} func (p PaymentReceiver) Charge(subscription model.Subscription) error { charge := charge.NewChargeFactory(subscription) return charge.Execute(...
package fuzzbuzz import ( "io/ioutil" "testing" ) func BenchmarkFirst(b *testing.B) { for i := 0; i < b.N; i++ { firstSolution(ioutil.Discard) } } func BenchmarkSecond(b *testing.B) { for i := 0; i < b.N; i++ { secondSolution(ioutil.Discard) } } func BenchmarkThird(b *testing.B) { for i := 0; i < b.N; i+...
package ac // https://leetcode-cn.com/problems/stream-of-characters/ type StreamChecker struct { root *Node current *Node } func Constructor(words []string) StreamChecker { root := Compile(words) return StreamChecker{root, root} } func (this *StreamChecker) Query(letter byte) bool { node := this.current f...
package models //1. やると決めたことを最後までやりきる //2. 無責任な人を見るとイライラする //3. 「〇〇すべき」という言葉をよく使っている //4. 厳しいしつけを受けてきた //5. わたしはホメ上手だと思う //6. 聞き役になることが多い //7. 困っている人をみるとなんとかしてあげたくなる //8. ボランティア活動などに参加するのが好き //9. 結果を予測して準備する //10.他の人はどうするだろう?と客観視する //11.物事を分析して、事実に基づいて考える //12.上手くいかない時でもあまりイライラしない //13.欲しいものは手に入れないと気が済まない //14.人のこと...
package main import ( "bufio" "github.com/codegangsta/cli" "io/ioutil" "log" "os" "path" "strings" "text/template" ) type EnumCase struct { Name string RawValue string } type EnumType struct { Name string Values []EnumCase Nested []EnumType } func parseFolder(filepath string) (EnumType, error) { ...
package config //软件状态机 var ( s_0_Init = StateAndInfo{ 0, "软件初始化状态", } s_1_Creating = StateAndInfo{ 1, "软件安装中", } s_2_Created = StateAndInfo{ 2, "软件已经安装", } s_3_Starting = StateAndInfo{ 3, "软件正在启动", } s_4_Started = StateAndInfo{ 4, "软件已经启动", } s_5_Offing = StateAndInfo{ 5, "软件正在关闭", } s_6_Offed...
package workflow import ( "time" "github.com/google/uuid" "github.com/pkg/errors" "github.com/yamil-rivera/flowit/internal/config" ) // Workflow is the data structure representing a single workflow instance type Workflow struct { ID string Preffix string Name string IsActive ...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //530. Minimum Absolute Difference in BST //Given a binary search tree with non-negative values, find the minimum absolute difference between values of...
package handler import ( "fmt" "github.com/gin-gonic/gin" "log" "net/http" "proxy_download/model" "strconv" ) func GroupDetail(context *gin.Context) { var group model.Group idString := context.Param("id") id, _ := strconv.Atoi(idString) groupDetail, err := group.Detail(id) if err != nil { fmt.Println("...
package gouldian_test import ( "testing" µ "github.com/fogfish/gouldian/v2" "github.com/fogfish/gouldian/v2/mock" "github.com/fogfish/it" ) func TestJWTLit(t *testing.T) { foo := mock.Endpoint( µ.GET( µ.URI(), µ.JWT(µ.Token.Sub, "sub"), ), ) success := mock.Input(mock.JWT(µ.Token{"sub": "sub"})) fa...
package model type Result struct { Status int64 Msg string Data interface{} } type VersionResult struct { Status bool `json:"status" description:"true 表示成功;false 表示失败"` Msg string `json:"msg" description:"status为false时的错误信息"` Data Version `json:"data" description:"版本信息"` } type VersionListResult ...
package main import ( "context" "encoding/base64" "flag" "io/ioutil" "os" "os/signal" "syscall" "time" //"github.com/gtfierro/xboswave/ingester/types" "github.com/immesys/wavemq/mqpb" logrus "github.com/sirupsen/logrus" "google.golang.org/grpc" ) func init() { logrus.SetFormatter(&logrus.TextFormatter{F...
package proxy import ( "log" "net/http" _ "net/http/pprof" "runtime" "time" ) func GoroNum(n int) { go func() { for _ = range time.Tick(time.Duration(n) * time.Second) { log.Println("#goroutines", runtime.NumGoroutine()) } }() } func PProfRun(addr string) { go func() { log.Println(http.ListenAndServ...
package store import ( "io" "mime/multipart" "os" "path/filepath" ) // Service is an interface that defines actions for storing files type Service interface { SaveFile(fileName string, file multipart.File) error } type serviceImpl struct { uploadDir string } // NewService creates new service for storing files ...
package service import ( "MI/models" "MI/pkg/cache" "MI/pkg/logger" "MI/utils/common" "MI/utils/response" "context" "fmt" "github.com/gin-gonic/gin" "strconv" ) func AddCart(c *gin.Context ,item models.Item){ cacheKey := fmt.Sprintf("cart:user:%s",item.Uid) //判断 cart:key在redis中是否已存在,商品不存在,新增该购物车,商品存在,商品数量...
package engine import ( "context" "sync" "time" "code.cloudfoundry.org/lager" "code.cloudfoundry.org/lager/lagerctx" "github.com/concourse/concourse/atc" "github.com/concourse/concourse/atc/db" "github.com/concourse/concourse/atc/exec" "github.com/concourse/concourse/atc/metric" ) //go:generate counterfeite...
package main import "fmt" import "time" //365.2545 // 2456668.43767 //The reference time used in the layouts is: //Mon Jan 2 15:04:05 MST 2006 //which is Unix time 1136239445. //calculate the Julian date, provided it's within 209 years of Jan 2, 2006. func Julian(t time.Time) float64 { // Julian date, in seconds, ...
package parser import ( "github.com/Spriithy/BPL/compiler/token" "github.com/Spriithy/BPL/compiler/ast" "fmt" "os" ) var prOps = map[string]struct { prec int rAssoc bool }{ "++" : {50, false}, "--" : {50, false}, "." : {40, false}, "[" : {40, false}, "!" : {30, true}, "~" : {30, true}, "-u" : {29, ...
package main import ( "sync" "time" ) var rwMu sync.RWMutex var count int // 死锁 //func main() { // // go StartHttpDebuger() // go RWA() // time.Sleep(2 * time.Second) // rwMu.Lock() // defer rwMu.Unlock() // count++ // fmt.Println(count) //} func RWA() { rwMu.RLock() defer rwMu.Unlock() RWB() } func RWB() { ...
package main import ( "fmt" "os" "github.com/isutare412/torbula" ) func main() { if len(os.Args) < 2 { fmt.Fprintf(os.Stderr, "usage: %s [setting.ini]\n", os.Args[0]) os.Exit(1) } var server *torbula.Server server, err := torbula.NewServer(os.Args[1]) if err != nil { fmt.Fprintf(os.Stderr, "on NewServ...
/* Usando uma literal composta: Crie um array que suporte 5 valores to tipo int Atribua valores aos seus índices Utilize range e demonstre os valores do array. Utilizando format printing, demonstre o tipo do array. */ package main import ( "fmt" ) func main() { listaDeInteiros := [5]int{ 1, 2, 3, 4, 5} fmt...
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is...
package config import ( "os" "os/signal" "syscall" ) // WaitSIGHUP blocks until a SIGHUP signal is received. func WaitSIGHUP() { ch := make(chan os.Signal, 1) signal.Notify(ch, os.Signal(syscall.SIGHUP)) <-ch }
package ldap import ( "log" "strings" "github.com/liut/staffio/pkg/models" ) var ( _ models.Authenticator = (*LDAPStore)(nil) _ models.StaffStore = (*LDAPStore)(nil) _ models.PasswordStore = (*LDAPStore)(nil) _ models.GroupStore = (*LDAPStore)(nil) ) type LDAPStore struct { sources []*ldapSource pag...
package storage import ( "fmt" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" log "code.google.com/p/log4go" "fairy/config" ) type ProductBrief struct { Product_id uint32 Product_name string Product_type uint32 price uint32 img s...
package main import ( "fmt" "io/ioutil" "os" "github.com/gocarina/gocsv" ) func WriteToFile(records []PaymentRecord) (*os.File, error) { f, err := ioutil.TempFile("./records", "record") if err != nil { return nil, fmt.Errorf("cannot create temp file: %v", err) } err = gocsv.MarshalFile(records, f) if err...
package main import ( "io/ioutil" "os" "path/filepath" "time" "github.com/therecipe/qt/core" "github.com/therecipe/qt/gui" "github.com/therecipe/qt/quick" "github.com/therecipe/qt/widgets" ) func displayWidgets() { //Label label := widgets.NewQLabel2("This Is A Label", nil, 0) label.Set...
package bca import ( "fmt" "net/url" ) type BalanceInformation struct { AccountDetailDataSuccess []AccountDetailDataSuccess `json:"AccountDetailDataSuccess"` AccountDetailDataFailed []AccountDetailDataFailed `json:"AccountDetailDataFailed"` } type AccountDetailDataSuccess struct { AccountNumber string `jso...
package sort // RadixSort 基数排序 func RadixSort(arr *[]int, maxNumber int) { buckets := make([][]int, 10) mod, dev := 10, 1 for i := 0; i < maxNumber; i, dev, mod = i+1, dev*10, mod*10 { for j := 0; j < len(*arr); j++ { bkPos := (*arr)[j] % mod / dev buckets[bkPos] = append(b...
package main import ( "fmt" "testing" ) func TestRepeatedString(t *testing.T) { testCases := []struct { s string n, want int64 }{ { s: "aba", n: 10, want: 7, }, { s: "a", n: 1000000000000, want: 1000000000000, }, { s: "epsxyyflvrrrxzvnoenvpegvuonodjoxfwdmcvw...
package ddl import ( "errors" "github.com/iftsoft/gopack/lla" "reflect" ) type ColumnMap map[string]string var ddlTableColumns map[string]ColumnMap func init() { ddlTableColumns = make(map[string]ColumnMap) } func RegisterObject(unit interface{}, table, alias string) { v := reflect.ValueOf(unit) if v.Kind() ...
package main import ( "context" "flag" "fmt" "net/http" "os" "strconv" "strings" "time" "github.com/adshao/go-binance/v2" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" log "github.com/sirupsen/logrus" ) const ( defaultUpdateInterval = "30...
package models import ( "github.com/jinzhu/gorm" ) // OrderHistory Model type OrderHistory struct { gorm.Model OrderID int `json:"order_id" gorm:"not null" binding:"required"` Status int `json:"status" gorm:"not null; type:tinyint" binding:"required"` Desc string `json:"desc" gorm:"type:text"` Order ...
package main import ( "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "regexp" "strings" "sync" "github.com/fsnotify/fsnotify" ) type watcherConfig struct { ReposRoot string `json:"reposRoot"` WatchPath string `json:"watchPath"` WatchRegexp string `json:"watchRegexp"` Execute s...
package po import ( "context" "encoding/json" "strconv" "time" "github.com/ChowRobin/fantim/model/vo" "github.com/ChowRobin/fantim/client" "github.com/jinzhu/gorm" ) type MessageRecord struct { Id int64 `gorm:"primary_key"` MsgId int64 `gorm:"column:msg_id"` Sender int64 `gorm:"column:sender"` Conv...
package settings import ( "testing" ) func Test_Setup(t *testing.T) { Setup() if AppCfg.Name != "gohelper" { t.Error("settings parse conf/app.conf AppCfg.Name != gohelper") } if DatabaseCfg.Type != "mysql" { t.Error("settings parse conf/app.conf DatabaseCfg.Type != mysql") } if DatabaseCfg.Host != "127....
// // Copyright 2020 IBM Corporation // // 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 ...
// Double-linked list // User adds listItem object into his structure // and uses structPtr() to get the pointer to his object by the pointer to listItem object. package cache import "unsafe" type listItem struct { next *listItem prev *listItem } // initialize list func listInit(l *listItem) { l.next = l l.pre...
/* * Copyright 2017 StreamSets 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...
package server import ( "encoding/json" "github.com/dublour/genesis_se_task3/pkg/binance" "github.com/dublour/genesis_se_task3/pkg/model" "log" "net/http" "os" ) func Respond(w http.ResponseWriter, r *http.Request, httpStatus int, data map[string]interface{}) { w.Header().Add("Content-Type", "application/json"...