text
stringlengths
11
4.05M
package consts var SmsBizType_name = map[int32]string{ 0: "Login", 1: "Register", 2: "Edit_Password", 3: "Forget_Password", 4: "Upgrade_Permit", 5: "Upgrade_Audite", 6: "Upgrade_Success", 7: "Upgrade_Omit", 8: "Modify_Mobile", 9: "Upgrade_Reward_Frozen", 10: "Upgrade_Reward_Unfreeze", 11: "Wallet...
package main import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" "sync" "time" ) var db *sql.DB var err error func init() { db, err = sql.Open("mysql", "root:123456@tcp(192.168.1.129:30006)/test?charset=utf8") if err != nil { log.Fatalf("db conn err ----- ", err) } db.Ping(...
package server import ( "fmt" lru "github.com/hashicorp/golang-lru" "github.com/miekg/dns" "time" ) const CACHE_SIZE = 2048 const MIN_TTL = 30 var cache, _ = lru.New2Q(CACHE_SIZE) // This is thread-safe type CachedItem struct { res *dns.Msg expires time.Time } func setCache(req *dns.Msg, res *dns.Msg) { ...
package memstorage import ( "context" "errors" "github.com/SmitSheth/Mini-twitter/internal/post" pb "github.com/SmitSheth/Mini-twitter/internal/post/postpb" ) type postRepository struct { storage *postStorage } func GetPostRepository() post.PostRepository { return &postRepository{PostStorage} } func NewPostR...
package eddb import ( "bufio" "bytes" "compress/zlib" "context" "encoding/json" "errors" "github.com/go-zeromq/zmq4" "goed/edGalaxy" "io" "log" "os" "sort" "strings" "sync/atomic" "time" ) const ( SCHEMA_KEY = "$schemaRef" RELAY = "tcp://eddn.edcd.io:9500" cmd_exit = 0 cmd_backup ...
package main import ( "bufio" "fmt" "log" "os" "strconv" "time" ) type numbers []int var preamble = 25 func main() { start := time.Now() fmt.Printf("Result is %v \n", run()) log.Printf("Code took %s", time.Since(start)) } func run() int { nums := numbers{} f, err := os.Open("input.txt") if err != n...
package app import ( "github.com/jinzhu/gorm" ) // State contains the current application state type State struct { Database *gorm.DB }
/* * Copyright (C) 2018 eeonevision * * 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, publish...
package htmlparser import ( "fmt" "log" "net/http" "strings" "sync" "time" ) // SiteMap is a struct which stores all // the info about the website type SiteMap struct { Domain string PageCount int BrokenLinks int Pages map[string][]*Link } // Page is a struct used to store the details // of an...
package capability // import ( // "reflect" // "strings" // "testing" // dynatracev1beta1 "github.com/Dynatrace/dynatrace-operator/src/api/v1beta1" // "github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/activegate/consts" // v1 "k8s.io/api/core/v1" // ) // func Test_capabilityBase_Properties(t *t...
/** * Copyright 2015 Qadium, 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 t...
/* * @lc app=leetcode id=120 lang=golang * * [120] Triangle * * https://leetcode.com/problems/triangle/description/ * * algorithms * Medium (43.54%) * Likes: 2085 * Dislikes: 246 * Total Accepted: 252.4K * Total Submissions: 572.3K * Testcase Example: '[[2],[3,4],[6,5,7],[4,1,8,3]]' * * Given a tr...
// +build cgo package main import ( _ "github.com/elastic/apm-agent-go/module/apmsql/sqlite3" )
package main import ( "encoding/json" "github.com/julienschmidt/httprouter" "io" "io/ioutil" "net/http" "video_server/api/dbops" "video_server/api/defs" "video_server/api/session" "video_server/api/utils" ) func CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params){ res,_ := ioutil.ReadAll(...
package p_00401_00500 // 404. Sum of Left Leaves, https://leetcode.com/problems/sum-of-left-leaves/ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func sumO...
package main import ( "fmt" "sync" "time" ) func main() { data := make([]int, 0, 10) dataCh := make(chan []int) wg := sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() r := <-dataCh fmt.Printf("%p\n", r) fmt.Println(r) time.Sleep(2 * time.Second) fmt.Println(r) }() fmt.Printf("%p\n", dat...
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package command type CommandList struct { Project struct { List ProjectList `command:"list" description:"list all accessable projects"` } `command:"project" description:"project related commands"` User struct { List UserList `command:"list" description:"list all known users"` Add UserAdd `command:"add" desc...
package poller import ( "context" "time" "github.com/gbolo/vsummary/common" "github.com/vmware/govmomi/view" "github.com/vmware/govmomi/vim25/mo" ) func (p *Poller) GetDatastores() (list []common.Datastore, err error) { // log time on debug defer common.ExecutionTime(time.Now(), "pollDatastores") // Create...
package main import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/google/logger" "github.com/gorilla/mux" ) func TestMain(m *testing.M) { setup() code := m.Run() tearDown() os.Exit(code) } var handler *Handler func setup() { ...
package store import ( "context" "github.com/RaniSputnik/ok/api/model" ) type Player interface { GetPlayer(ctx context.Context, username string) (*model.Player, error) SavePlayer(ctx context.Context, input *model.Player) error }
package lc import "sort" // Time: O(n logn) // Benchmark: 80ms 6.3mb | 9% 16% func maximumProductB(nums []int) int { sort.Ints(nums) left := nums[0] * nums[1] * nums[len(nums)-1] right := nums[len(nums)-1] * nums[len(nums)-2] * nums[len(nums)-3] if left > right { return left } return right }
//写微博发出每日的逾期信息 package main import ( "./dao" "encoding/base64" "fmt" "math/rand" "net/http" "os/exec" "time" ) func main() { //url := "http://10.209.134.40/index" url := "http://10.210.226.124/index" msgs := [6]string{"麻烦有空像一只喜鹊一样叽叽喳喳海森地去还一下", "麻烦你像一只小猫一样喵喵乖巧地去还一下", "麻烦有空像一只小鹿一样欢快地跑过去还一下", "麻烦像一只小兔子一样蹦...
package runtime import ( "fmt" "net/http" ) // from k8s var ( // ReallyCrash controls the behavior of HandleCrash and now defaults // true. It's still exposed so components can optionally set to false // to restore prior behavior. ReallyCrash = true ) // PanicHandlers is a list of functions which will be invo...
package main import "fmt" // User is a user struct type type User struct { ID int FirstName, LastName, Email string } func updateEmail(u *User, newEmail string) { u.Email = newEmail } func main() { u := User{ ID: 1, FirstName: "Tony", LastName: "Stark", Email: "ironma...
package banana import "errors" var ( UserConflic = errors.New("Người dùng đã tồn tại") SignUpFall = errors.New("Đăng kí thất bại") UserNotFound = errors.New("Người dùng không tồn tại") )
package main // Leetcode 688. (medium) func knightProbability(N int, K int, r int, c int) (res float64) { dr := []int{2, 1, -1, -2, -2, -1, 1, 2} dc := []int{1, 2, 2, 1, -1, -2, -2, -1} dp := make([][]float64, N) for i := range dp { dp[i] = make([]float64, N) } dp[r][c] = 1.0 for step := 0; step < K; step++ ...
package password import ( "gin_bbs/app/auth" "gin_bbs/app/controllers" "gin_bbs/app/helpers" passwordResetModel "gin_bbs/app/models/password_reset" passowordRequest "gin_bbs/app/requests/password" "gin_bbs/pkg/ginutils/flash" "gin_bbs/pkg/ginutils/validate" "github.com/gin-gonic/gin" ) // ShowLinkRequestForm...
package impl import ( . "github.com/hsedjame/products-api/src/models" "log" "sort" "time" ) type SimpleProductRepository struct { logger *log.Logger products Products } func NewSimpleProductRepository(logger *log.Logger) *SimpleProductRepository { return &SimpleProductRepository{logger: logger, products: Pro...
package math import ( "testing" "github.com/stretchr/testify/assert" ) func TestFnRoundToEven(t *testing.T) { input := 12.50 f := &fnRoundToEven{} v, err := f.Eval(input) assert.Nil(t, err) assert.Equal(t, 12.0, v) }
package main import "testing" func TestTopologicalSort(t *testing.T) { graph := loadData("test_input.txt") nodes, err := topologicalSort(graph) if err != nil { t.Error(err) } if nodes.String() != "CABDFE" { t.Errorf("Wrong sort order, expected CABDFE, got %v.", nodes.String()) } } func TestTopologicalSort2...
package main import ( "bytes" "fmt" "io" "strings" ) type limitReader struct { r io.Reader limit int64 read int64 } func (lr *limitReader) Read(p []byte) (n int, err error) { if lr.read >= lr.limit { return 0, io.EOF } if int64(len(p))+lr.read < lr.limit { lr.read += int64(len(p)) return lr.r.Re...
package main import "testing" func Test_normalize(t *testing.T) { tests := []struct { name string base string file string strip bool want string }{ {"stripBase", "/var/www/html/", "/var/www/html/test/a.gif", true, "test/a.gif"}, {"don't stripBase", "/var/www/html", "/var/www/html/test/a.gif", fal...
/* * Wire API * * Moov Wire implements an HTTP API for creating, parsing, and validating Fedwire messages. * * API version: v1 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package openapi // LocalInstrument struct for LocalInstrument type LocalInstrument struct { // LocalInstrument *...
// 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 // 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 // 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 // 示例: // 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) // 输出:7 -> 0 -> 8 // 原因:342 + 465 = 807 package main //Definition for singly-linked list. type ListNode struct { ...
package main import ( "context" "fmt" "reflect" "time" "github.com/arangodb/go-driver" "github.com/arangodb/go-driver/http" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) type ArangoResults struct { Key string `json:"_key"` Id st...
// Copyright (C)2018 by Lei Peng <pyp126@gmail.com> // // 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,...
package main import ( "sort" "fmt" ) func main() { num := []int{1,5,2,4,2,7,6,8} sort.Ints(num) for _, v := range num { fmt.Println(v) } }
package pointer import "fmt" /** - 变量初始化后,该变量的指针(开辟的内存空间)位置不变,如果重新对此变量赋值,将刷新该内存空间中的内容 - 无法对一个的值变量的指针做改变? e.g. a := 1 / b := 2 / &a = &b 运行异常 ??不太确定 - & 取指针操作 - * 解析指针操作 - 类型前面加 * 表示持有该类型的指针 - 如果有个结构体的指针, 如 demo3 中的 s 变量,要访问结构体的内容,不需要显示使用 * 解指针,直播调用,如 s.name - 方法形参是指针时,通过该指针可直接操作原有对象的内容, - 方法形参是值时,传入的是原值的 copy...
package main import "fmt" func main() { s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} s = append(s[:3], s[5:]...) //OU // x := s[:3] // y := s[5:] //s = append(x, y...) s = append(s[:3], s[5:]...) fmt.Println(s) //[0 1 2 5 6 7 8 9 10] }
package service import ( "context" "login/internal/base" "login/model" "shared/common" "shared/utility/errors" "shared/utility/key" "strconv" ) var koMoe = &KoMoe{ host: "https://line3-sdk-adapter.komoejoy.com", spareHost: "https://line1-sdk-adapter.komoejoy.com", GP: &KoMoeAppConfig{ merchant_id: 1,...
package main import ( "github.com/friendlyhank/etcd-use/discover/client" "log" "time" ) func main() { m, _ := client.NewEtcdV3Discovery("node",[]string{"localhost:2379", "localhost:2381", "localhost:2383"}) for{ list,_ := m.GetServiceList() if len(list) == 0{ continue } for _,endPoint:= range list{ ...
package structs import "encoding/json" type PubSubMessage struct { Event string Data struct { IDString string IDInt uint } } func (r PubSubMessage) JSONify() string { b, _ := json.Marshal(&r) return string(b) }
package arlo import ( "bytes" "context" "encoding/json" "errors" "net/http" "github.com/satori/uuid" ) const ( fullFrameSnapshotURL = "https://arlo.netgear.com/hmsweb/users/devices/fullFrameSnapshot" ) func (c *Client) FullFrameSnapshot(ctx context.Context, camera Device) error { transactionID, err := uuid....
package util import ( "log" "os" ) var AppConfig Config type Config struct { SentryDSN string DBHost string DBPort string DBUser string DBPassword string DBName string AppPort string } func init() { AppConfig = Config{ SentryDSN: os.Getenv("SENTRY_DSN"), DBHost: os.Getenv("DB_...
package handler /* func GetAllWorkers(db *gorm.DB, c *gin.Context) func(*gin.Context){ employees := []model.Worker{} db.Find(&employees) //respondJSON(w, http.StatusOK, employees) message := "hello" return func(c *gin.Context) { c.String(http.StatusOK, message) } } func CreateWorker(db *gorm.DB, w http.Respon...
package helpers import ( "ktmall/common/jpush" ) func LoginPush(pushId string) { opts := jpush.BuildJPushOptions(). SetPlatform(). SetAudience([]string{pushId}). SetMessage("", "登录", map[string]interface{}{ "code": 1, }) jpush.GetInstance().Send(opts) } func OrderPush(pushId, orderId string) { opts :...
package user type User struct { Id string `gorethink:"id,omitempty"` Name string `gorethink:"name"` }
package main import ( "context" "errors" "flag" "fmt" "html/template" "log" "net" "net/http" "os" "os/signal" "path" "sync" "syscall" "time" env "github.com/caarlos0/env/v7" "github.com/joho/godotenv" ) type config struct { envfile string Host string `env:"KUBICO_HOST" envDefault:"0.0....
package lexer import ( "fmt" "strings" "unicode" "github.com/stephens2424/php/token" ) // longestToken is length of the longest token string var longestToken = 0 const shortPHPBegin = "<?" const longPHPBegin = "<?php" const phpEnd = "?>" const eof = -1 func init() { for k := range token.TokenMap { if len(k...
package model //go:generate gom exec dgw postgres://artiefact@localhost/artiefact?sslmode=disable --package=model --output=table.go --exclude=alembic_version // Remember that you can specify schema.
package action import "testing" func TestActions(t *testing.T) { var act Logger act = New("test action") exp := "test action" if act.Action() != exp { t.Errorf( "&actionString %s != %s", act, exp, ) } }
package main import "fmt" func main() { x := 41 if x > 42 { fmt.Println("The value is greater than 42") } else if x < 42 { fmt.Println("The value is less than 42") } else { fmt.Printf("The value is: %v", x) } }
package main //558. 四叉树交集 //二进制矩阵中的所有元素不是 0 就是 1 。 // //给你两个四叉树,quadTree1 和 quadTree2。其中 quadTree1 表示一个 n * n 二进制矩阵,而 quadTree2 表示另一个 n * n 二进制矩阵。 // //请你返回一个表示 n * n 二进制矩阵的四叉树,它是 quadTree1 和 quadTree2 所表示的两个二进制矩阵进行 按位逻辑或运算 的结果。 // //注意,当 isLeaf 为 False 时,你可以把 True 或者 False 赋值给节点,两种值都会被判题机制 接受 。 // //四叉树数据结构中,每个内部节点只有...
package function import ( "encoding/json" "github.com/hecatoncheir/Storage" "io" "io/ioutil" "net/http" "net/http/httptest" "testing" ) func TestFAASFunctions_CompaniesReadByName(t *testing.T) { LanguageForTest := "ru" CompanyNameForTest := "TestCompanyName" DatabaseGatewayForTest := "http://TestDatabaseGa...
// 150.Documentation 圖 文件概念解說? // 不是告知 物體 要分享出去 // 而是告知本身帶有分享的情報? // https://golang.org/ref/spec#Go_statements // <- = channl 後面會講 package main import ( "fmt" ) func dosomething(x int) int { return x * 5 } func main() { ch := make(chan int) go func() { ch <- dosomething(5) }() fmt.Println(<-ch) } // go li...
package main import "github.com/gopherjs/gopherjs/js" func main() { js.Global.Set("onmessage", func(evt *js.Object) { js.Global.Get("console").Call("log", evt) }) }
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package ip import ( "context" "io" "zenhack.net/go/tempest/capnp/ip" "zenhack.net/go/tempest/pkg/exp/util/bytestream" "capnproto.org/go/capnp/v3" ) func ConnectTCP(ctx context.Context, port ip.TcpPort) io.ReadWriteCloser { fromThem, toUs := bytestream.Pipe() res, release := port.Connect(ctx, func(p ip.TcpPor...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package wifiutil import ( "context" "time" "chromiumos/tast/common/servo" "chromiumos/tast/ctxutil" "chromiumos/tast/dut" "chromiumos/tast/errors" "chromiumos/tast/r...
package propose import ( pb "github.com/xuperchain/xupercore/protos" ) type ProposeManager interface { GetProposalByID(proposalID string) (*pb.Proposal, error) }
package main import ( "bank/pkg/bank/card" "bank/pkg/bank/types" "fmt" ) func main() { card1 := types.Card{ Balance: 0, MinBalance: 2_027_777_78, Active: true, } oldBalance := card1.Balance card.AddBonus(&card1, 3, 30, 365) newBalance := card1.Balance fmt.Println(newBalance - oldBalance) }
package driver /* #cgo LDFLAGS: -lcomedi -lm #include "io.h" #include "channels.h" #include "elev.h" */ import "C" type elev_button_type_t int type elev_motor_direction_t int const ( BUTTON_CALL_UP elev_button_type_t = iota BUTTON_CALL_DOWN BUTTON_COMMAND ) const ( DIRN_DOWN elev_motor_direction_t ...
package builder import ( . "openreplay/backend/pkg/messages" ) type builderMap map[uint64]*builder func NewBuilderMap() builderMap { return make(builderMap) } func (m builderMap) GetBuilder(sessionID uint64) *builder { b := m[sessionID] if b == nil { b = NewBuilder() m[sessionID] = b b.sid = sessionID ...
package model import "errors" // ErrPermissionDenied - raise when user does not have required permissions var ErrPermissionDenied = errors.New("permission denied") // ErrUnAuthorized - raise when user does not authorized var ErrUnAuthorized = errors.New("unauthorized")
package column_test import ( "context" "fmt" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/vahid-sohrabloo/chconn/v2" "github.com/vahid-sohrabloo/chconn/v2/column" ) func TestMapUint8(t *testing.T) { testMapColumn(t, "UInt8", "uint8", func(i int) []uin...
package suren import ( "crypto/sha1" "fmt" "github.com/levigross/grequests" "github.com/sirupsen/logrus" "io" "sort" "strings" "time" ) type ( Suren struct { appID string secret string token string accessToken string expiresIn int refreshed chan byte } ) var ( accessTokenE...
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package quicksettings import ( "context" "time" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/uiauto" "chromiumos/tast/local/chrome/uiauto/faillog" "ch...
// Copyright 2019 The gVisor 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 agree...
package cmd import ( "context" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/hellofresh/github-cli/pkg/config" "github.com/hellofresh/github-cli/pkg/github" "github.com/hellofresh/github-cli/pkg/log" ) type ( // RootOptions represents the ahoy global options RootOptions struct { config...
package leetcode_go func widthOfBinaryTree(root *TreeNode) int { type NodePos struct { node *TreeNode pos int } res := 1 q := []*NodePos{&NodePos{root, 1}} var curLen int for len(q) > 0 { curLen = len(q) left := q[0].pos right := left for i := 0; i < curLen; i++ { node := q[i].node right = q[...
// Package fbapp provides a Facebook Application type and some related // utilities. package fbapp import ( "flag" "fmt" "net/url" ) type App interface { ID() uint64 Secret() string Namespace() string SecretByte() []byte Set(values url.Values) error } type app struct { id uint64 secret string ...
package main import "fmt" func main() { //Range on array l := []int{1, 2, 3, 4, 5} sum := 0 for _, num := range l { sum = sum + num } fmt.Println("Print value num ", sum) //Range on map m := map[string]int{"one": 1, "two": 2, "three": 3, "four": 4} for key, val := range m { fmt.Printf("%s ---> %d\n"...
package dsl import ( "fmt" "reflect" "strings" ) // EachLike specifies that a given element in a JSON body can be repeated // "minRequired" times. Number needs to be 1 or greater func EachLike(content interface{}, minRequired int) string { return fmt.Sprintf(` { "json_class": "Pact::ArrayLike", "content...
package main import ( "errors" "fmt" ) /** 题目: 给定一个二叉树,每个节点上有一个数字。 对于每一个叶子节点,输出从该节点到根 节点路径上所有数的和。 思路: 实际上是一个遍历问题,递归查找叶子节点,利用回溯的思想,用栈存储 找到节点的路径 当找到节点后,计算栈中的数据和。 **/ func main() { //构建题目中的树 rootNode := GenerateTree() HeadNode := &Node{0, nil, nil} //构建的栈 stack := &Stack{HeadNode...
package twitch import ( "context" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "strings" "time" "gitlab.com/kavenc/telepathy/internal/pkg/telepathy" ) // A Stream represents a twtich stream type Stream struct { CommunityID []string `json:"community_ids"` GameID string `json:...
// the simulation implement a pool of database connections package main import ( "GoInAction/concurrent2/pool" "io" "log" "math/rand" "sync" "sync/atomic" "time" ) const ( maxGoroutines = 10 pooledResources = 2 ) // shared resource type dbConnection struct { ID int32 } func (dbConn *dbConnection) Close(...
package main import ( "fmt" "go-demo/pointer/swap" ) // 通过指针在函数内部修改值影响外部 func pointer(p *int) { // *就是改变指针指向的地址的值 *p = 10 } func main() { a := 5 // 传递地址,而不是值的拷贝 pointer(&a) // 打印 10 println("a =", a) /* * @description: 下面是交换两个数字的例子 */ b := 10 c := 20 fmt.Printf("previous: b = %d, c = %d\n", b, c) ...
// Copyright 2017 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package keeper import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tharsis/ethermint/x/feemarket/types" ) var _ types.QueryServer = Keeper{} // Params implements the Query/Params gRPC method func (k Keeper) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, e...
package main import ( "os" "os/signal" "syscall" "github.com/sirupsen/logrus" ) func main() { memeBot = newBot(conf.Discord.BotToken) memeBot.AddHandler(handlePutMemeMessage) memeBot.AddHandler(handleGetMemeMessage) memeBot.Listen() log.WithFields(logrus.Fields{"token": conf.Discord.BotToken}).Info("Bot ha...
package utils import ( "fmt" "strings" ) // Namespaced returns a namespaced formatted string. func Namespaced(ns, name string) string { if ns != "" { ns += "_" } return ns + name } // MaskString replaces a section of the string with mask character '*'. func MaskString(s string, n int) string { const maskToke...
package litbamf import ( "fmt" "net/http" "regexp" ) func BamfListen(bamfport uint16, litHomeDir string) { listenString := fmt.Sprintf("http://127.0.0.1:%d", bamfport) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { jsExpr, _ := regexp.Compile("/js.*") imagesExpr, _ := regexp.Compile("/i...
package main /* Design a HashSet without using any built-in hash table libraries. To be specific, your design should include these functions: add(value): Insert a value into the HashSet. contains(value) : Return whether the value exists in the HashSet or not. remove(value): Remove a value in the HashSet. If the value...
package typeutils import ( "testing" "github.com/wolfgarnet/logging" ) type typeA struct { Field string Name string Age int } type typeB struct { typeA Title string } func TestFindField(t *testing.T) { instance := typeB{typeA{"fff", "snade", 10}, "the title"} result := FindField(instance, "Title", -1) ...
package redis import ( "context" r "github.com/go-redis/redis/v8" c "github.com/kooixh/genid/pkg/constants" ) var ctx context.Context var client *r.Client func init() { ctx = context.Background() client = newClient() } func newClient() *r.Client { return r.NewClient(&r.Options{ Addr: c.RedisHost + ":" +...
package models import ( "api/base" "api/editor" ) type HelloModel struct { // } func (hello *HelloModel) GetHelloData(id string) string { /*id += "aaaa" //model需要各自层面实现对应provider的实例化,在当前包内有效还是全局有效,都需要进行判断 //以及连接池的初始化 id = baseProvider.User.RedisProvider.GetUserName(id) id = baseProvider.Test.RedisProvider....
package twoSum //Given an array of integers, return indices of the two numbers such that they add up to a specific target. //You may assume that each input would have exactly one solution, and you may not use the same element twice. // //Example: //Given nums = [2, 7, 11, 15], target = 9, // //Because nums[0] + nums[1...
/* MIT License Copyright (c) 2019 Javier Alvarado */ // Package bytez encapsulates functionality for working with large byte sizes in a human-friendly // way. (The 'z' in the name is not an attempt to be cute but to create a package name that is // short yet unique.) // // Unfortunately, the history is computing is...
/* Copyright 2021 The KodeRover 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 main import "fmt" func main() { people := [][]string{ []string{"Bob", "Smith", "IT guy"}, []string{"Alice", "Smith", "Instagirl"}, } fmt.Println(people) for _, v := range people { fmt.Println(v) for _, p := range v { fmt.Println(p) } } }
package tools import ( "context" "errors" "io/ioutil" "net" "net/http" "strings" "time" ) type HttpReq struct { Ua string Referer string Cookie string request *http.Request } func NewHttpReq() *HttpReq { return &HttpReq{} } // http get 请求 func (h *HttpReq) HttpGet(url string) (response *http.Respo...
package datastructure import "errors" type stackLinkedList struct { Current *LinkedListNode Length int } // NewStackLinkedList returns stack made with linked list. func NewStackLinkedList() Stack { return &stackLinkedList{} } func (s *stackLinkedList) Push(obj interface{}) { newNode := &LinkedListNode{} newNo...
package main import ( "testing" ) func TestFun(t *testing.T) { in := []string{"a", "b", "ba", "bca", "bda", "bdca"} out := longestStrChain(in) if out != 4 { t.Errorf("got %d, want %d", out, 4) } }
package device import ( "errors" "fmt" "log" "sync" "time" "github.com/lann/tuya/net" ) // ErrClosed is return if the Manager has been closed. var ErrClosed = errors.New("closed") // A State holds device state ("dps") data. type State map[uint32]interface{} // Wrap response and error to pass through response...
package config // Configuration models env configuration type Configuration struct { BasePath string `envconfig:"base_path" default:"/kuraifu"` BasePort string `envconfig:"base_port" default:"8080"` LineChannelID string `envconfig:"line_channel_id" required:"true"` LineChannelSecret string `e...
package mail import ( "github.com/smancke/mailigo/logging" "io" "math/rand" "path/filepath" "time" ) type MailingManager struct { templateBaseDir string sender Sender } func NewMailingManager(templateBaseDir string, sender Sender) *MailingManager { return &MailingManager{ templateBaseDir: template...
package commands import ( "github.com/pniedzwiedzinski/photoprism-cli/internal/login" "github.com/urfave/cli/v2" ) // Commands - All cli commands var Commands = []*cli.Command{ { Name: "login", Action: login.Command, }, }
package Two_Sum_II func twoSum(numbers []int, target int) []int { length := len(numbers) index1 := 0 index2 := length - 1 result := []int{} for index1 < index2 { if numbers[index1]+numbers[index2] == target { result = append(result, index1+1) result = append(result, index2+1) return result } if n...
package main import ( "testing" "github.com/aqatl/mal/anilist" ) func TestParseScore(t *testing.T) { { _, err := parseScore("0", anilist.Point10) if err != nil { t.Error(err) } } { score, err := parseScore("-1", anilist.Point10) if err == nil { t.Error("Expected fail, got", score) } } { sc...