text
stringlengths
11
4.05M
package main /* 123 ++ package dùng để nhóm 1 hoặc nhiều tập tin có liên quan đến nhau ++ tên package sử dụng in thường, định nghĩa ở đầu chương trình ++ tập để chạy chương trình thì tên là package main, đồn thời phải khởi tạp func main trình Go compiler sẽ tìm func main để run */ /* ++ import package để sử dụng 1 p...
package ch06 func BubbleSort(arr []int, comp func(int, int) bool) { for i := 0; i < len(arr) - 1 ; i++ { for j := 0; j < len(arr) - 1 - i - 1; j++ { if comp(arr[j], arr[j+1]) { // swap arr[j+1], arr[j] = arr[j], arr[j+1] } } } }
package backup import ( "context" "github.com/cbochs/spotify-backup-api/schema" "github.com/cbochs/spotify-backup-api/spotify" "github.com/cbochs/spotify-backup-api/spotify/options" "go.mongodb.org/mongo-driver/bson/primitive" ) type Client struct { ID primitive.ObjectID User schema.SpotifyUser servi...
package main import ( "fmt" "os" "strings" "time" "encoding/json" "github.com/kazu69/hosts_file_manager" "github.com/ttacon/chalk" "github.com/urfave/cli" ) var ( version string ) func main() { hfm, err := hfm.NewHosts() if err != nil { fmt.Println(err) os.Exit(1) } app := cli.NewApp() app.Nam...
package db import ( "github.com/evansmwendwa/uxp/model" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" // Required for sqlite connection ) var session *gorm.DB var err error func init() { db, err := gorm.Open("sqlite3", "data/data.sqlite") if err != nil { panic("DB connection error") } ...
package gormSupported import ( "github.com/jinzhu/gorm" "github.com/mukesh0513/RxSecure/internal/model" ) type GormConnection struct{} var ( gormConn *gorm.DB //GormConnProvider sqlData.ISqlDatabase ) func Initialize(db *gorm.DB, logging bool) { if gormConn == nil { gormConn = db //GormConnProvider...
package routers import ( "bubble/controller" "github.com/gin-gonic/gin" ) func SetRouters() *gin.Engine { r := gin.Default() //静态变量设置 r.Static("/static","static") //模板设置 r.LoadHTMLGlob("template/*") r.GET("/", controller.IndexHandle) //v1 设置访问前缀 v1Group := r.Group("v1") { //代办事项 //添加 v1Group.POST("/...
package wire import ( "net/url" "sort" "strings" "fmt" "net/http" ) type Mapping struct { field *string required bool } func Required(field *string) *Mapping { return &Mapping{ field: field, required: true, } } func Optional(field *string) *Mapping { return &Mapping{ field: field, require...
package agency import ( "github.com/bububa/oppo-omni/core" "github.com/bububa/oppo-omni/model" "github.com/bububa/oppo-omni/model/communal/agency" ) // 代理商余额查询 func Balance(clt *core.SDKClient) ([]agency.BalanceAccount, error) { var req model.BaseRequest req.SetResourceName("communal") req.SetResourceAction("ag...
package main import "fmt" func main() { a := "aa" b := "*" fmt.Println(isMatch(a, b)) a = "zacabz" b = "*a?b*" fmt.Println(isMatch(a, b)) a = "aa" b = "a" fmt.Println(isMatch(a, b)) a = "aaabbbaabaaaaababaabaaabbabbbbbbbbaabababbabbbaaaabaa" b = "a*******b" fmt.Println(isMatch(a, b)) a = "babbbbaabababaa...
package _862_Shortest_Subarray_with_Sum_at_Least_K import "testing" func TestShortestSubarray(t *testing.T) { var res int if res = shortestSubarray([]int{1}, 1); res != 1 { t.Errorf("wrong res=%d", res) } }
package utils import ( "path/filepath" "reflect" "sort" ) // Get the steps-th parent directory of fullPath. func GetParentDir(fullPath string, steps int) string { fullPath = filepath.Clean(fullPath) for ; steps > 0; steps-- { fullPath = filepath.Dir(fullPath) } return fullPath } type mapKeyWithString struct...
package piper import ( "context" "errors" "fmt" "math/rand" "strconv" "testing" ) type testBatchExecAllSucceedFn struct { } func (fn *testBatchExecAllSucceedFn) Execute(ctx context.Context, datum []DataIF) (map[string]error, error) { errorsMap := make(map[string]error) for _, data := range datum { td := da...
package route import ( "bytes" "fmt" "net/http" "path/filepath" "text/template" "github.com/Sirupsen/logrus" "github.com/gorilla/mux" ) const ( pathStatic = "/_static" pathWS = "/_ws" pathDownload = "/_dl" ) var ( indexTemplate = template.Must(template.ParseFiles("./client/dist/index.html")) log...
package article import ( "context" "database/sql" "time" ) type Article struct { Id string `db:"id"` Body string `db:"body"` Title string `db:"title"` Preface string `db:"preface"` UserId string `db:"user_id"` CreatedAt time.Time `db:"created_at"` Update...
package common import "encoding/json" func ToJson(v interface{}) string { bs, _ := json.Marshal(v) return string(bs) }
package main import ( "fmt" ) func dropEmety(s []string) []string { var count int for _, v := range s { if v != "" { s[count] = v count++ } } return s[:count] } func dropSame(s []string) (k []string) { var lk int = 1 k = make([]string, len(s)) for _, v := range s { if v != k[lk-1] { k[lk] = v ...
// 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...
package main import "fmt" func hello() { fmt.Print("hello ") } func world() { fmt.Println("world") } func main() { defer world() // defers the function right before the main exits (in this case) hello() }
// Copyright 2016 Lennart Espe. 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 lib generates and fetches hash patches. package lib import ( "bytes" "errors" "io/ioutil" "os" "path/filepath" "runtime" "github.com/lnsp/g...
package usecase import ( "github.com/taniwhy/mochi-match-rest/domain/models" "github.com/taniwhy/mochi-match-rest/domain/repository" ) // UserDetailUseCase : type UserDetailUseCase interface { FindUserDetailByID(id int64) (*models.UserDetail, error) CreateUserDetail(userDetail *models.UserDetail) error UpdateUse...
package problem0079 func exist(board [][]byte, word string) bool { if len(word) == 0 { return true } visited := make([][]bool, len(board)) for i := 0; i < len(board); i++ { visited[i] = make([]bool, len(board[i])) } for i := 0; i < len(board); i++ { for j := 0; j < len(board[i]); j++ { if dfs(board, wor...
package worker // InitWorker is the entry point of init the worker, during which multiple components of // worker need to be initialized. func InitWorker(filePath string) error { if err := InitConfig(filePath); err != nil { return err } if err := InitRegister(); err != nil { return err } if err := InitLogSi...
/* * Copyright 2019-present Open Networking Foundation * 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 ...
package json import ( "testing" "github.com/polydawn/refmt/tok/fixtures" ) func testComposite(t *testing.T) { t.Run("array nested in map as non-first and final entry", func(t *testing.T) { seq := fixtures.SequenceMap["array nested in map as non-first and final entry"] checkCanonical(t, seq, `{"k1":"v1","ke":[...
package util import ( "github.com/mndrix/tap-go" rspec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/cgroups" ) // ValidateLinuxResourcesMemory validates linux.resources.memory. func ValidateLinuxResourcesMemory(config *rspec.Spec, t *tap.T, state *rspec.State) error { ...
package routers import ( "github.com/astaxie/beego" "goWebDemo/controllers" ) func init() { beego.Router("/", &controllers.HomeController{}, "Get:Index") beego.Router("/menu", &controllers.MenuController{}, "Get:Index") beego.Router("/menu/list", &controllers.MenuController{}, "*:List") beego.Router("/menu/edi...
package _56_Merge_Intervals import ( "fmt" "testing" ) func TestMerge(t *testing.T) { var ( intervals, ret [][]int ) intervals = [][]int{{1, 3}, {2, 6}, {8, 10}, {15, 18}} ret = merge(intervals) fmt.Println(ret) intervals = [][]int{{1, 4}, {4, 5}} ret = merge(intervals) fmt.Println(ret) intervals = [][...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package main import ( "flag" "github.com/fighterlyt/file2go/compress" ) var ( file = "" packageName = "" targetFileName = "file2go.go" ) func init() { flag.StringVar(&file,"file", file, "数据文件名") flag.StringVar(&packageName,"package", packageName, "包名") flag.StringVar(&targetFileName,"target", ta...
package export import ( "encoding/json" "io" "os" "github.com/Zenika/marcel/api/db" ) func export(fetch func() (interface{}, error), outputFile string, pretty bool) error { if err := db.OpenRO(); err != nil { return err } defer db.Close() var w io.WriteCloser if outputFile == "" { w = os.Stdout } else...
package main import ( "bytes" "crypto/md5" "crypto/sha1" "crypto/sha256" "encoding/hex" "fmt" "io" "log" "os" "path/filepath" "strings" "golang.org/x/crypto/openpgp" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/clearsign" "golang.org/x/crypto/openpgp/packet" ) // createRelease scan...
package main import ( "fmt" "github.com/gin-gonic/gin" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "net/http" ) var ( DB *gorm.DB ) func initMySQL() (err error) { dsn := "root:123456@tcp(192.168.99.100:13306)/db1?charset=utf8mb4&parseTime=True&loc=Local" DB ,err = gorm.Open("mysql",dsn...
package main import ( "flag" "github.com/a8uhnf/suich/cmd" ) func main() { flag.Parse() c := cmd.RootCmd() if err := c.Execute(); err != nil { panic(err) } }
// Copyright 2011 The Go Authors. All rights reserved. // Copyright 2011 ThePiachu. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bitecdsa import ( "crypto/rand" "encoding/base64" "math/big" "testing" "github.com/njones/bitco...
package main import ( "fmt" "math/rand" "os" "os/exec" "time" ) const ( width = 80 height = 15 ) // Universe is a type which holds a 2d field of cells. // Each cell will be either dead(false) or alive(true) type Universe [][]bool // NewUniverse creates a Universe with heigth rows and width columns per row f...
package models import ( "strings" ) // DatabaseModel represent the config for a single model that can be written to the DB. type DatabaseModel struct { configFile string createScript string constraintScript string insertScript string } // ModelConfig Is the pre-dialect creation scripts for a given...
package client import ( "github.com/wish/ctl/pkg/client/types" appsv1 "k8s.io/api/apps/v1" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" // describeversioned "k8s.io/kubectl/pkg/describe/versioned" "fmt" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/kubectl/pkg/describe" "strings" ) // Helper ...
package flow import ( "testing" . "github.com/BaritoLog/go-boilerplate/testkit" "github.com/BaritoLog/instru" ) func ResetApplicationSecretCollection() { instru.Metric("application_group").Put("app_secrets", nil) } func TestContains_NotMatch(t *testing.T) { given := []string{"a", "b"} exist := Contains(given,...
package main import ( "bufio" "fmt" "math/big" "os" ) func main() { var reader = bufio.NewReader(os.Stdin) var n big.Int fmt.Fscan(reader, &n) divisor := big.NewInt(20000303) ret := new(big.Int) ret = ret.Mod(&n, divisor) fmt.Println(ret) }
package handler import ( "context" "path/filepath" "testing" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/subscription/v1" jinmuidpb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1" "github.com/micro/go-micro/v2/client" "github.com/stretchr/testify/assert" "github.com/stre...
package image import ( "encoding/base64" "testing" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" aiv1beta1 "github.com/openshift/assisted-service/api/v1beta1" "github.com/openshift/assisted-service/models" hivev1 "github.com/openshift/hive/apis/hive/v1" "github.com/openshift/installer/pkg/asse...
package config import ( "os" "path/filepath" "github.com/hashicorp/go-multierror" "gopkg.in/yaml.v2" ) const ( lockFileName = "mona.lock" lockFilePerm = 0644 ) type ( // The LockFile type represents the structure of a lock file, it stores the project name, // version and the last build hashes used for each ...
package mock import ( "fmt" ) // MockTask holds the attributes needed to perform unit of work type MockTask struct { id int writerID int } // New creates MockTask object, takes a producer id func New(taskID, writerID int) *MockTask { return &MockTask{ id: taskID, writerID: writerID, } } // Iden...
package main import ( "encoding/json" "log" "math/rand" "net" "os" "github.com/nsf/termbox-go" ) var AI_DISPLAY_ON = true type AIPlayer struct { arena [][]bool prev Move display Display } func NewAI() (AI AIPlayer) { AI.arena = buildArena() return AI } func (ai *AIPlayer) ReadState(conn net.Conn) ...
// 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 in ...
package main import ( "log" "net" ) // Controller is an interface representing a controller that can handle incoming events // and add new clients type Controller interface { HandleEvent(string) error Reset() AddUserClient(UserClient) } // ForwarderController connects the domain model and the notification logic...
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "root:ResAdmin14@tcp(127.0.0.1:3306)/sakila") if err != nil { panic(err.Error()) } // defer the close till after the main function has finished // executing defer db.Close() rows, e...
package app import ( "github.com/martini-contrib/render" "github.com/martini-contrib/sessions" ) func homepage(r render.Render, s sessions.Session) { user := s.Get("user") if user == nil { r.Redirect("/login") return } r.Redirect("/dashboard") } func dashboard(r render.Render) { r.HTML(200, "dashboard", n...
package basic import ( "fmt" ) func bitOperation() { var a uint8 = 0x82 var b uint8 = 0x02 fmt.Printf("%08b [A]\n", a) fmt.Printf("%08b [B]\n", b) fmt.Printf("%08b (NOT B)\n", ^b) // ^ 即取反 /* 异或运算, 两个不一样才为1 */ fmt.Printf("%08b ^ %08b = %08b [B XOR 0xff]\n", b, 0xff, b^0xff)...
// +build !windows package dht import "syscall" func curFileLimit() uint64 { var n syscall.Rlimit syscall.Getrlimit(syscall.RLIMIT_NOFILE, &n) // cast because some platforms use int64 (e.g., freebsd) return uint64(n.Cur) }
package message import ( "bytes" "encoding/gob" "github.com/hashicorp/memberlist" "log" ) type BroadcastMsg struct { Msg P2PMessage } func (bm BroadcastMsg) Finished() { } func (bm BroadcastMsg) Invalidates(b memberlist.Broadcast) bool { // todo figure out what that does return false } func (bm BroadcastMsg...
package main import ( "github.com/MathisBurger/yb-http/config" "github.com/MathisBurger/yb-http/installation" "github.com/MathisBurger/yb-http/routing" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/logger" ) func main() { installation.Install() config.LoadConfigurations() app := fiber...
// Author: Sankar <sankar.curiosity@gmail.com> // Distributed under Creative Commons Zero License - Public Domain // For more information see LICENSE file package main import ( "bufio" "fmt" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) const usage = `Usage: cla...
// Copyright 2020, Jeff Alder // // 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 a...
package glc import ( "fmt" "io/ioutil" "os" "runtime" "strings" "time" "github.com/golang/glog" ) // exit status of cleaner routine. var status = true // exit status of GLC. var exit = false // GLC define the glog cleaner options: // // path - Log files will be clean to this directory // prefix ...
package trycopy import ( "fmt" ) func init() { fmt.Println("package trycopy init()") } func countries() []string { countries := []string{"USA", "Singapore", "Germany", "India", "Australia"} neededCountries := countries[:len(countries)-2] countriesCpy := make([]string, len(neededCountries)) copy(countriesCpy, n...
package common // Abs : 绝对值 func Abs(a int) int { if a < 0 { return -a } return a } // Clamp : 范围限制 func Clamp(v, min, max int) int { if v < min { return min } if v > max { return max } return v } // Sign : 根据输入的正负情况返回 -1, 0, 1 func Sign(a int) int { if a < 0 { return -1 } if a > 0 { return 1 }...
package core import ( "fmt" "math" "pmvs/featdetect" "sort" "gonum.org/v1/gonum/mat" ) func StartMatching() { fmt.Println("Initial Matching...") for id, photo := range imgsManager.Photos { num := 0 relevantImgs := getRelevantImages(id) for _, featPool := range photo.Feats { for _, feat := range feat...
package common import ( "encoding/json" "os" ) type configuration struct { Lang string `json:"lang"` Debug bool `json:"debug"` Address string `json:"address"` Port int `json:"port"` Rpc string `json:"rpc"` ReadTimeout int64 `json:"readT...
// Copyright (C) 2019 Cisco Systems 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 srapi import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" ) func GetGameByID(id string) (*Game, error) { resp, err := http.Get(fmt.Sprintf("https://www.speedrun.com/api/v1/games/%s", id)) if err != nil { return nil, err } defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) ...
package bucket import ( "container/list" "fmt" "sync" "time" ) // TokenBucket represents a token bucket // (https://en.wikipedia.org/wiki/Token_bucket) which based on multi goroutines, // and is safe to use under concurrency environments. type TokenBucket struct { interval time.Duration ticker ...
package log_test import ( "Edwardz43/tgbot/log" "testing" "time" "github.com/stretchr/testify/assert" ) func TestEmitThenReturnSuccess(t *testing.T) { c := &log.Content{ Level: "Info", Message: "Test ES Log", Date: time.Now(), Caller: "zaplogger/zaplogger.go:104", } err := log.Emit(c) assert.Ni...
// Copyright 2019 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 osbuild2 // Options for the org.osbuild.ostree.pull stage. type OSTreePullStageOptions struct { // Location of the ostree repo Repo string `json:"repo"` } func (OSTreePullStageOptions) isStageOptions() {} type OSTreePullStageInput struct { inputCommon References OSTreePullStageReferences `json:"reference...
// +build !boltdb package model func getArtistCount() int { return len(db) } func getArtistForID(ID int) *Artist { return db[ID] } func GetArtistForName(name string) *Artist { for _, artist := range db { if artist.Name == name { return artist } } return nil } func getAlbumCount() i...
package main import ( "database/sql" "fmt" "os" "path/filepath" "time" _ "github.com/go-sql-driver/mysql" ) var db *sql.DB func dbConnect(dbUser, dbPass, dbName string) { var err error db, err = sql.Open("mysql", fmt.Sprintf("%s:%s@/%s", dbUser, dbPass, dbName)) checkErr(err) db.SetConnMaxLifetime(time.M...
package field import "errors" const ( rowID = 1 fullpathID = 2 locationID = 3 filenameID = 4 titleID = 6 artistID = 7 albumID = 8 genreID = 9 lengthID = 10 bitrateID = 13 bpmID = 15 commentID = 17 groupingID = 19 remixerID = 20 labelID = 21 composerID = 22 ...
/* Copyright 2016 Manav Bhatia 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 distri...
package raffle import ( "github.com/avecost/promov/db" ) type NBRaffle struct { Id int Cardno string Terminal string Provider string Outlet string Game string JackpotAt string Cashier string JackpotAmt float32 } func GetAllPendingNonBaccaratResultsByDate(db *db.DB, dateTo stri...
package base import ( "container/heap" "gonum.org/v1/gonum/floats" "sort" ) // Indexer manages the map between sparse IDs and dense indices. A sparse ID is // a user ID or item ID. The dense index is the internal user index or item index // optimized for faster parameter access and less memory usage. type Indexer ...
package Services import ( "github.com/kylesliu/gin-demo/App/Extensions/Crypto" "github.com/kylesliu/gin-demo/Bootstrap/config" ) // 加密 func Encryption(str string) string { key := config.AppConfig.EncryptKey res := Crypto.EncryptDES_ECB(str, key) return res } // 解密 func Decryption(str string) string { key := co...
package ibmcloud import ( "context" "github.com/openshift/installer/pkg/asset/installconfig/ibmcloud" ) // AvailabilityZones returns a list of supported zones for the specified region. func AvailabilityZones(region string) ([]string, error) { ctx := context.TODO() client, err := ibmcloud.NewClient() if err != ...
// Copyright 2021 The image-cloner 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 o...
package entity import "github.com/jinzhu/gorm" // PostとImageの中間テーブル type PostImage struct { gorm.Model //ID, CreatedAt, UpdatedAt, DeletedAtを自動で定義する PostId uint `gorm:"type:int; not null"` Position int `gorm:"type:int; default:0 not null"` // FIXME: 少し書いているけど、この定義はまだdb処理を追加していません。後日改修予定 ImageId uint...
package p07 func selfDividingNumbers(left int, right int) []int { ret := make([]int, 0) for i := left; i <= right; i++ { if isSelfDividing(i) { ret = append(ret, i) } } return ret } func isSelfDividing(n int) bool { m := n for n != 0 { d := n % 10 if d == 0 { return false } if m%d != 0 { re...
package models import ( "github.com/astaxie/beego/orm" "strconv" "time" "tokensky_bg_admin/common" "tokensky_bg_admin/conf" "tokensky_bg_admin/utils" ) //查询的类 type HashrateSendBalanceRecordParam struct { BaseQueryParam StartTime int64 `json:"startTime"` //开始时间 EndTime int64 `json:"endTime"` //截止时间 Tre...
// Copyright 2019 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 puzzle import ( "testing" ) func TestSetPossibilities(t *testing.T) { puzzle := CreateTestPuzzleEasy() puzzle = puzzle.CalculatePossibilities() var set Set = puzzle[0] tables := []struct { index int possible bool }{ {0, true}, {1, true}, {2, true}, {3, true}, {4, true}, {5, true}, ...
package main import ( "flag" "fmt" "time" ) var period = flag.Duration("period", 1*time.Second, "sleep period") func main() { flag.Parse() fmt.Printf("Sleeping for %v ... ", *period) time.Sleep(*period) fmt.Println() } /* 注意flag的用法 package flag // Value is the interface to the value stored in a flag type ...
package Core import "com/pdool/DataStruct" type PropertyManager struct { guid GUID props DataStruct.Dictionary } // 生成一个属性管理器 func NewPropertyManager(guid GUID) *PropertyManager { pMgr := new(PropertyManager) pMgr.guid = guid pMgr.props = DataStruct.Dictionary{} return pMgr } // 添加一个属性 func (p *PropertyManag...
package main import ( "context" api "github.com/micro/go-api/proto" "github.com/micro/go-micro/errors" "encoding/json" "strings" ) type Handler struct { } func(h *Handler) Hello(ctx context.Context,req *api.Request,resp *api.Response) (error) { name, ok := req.Get["name"] if !ok || len(name.Values) == 0 { ...
/* * Copyright (c) 2014-2015, Yawning Angel <yawning at torproject dot org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyr...
package main import ( "fmt" "io" "log" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { fmt.Printf("%+v", r) _, err := io.WriteString(w, "Hello world!") if err != nil { panic(err) } } func main() { http.HandleFunc("/hello", hello) fs := http.FileServer(http.Dir("static")) http.Handle("...
package wphash import ( "testing" "github.com/stretchr/testify/assert" ) func TestCheckWordPressPasswordHash(t *testing.T) { // true case 123456 -> $P$BmIaPlVaAl6kEsffVZGdASCVH.i1cZ0 ret := CheckWordPressPasswordHash("123456", "$P$BmIaPlVaAl6kEsffVZGdASCVH.i1cZ0") assert.Equal(t, true, ret) // false case 12345...
package ksqlparser import ( "fmt" "strings" ) func (p *parser) peek(reservedWords ...string) string { peeked, _ := p.peekWithLength(reservedWords...) return peeked } func (p *parser) pop(reservedWords ...string) string { peeked, l := p.peekWithLength(reservedWords...) p.i += l p.popWhitespace() return peeked...
package main /* 事件驱动调度 */ import ( "fmt" "time" "sync" ) type eventMap struct { index int length int bitmap []int ticker *time.Ticker mux sync.Mutex } func (s *eventMap) set(index int) { word, bit := index/32, uint(index%32) s.lock() s.bitmap[word] |= 1 << bit } func (s *eventMap) clear(index int) {...
package account import ( "core/positions" "errors" "qutils/coder" ) //Ruturn user object based on login and password func logInAccount(credential LoginRequest) *Account { chekInitialization() keys := map[string]interface{}{ "email": credential.Email, "password": coder.EncodeSha1(credential.Password), } ...
package pgsql import ( "database/sql" "database/sql/driver" "encoding/json" ) // JSON returns a value that implements both the driver.Valuer and sql.Scanner // interfaces. The driver.Valuer produces a PostgreSQL json(b) from the given val // and the sql.Scanner unmarshals a PostgreSQL json(b) into the given val. f...
package routers import ( "encoding/json" "net/http" "github.com/rodzy/flash/db" "github.com/rodzy/flash/models" ) //ModifyUserInfo our method to env the new user info func ModifyUserInfo(w http.ResponseWriter,r *http.Request) { var user models.User err:=json.NewDecoder(r.Body).Decode(&user) if err != nil { ...
// Copyright 2020 // // 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, softwar...
package crypto import ( "testing" ) func TestPKCS5Padding(t *testing.T) { padding := &PKCS5Padding{ BlockSize: 15, } data := []byte("0123456789") pd := padding.Padding(data) t.Log(data, pd) upd := padding.UnPadding(pd) t.Log(upd) if string(data) != string(upd) { t.Error(upd) } }
package weather import ( forecast "github.com/mlbright/forecast/v2" "log" "os" "strconv" "time" ) var apiKey string func init() { envVar := "FORECAST_API_KEY" apiKey = os.Getenv(envVar) if apiKey == "" { log.Fatalf("Missing value for environment variable %s. See https://developer.forecast.io.\n", envVar) ...
package handler import ( "backend/mux" "backend/nullable" "encoding/json" "fmt" "net/http" "strconv" ) func (h *Handler) GetUser(writer http.ResponseWriter, request *http.Request) { vals := mux.GetPathVals(request) userID, err := strconv.Atoi(vals["uid"]) if err != nil { writer.WriteHeader(http.StatusBadRe...
package main import ( "container/ring" "context" "crypto/md5" "fmt" "os" "os/signal" "strconv" "sync" randomdata "github.com/Pallinder/go-randomdata" ) func inserisci(num int, wg *sync.WaitGroup) { defer wg.Done() defer close(in) for n := 1; n <= num; n++ { aggettivo := randomdata.Adjective() //fmt.P...
package ast import ( "log" "strings" "github.com/emptyland/akino/sql/token" ) type Node interface { Pos() int End() int } type Command interface { Node } type Expr interface { Node } type NameRef struct { First string Second string } func (self *NameRef) Table() string { if self.Second == "" { retur...
// Copyright 2019 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 main import ( "encoding/json" "fmt" "sync" "github.com/couchbaselabs/go-couchbase" ) type Event struct { Type string `json:"type"` Name string `json:"name"` Likes int `json:"likes"` } func NewEvent(name string) *Event { return &Event{"event", name, 0} } func NewEventJSON(jsonbytes []byte) (eve...
package cache import ( "github.com/go-redis/redis" ) // cache caches the frames using redis // specs: 64MB cache size var client *redis.Client func init() { client = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", // no password set DB: 0, // use default DB }) pong, err :=...