text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
"strings"
)
func main() {
//Declare Var
var m1 int
var s1 string
m1 = 2
s1 = "Budi"
fmt.Println(m1)
fmt.Println(s1)
//Declare Many Var
var (
m2 = 3
m3 = 3
)
fmt.Println(m2 + m3)
var m4 int32
var m5 int64
//Casting
fmt.Println(int64(m4) + m5)
//Declare Simple Var
m... |
package main_test
import (
"github.com/stretchr/testify/assert"
"go-restapi/routes"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
)
/* REST API TESTS */
type HttpTestCase struct {
method string
path string
jsonParams string
expectedStatus in... |
// +build linux darwin freebsd openbsd
package pb
const sys_ioctl = 16
|
package global
import (
"encoding/json"
"net/http"
"github.com/garyburd/redigo/redis"
"github.com/felipeguilhermefs/restis/router"
)
type PipelineCommandPayload struct {
Command string `json:"command"`
Args []interface{} `json:"args,omitempty"`
}
type PipelinePayload []PipelineCommandPayload
func Pipe... |
package leet524
import "fmt"
func main() {
var s = "abpcplea"
var d = []string{"a", "b", "c"}
fmt.Println("----------", findLongestWord(s, d))
}
func findLongestWord(s string, d []string) string {
longest := ""
for _, v := range d {
if len(v) > len(longest) || (len(v) == len(longest) && v < longest) {
if i... |
package leetcode
/*给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
/**
* Definition for a binar... |
package Problem0393
func validUtf8(data []int) bool {
// cnt 是还需检查的 byte 的个数
cnt := 0
var d int
for _, d = range data {
if cnt == 0 {
switch {
case d>>3 == 30: //0b11110
cnt = 3
case d>>4 == 14: //0b1110
cnt = 2
case d>>5 == 6: //0b110
cnt = 1
case d>>7 > 0:
// data[0] 和 data[len(d... |
package todoController
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/user/gogo/models"
)
//FetchAllTodo GET
func FetchAllTodo(c *gin.Context) {
var todos []models.TodoModel
var _todos []models.TransformedTodo
db.Find(&todos)
if len(todos) <= 0 {
c.JSON(http.StatusNotFound, gin.H{"status": http.... |
package filters
import (
"bufio"
"io"
)
type asciiCleaner struct {
buf []byte
src *bufio.Reader
index int
next int
}
func NewAsciiCleaner(reader io.Reader) io.Reader {
ac := &asciiCleaner{
buf: make([]byte, 512),
src: bufio.NewReader(reader),
}
return ac
}
func (ac *asciiCleaner) Read(p []byte) (i... |
// START ONE OMIT
func SendMessage(req *http.Request, to, from, message string) (err error) {
c := appengine.NewContext(req)
client := urlfetch.Client(c)
t := twilioclient.NewTwilioClient(twilioSID, twilioSecret)
err = t.SendMessage(*client, to, from, message)
c.Debugf("SENDING %s %s %s", to, from, message)
if ... |
/*package main
import (
//"encoding/json"
"fmt"
)
func main(){
//json.MarshalIndent()
}
*/
package main
import (
"strings"
"fmt"
)
const (
ONE_IPTABLES_RULES = int(1)
IPTABLES_PARAMS_NUM = int(8)
)
type IptablesRules struct {
PackageLossType string
ExecCmdIp string
ExecCmdPort str... |
package main
import (
"fmt"
)
//声明变量
var name string
var age int
var isOk bool
var (
a = 1
b = 3
c = "dds"
)
//批量声明常量
const (
OK = 200
notFound = 404
)
const (
n1 = 100
n2 //默认和上边一致
n3 //默认和上边一致
)
//iota 计数器
const (
a1 = iota //0
a2 = iota //1
a3 //2
)
const (
b1 = iota //0
b2 = iota //... |
package optionsgen
import (
"fmt"
"log"
"os"
"github.com/kazhuravlev/options-gen/internal/generator"
)
type DefaultsFrom string
const (
DefaultsFromTag DefaultsFrom = "tag"
DefaultsFromNone DefaultsFrom = "none"
DefaultsFromVar DefaultsFrom = "var"
DefaultsFromFunc DefaultsFrom = "func"
)
type Defaults s... |
package blobstore
import (
"crypto"
"crypto/rand"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
const (
defaultPerms = 0750
vfsRoot = ""
filesAtOnce = 10
)
// NewFileBlobServer returns a VFSBlobServer using a fileBlobs, that is on top of the os files
func NewFileBlobServer(dir string, hash crypto.Hash)... |
package main
/*
* Simple GO program to solve sudokus.
*
* TODO Try to use clz and popcount, link against C.
*/
import (
"fmt"
"os"
)
type mask uint16 // Enough to hold 9 bits.
type cell struct {
groups [3]*mask
next *cell
value uint
}
const (
DEFAULT_MASK mask = (1 << 9) - 1
)
var (
// Group resolve... |
package storage
import (
// Standard Library Imports
"context"
"fmt"
// External Imports
"github.com/ory/fosite"
)
// User provides the specific types for storing, editing, deleting and
// retrieving a User record in mongo.
type User struct {
//// User Meta
// ID is the uniquely assigned uuid that references ... |
// Copyright (c) 2018 ECAD Labs Inc. MIT License
// Copyright (c) 2020 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package rpc
import (
"encoding/json"
"fmt"
"tezos_index/chain"
)
// TestChainStatus is a variable structure depending on the Status field
type TestChainStatus interface {
TestChainStatus() s... |
package service
import "github.com/myownhatred/botAPI/pkg/repository"
type Picture interface {
}
type Video interface {
}
type Translate interface {
}
type GoogleService struct {
Picture
Video
Translate
}
func NewGoogleService(rep *repository.GoogleRepository) *GoogleService {
return &GoogleService{}
}
|
package blockchain
import (
"encoding/hex"
"fmt"
"github.com/dgraph-io/badger"
log "github.com/sirupsen/logrus"
"os"
"runtime"
)
const (
dbPath = "/home/shiun/tmp/blocks"
// to verify if our blockchain database is exists
dbFile = "/home/shiun/tmp/MANIFEST"
genesisData = "First Transaction from Genesis"
)
t... |
package architecture
import "strings"
type Architecture struct {
Root *Directory
}
func NewArchitecture() *Architecture {
return &Architecture{
Root: NewDirectory(),
}
}
func (arch *Architecture) FindDirectory(path string) *Directory {
pathSections := strings.Split(path, "/")
currentNode := arch.Root
for ... |
package base
import (
"gengine/context"
"gengine/core/errors"
"reflect"
)
type IfStmt struct {
Expression *Expression
StatementList *Statements
ElseIfStmtList []*ElseIfStmt
ElseStmt *ElseStmt
knowledgeContext *KnowledgeContext
dataCtx *context.DataContext
}
func (i *IfStmt) Evalu... |
package Problem0172
func trailingZeroes(n int) int {
res := 0
for n >= 5 {
n /= 5
res += n
}
return res
}
|
package rtrserver
import (
"bytes"
"net"
"time"
"github.com/cpusoft/goutil/belogs"
"github.com/cpusoft/goutil/convert"
"github.com/cpusoft/goutil/jsonutil"
)
type RtrTcpServerProcessFunc struct {
}
func (rs *RtrTcpServerProcessFunc) OnConnect(conn *net.TCPConn) {
}
func (rs *RtrTcpServerProcessFunc) OnReceiv... |
package dbops
import (
"log"
"database/sql"
_ "github.com/go-driver/mysql"
)
func openConn() *sql.DB {
dbConn, err := sql.Open("mysql","root:123@tcp(localhost:3306)/video_server?charset=utf8")
if err != nil {
panic(err.Error())
}
return dbConn
}
func AddUerCredential(loginName string, pwd string) error {
... |
package pgsql
import (
"testing"
)
func TestNumRange(t *testing.T) {
testlist2{{
valuer: NumRangeFromIntArray2,
scanner: NumRangeToIntArray2,
data: []testdata{
{
input: [2]int{-9223372036854775808, 9223372036854775807},
output: [2]int{-9223372036854775808, 9223372036854775807}},
},
}, {
valu... |
package runner
import (
"context"
"runtime"
"strings"
"testing"
"encoding/json"
"github.com/pkg/errors"
)
const (
CombinedShScript = "./fixture/combined.sh"
CombinedPowershellScript = "./fixture/combined.ps1"
)
func TestConfigLoadConfig(t *testing.T) {
c := &Runner{}
if err := c.LoadFromFile("./f... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-05-12 11:57
# @File : pdf.go
# @Description :
# @Attention :
*/
package utils
import (
"errors"
"github.com/SebastiaanKlippert/go-wkhtmltopdf"
"io"
"os"
"path/filepath"
)
type PageOperationDecorator interface {
Decorate(options *wkhtmltopdf.PageOpti... |
//aws_status_vpc.go
package main
import (
"fmt"
)
/*func aws_status_vpc(region string, environment string) {
fmt.Println("AWS vpc Status in region: " + region + " for environment: " + environment)
}*/
func aws_status_vpc(region string,environment string) {
if check_aws_initialized() == true {
fmt.Println( ... |
package main_test
import (
"fmt"
"strconv"
"strings"
"testing"
"time"
)
func TestReplace(t *testing.T) {
str := "BrokerAPIDeployment$TIMESTAMP$"
nowStr := strconv.Itoa(int(time.Now().Unix()))
replacedStr := strings.ReplaceAll(str, "$TIMESTAMP$", nowStr)
fmt.Println(replacedStr)
}
|
package account
import "context"
type Customer struct {
ID, Email, Password, Phone string
}
type Repository interface {
CreateCustomer(ctx context.Context, customer Customer) error
}
|
package main
import (
"context"
"fmt"
"net/http"
"strings"
_ "net/http/pprof"
"github.com/ephraimkunz/go-trending"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
"google.golang.org/appengine/log"
"google.golang.org/appengine/urlfetch"
)
const (
SummaryIntent = "summary_intent"
Trendin... |
// Copyright 2020 Ant Group. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
package checker
import (
"context"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/dragonflyoss/image-service/contrib/nydusify/pkg/checker/rule"
"github.com/dragonflyoss/image-ser... |
/*
Copyright 2021 The Tekton 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, softw... |
package validatingroundtripper
import (
"fmt"
"net/http"
"os"
"github.com/operator-framework/operator-lifecycle-manager/pkg/controller/install"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/rest"
)
type validatingRoundTripper struct {
delegate http.... |
package commonutils
import (
consulapi "github.com/hashicorp/consul/api"
log "github.com/sirupsen/logrus"
"strconv"
)
func GetConsulApiClient(host string, port int) (*consulapi.Client, error) {
log.WithFields(log.Fields{"package": "commonutils","function": "GetConsulApiClient",}).Debugf("Getting Consul API clie... |
/*
Write a program to find all the prime factors of a given number.
The program must return an array containing all the prime factors, sorted in ascending order.
Remember that 1 is neither prime nor composite and should not be included in your output array.
Examples
primeFactorize(25) ➞ [5, 5]
primeFactorize(19) ➞ [... |
// SPDX-License-Identifier: Apache-2.0
// Copyright The Linux Foundation
package main
// based on quickstart from https://developers.google.com/sheets/api/quickstart/go
// and code from https://github.com/gsuitedevs/go-samples/blob/master/sheets/quickstart/quickstart.go
// with the following copyright and license not... |
package element
// note: not thourougly tested on moduli != .NoCarry
const FromMont = `
// FromMont converts z in place (i.e. mutates) from Montgomery to regular representation
// sets and returns z = z * 1
{{- if eq .IfaceName .ElementName}}
func (z *{{.ElementName}}) FromMont() *{{.ElementName}} {
{{else}}
func (z ... |
// 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 main
import (
"fmt"
smartling "github.com/Smartling/api-sdk-go"
"github.com/reconquest/hierr-go"
)
func doFilesDelete(
client *smartling.Client,
config Config,
args map[string]interface{},
) error {
var (
project = config.ProjectID
uri = args["<uri>"].(string)
)
var (
err error
files ... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package wasmproc
import (
"encoding/binary"
"fmt"
"github.com/iotaledger/wasp/packages/kv"
"github.com/iotaledger/wasp/packages/kv/codec"
"github.com/iotaledger/wasp/packages/kv/dict"
"github.com/iotaledger/wasp/packages/vm/wasmhost"
"strin... |
package raw_client
import (
"context"
)
type PutRecordRequestRecord struct {
Value string `json:"value"`
}
type PutRecordRequest struct {
App string `json:"app"`
Id string `json:"id"`
Record map[string]PutRecordRequestRecord `json:"record,omitempty"`
... |
package LongSteps
type DoNothing struct {
Operand
}
func (d DoNothing) Evaluate(environment Environment) (Operand, Environment) {
return d.Operand, environment
}
func (d DoNothing) Int(environment Environment) int {
return d.Operand.Int(environment)
}
func (d DoNothing) Bool(environment Environment) bool {
return... |
// Copyright 2019 The Android Open Source Project
//
// 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 ... |
package blog
import "github.com/jinzhu/gorm"
type (
Post struct {
gorm.Model
From string `json:"from" gorm: NOT NULL"`
Message string `json:"message" gorm: NOT NULL"`
}
)
|
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func sayHello(w http.ResponseWriter, r *http.Request) {
b, _ := ioutil.ReadFile("./hello.txt")
_, _ = fmt.Fprintln(w, string(b))
}
func main() {
http.HandleFunc("/hello", sayHello)
err := http.ListenAndServe(":9090", nil)
if err != nil {
fmt.Printf("http... |
package get
import (
"encoding/json"
"fmt"
"reflect"
"testing"
)
func TestGet_getArgs(t *testing.T) {
type args struct {
input string
}
tests := []struct {
name string
args args
want map[string]string
}{
{name: "tes1", args: args{input: "/login?ph=1"}, want: map[string]string{"ph": "1"}},
{name: "... |
package main
import "fmt"
/*
get this code working using a buffered channel
*/
/*BEFORE
func main() {
c := make(chan int)
c <- 42
fmt.Println(<-c)
}
*/
//AFTER
func main() {
c := make(chan int, 3)
c <- 42
c <- 43
c <- 44
fmt.Println(<-c)
fmt.Println(<-c)
fmt.Println(<-c)
} |
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... |
package main
import (
"fmt"
"strings"
"../../link"
)
var exampleHTML = `
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1>Social stuffs</h1>
<div>
<a href="https://www.twitter.com/joncalhoun">
Check me out o... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"strings"
)
func main() {
flag.Parse()
if len(flag.Args()) != 1 {
return
}
fileContents := MustOpenTextFile(flag.Args()[0])
for _, line := range strings.Split(fileContents, "\n") {
if len(line) == 0 {
continue
}
var n, m int
fmt.Sscanf(line... |
// Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license"... |
package main
import "fmt"
// https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
func searchRange(nums []int, target int) []int {
l, h := 0, len(nums)-1
low, up := 0, 0
ok := false
for m := 0; l <= h; {
m = (l + h) / 2
if nums[m] == target {
ok = true
}
if nums[m]... |
package main
import (
"bytes"
"context"
"errors"
"html/template"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/caddyserver/certmagic"
"github.com/gernest/8x8/pkg/auth"
"github.com/gernest/8x8/pkg/mw"
"github.com/gernest/8x8/pkg/xl"
"github.com/gernest/8x8/templates"
"github.com/gorilla/mux"
"... |
package logic
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/kafka"
"Open_IM/pkg/common/log"
)
var (
persistentCH PersistentConsumerHandler
historyCH HistoryConsumerHandler
producer *kafka.Producer
)
func Init() {
log.NewPrivateLog(config.Config.ModuleName.MsgTransferName)
persistentCH.Init(... |
package temp
type ObjectMetaTemp struct {
Name, Namespace string
}
|
package eventfile
import (
"bytes"
"strings"
"testing"
"time"
"github.com/golang/protobuf/proto"
"google.golang.org/protobuf/runtime/protoiface"
spb "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/summary_go_proto"
epb "github.com/tensorflow/tensorflow/tensorflow/go/core/util/event_go_proto"
... |
package handler
import (
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
"go.mercari.io/hcledit/internal/ast"
)
type ctyValueHandler struct {
exprTokens hclwrite.Tokens
beforeTokens hclwrite.Tokens
afterKey string
}
func newCtyValueHandler(value cty.Value, comment, afterKey string, b... |
// Package main provides ...
package selectionsort
import (
"github.com/lzcqd/sedgewick/chap2_sorting/sortable"
"reflect"
"testing"
)
func TestSort(t *testing.T) {
cases := []struct {
in, want sortable.Interface
}{
{sortable.Intslice([]int{8, 3, 5, 7, 10, 1, 4, 2, 9, 6}), sortable.Intslice([]int{1, 2, 3, 4, ... |
package main
import (
"errors"
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"strings"
"github.com/boltdb/bolt"
"github.com/codegangsta/cli"
)
const saveLocationName = ".projects.db"
const bucketName = "projects"
var errTxNotWritable = errors.New("tx not writable")
func getBucket(tx *bolt.Tx) (*bolt.Bucket, ... |
package mmongo
import (
"errors"
)
// 单例管理器
var MyfMongo *MongoManager
const (
DEFAULT_MAX_POOL_SIZE uint64 = 100 //默认最大连接数
DEFAULT_MIN_POOL_SIZE uint64 = 10 //默认闲置连接
//ConnectTimeout
DEFAULT_CONNECT_TIMEOUT int = 10000 //默认连接超时 10s
)
// 单实例配置
type MongoConnConf struct {
Host string `toml:"host"` // host
Por... |
package config
import (
"encoding/json"
"os"
)
// Config struct for file config.json
type Config struct {
TelegramBotToken string `json:"TELEGRAM_BOT_TOKEN"`
TelegramChannelChatID int64 `json:"TELEGRAM_CHANNEL_CHAT_ID"`
}
// LoadConf func ...
func LoadConf() Config {
file, _ := os.Open("resources/config.j... |
package bench
import (
"sync"
"testing"
)
func TestCounter_Add(t *testing.T) {
type fields struct {
value int64
mu *sync.RWMutex
}
type args struct {
amount int64
}
tests := []struct {
name string
fields fields
args args
}{
{"base-case", fields{0, &sync.RWMutex{}}, args{10}},
}
for _, t... |
package main
//create a type SQUARE
//create a type CIRCLE
//attach a method to each that calculates AREA and returns it
//circle area= π r 2
//square area = L * W
//create a type SHAPE that defines an interface as anything that has the AREA method
//create a func INFO which takes type shape and then prints the area
/... |
/**
* @Author: yanKoo
* @Date: 2019/3/11 10:48
* @Description: 处理请求的业务逻辑
*/
package controllers
import (
pb "api/talk_cloud"
cfgWs "configs/web_server"
"context"
"github.com/gin-gonic/gin"
"log"
"model"
"net/http"
tg "pkg/group"
"server/common/src/db"
"service"
"service/grpc_client_pool"
"strconv"
)
// w... |
package game
import (
"errors"
"github.com/golang/glog"
"github.com/jinzhu/gorm"
"github.com/noxue/utils/argsUtil"
"github.com/noxue/utils/fsm"
"math/rand"
"qipai/config"
"qipai/dao"
"qipai/model"
"qipai/utils"
"strconv"
"strings"
"time"
)
var n = 0
func StateSelectBanker(action fsm.ActionType, args ...... |
package covid
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/NavenduDuari/goinfo/covid/utils"
)
func getCovidData() covidStruct {
url := "https://api.covid19india.org/data.json"
res, err := http.Get(url)
if err != nil {
fmt.Println(err)
}
var covidObj covidStruct
responseData,... |
package main
import (
"bufio"
"flag"
"fmt"
"math"
"os"
"strconv"
)
func scanFile(filePath string, maxLines uint, showLineNum bool) {
file, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
s := bufio.NewScanner(file)
if showLineNum {
digits := strconv.FormatFloat... |
package datastruct
import "fmt"
func ExampleStack() {
// we can use slice instead of stack
s := make([]int, 0)
// Push
s = append(s, 1)
s = append(s, 8)
s = append(s, -2)
// Pop
top := s[len(s)-1]
s = s[:len(s)-1]
fmt.Println(top)
top = s[len(s)-1]
s = s[:len(s)-1]
fmt.Println(top)
s = append(s, 10)... |
package scoped
import (
"fmt"
"strings"
"github.com/rancher/norman/api/access"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/store/transform"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/types/client/management/v3"
mgmtclient "github.com/r... |
package controllers
import (
"encoding/json"
"mall/models"
)
// Operations about Logout
type LogoutController struct {
BaseController
}
// @Title Logout
// @Description Logout umsMember
// @Param body body models.UmsMember true "body for UmsMember content"
// @Success 200 {object} models.UmsMember
// @Failure ... |
package fixtures
import (
"context"
"time"
"github.com/tilinna/clock"
)
// NewAdvancingClock attaches a virtual clock to a context which advances
// at full speed (not wall speed), and a cancel function to stop it. The
// clock also stops if the context is canceled.
func NewAdvancingClock(ctx context.Context) (c... |
package main
// === package di ===
import "reflect"
var (
// define how what name binds to which value
bindings = make(map[string]reflect.Value)
// define where to bind the values by name
targets = make(map[string][]reflect.Value)
)
// add a new binding target
func Resolve(name string, service interface{}) {
if... |
package ignorefile
type Matcher interface {
MatchPath(path string) bool
}
type NopMatcher struct{}
//nolint:revive
func (n NopMatcher) MatchPath(path string) bool {
return false
}
var _ Matcher = &NopMatcher{}
|
package main
import "fmt"
func main() {
var num1 int32 = 40
var num2 int32 = 20
var num3 int32 = 70
var num4 int64 = 70
switch num1 {
case num2,10,70://case后面的表达式可以有多个
fmt.Println("success")
case num3://case后面的表达式如果是常量值,编译不会报错
fmt.Println("fail")
case 70://case后面的表达式如果是常量值,编译会报错
fmt.Println("fail const"... |
package table
var tmpls = map[string]string{"choose_table_ajax": `{{define "choose_table_ajax"}}
NProgress.start();
let info_table = $("tbody.fields-table");
info_table.find("tr").remove();
let tpl = $("template.fields-tpl").html();
for (let i = 0; i < data.data[0].length; i++) ... |
package main
import (
"classpath"
"flag"
"fmt"
"os"
"rtda/heap"
"strings"
)
// Cmd
/**
该结构体来表示命令行参数与选项
成员说明:
1. helpFlag 帮助选项
2. versionFlag 版本选项
3. cpOption 类路径选项
4. XjreOption Java虚拟机将使用JDK的启动类路径来寻找和加载Java标准库中的类.该参数指定加载的jre的目录。
5. class 指定类路径
6. args 参数
*/
type Cmd struct {
helpFlag bool
versionFlag... |
package git
import (
"io/ioutil"
"testing"
)
func TestResetToCommit(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
seedTestRepo(t, repo)
// create commit to reset to
commitId, _ := updateReadme(t, repo, "testing reset")
// create commit to reset from
nextCommitId, _ :... |
package name_test
import (
"fmt"
"github.com/QisFj/godry/name"
)
func ExampleToCamelCase() {
for _, s := range []string{
"a",
"aa",
"aa_aa",
"http_request",
"battery_life_value",
"id0_value",
} {
fmt.Println(name.ToCamelCase(s))
}
// Output:
// A
// Aa
// AaAa
// HttpRequest
// BatteryLifeVa... |
package http
import (
"github.com/gin-gonic/gin"
"fmt"
"net/http"
)
var Router = gin.Default()
func init() {
Router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World")
})
Router.GET("/post", func(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "0")
name := c.... |
package flow
import (
"context"
"errors"
"path/filepath"
"time"
"github.com/direktiv/direktiv/pkg/flow/bytedata"
"github.com/direktiv/direktiv/pkg/flow/database"
"github.com/direktiv/direktiv/pkg/flow/database/recipient"
"github.com/direktiv/direktiv/pkg/flow/grpc"
"github.com/direktiv/direktiv/pkg/refactor/... |
package main
import (
"./s3go" // import straight from github? commit?
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
// "strconv"
"time"
)
func dothing(r *s3.SDBRequest, cred *s3.SecurityCredentials) {
r.AddCredentials(cred)
req, err := r.HttpRequest()
if err != nil {
log.Fatal(err)
}
log.Println(req)
r... |
package rule
import (
"net/http"
"github.com/sirupsen/logrus"
)
type orRule struct {
rules []Rule
}
// NewOrRule :
func NewOrRule(rules []Rule) Rule {
return orRule{
rules: rules,
}
}
// Execute Execute And Rule
func (r orRule) Execute(req *http.Request) bool {
logrus.WithFields(logrus.Fields{
"type": "... |
package main
import (
"fmt"
"log"
"os"
"github.com/awslabs/aws-sdk-go/aws"
"github.com/awslabs/aws-sdk-go/gen/cloudwatch"
)
var region = "us-west-2"
// Connect will provide a valid RDS client
func Connect() *cloudwatch.CloudWatch {
creds := aws.Creds(os.Getenv("AWS_ACCESS_KEY"), os.Getenv("AWS_SECRET_KEY"), "... |
// 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 "fmt"
func sum(nums ...int){
fmt.Println(nums," ")
total := 0
for sum := range nums {
total += sum
}
fmt.Println("total sum",total)
}
func main(){
sum(1,2)
sum(2,3,4)
sum(4,5,6,7)
nums := []int {1,2,3,4,5,6}
sum(nums...)
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//217. Contains Duplicate
//Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appear... |
package main
func (this *Application) StatusAction(args []string) {
}
|
package storage
// LRUStrategy is the cache eviction strategy which uses pseudo LRU algorithm.
type LRUStrategy struct {
}
// NewLRUStrategy return the pointer of LRUStrategy.
func NewLRUStrategy() *LRUStrategy {
return &LRUStrategy{}
}
// TouchPage is the process which is happened when page use.
func (s *LRUStrate... |
package main
import (
"net"
"strings"
)
func isDNSError(err error) bool {
errMsg := err.Error()
return strings.Contains(errMsg, "No such host") ||
strings.Contains(errMsg, "GetAddrInfoW") ||
strings.Contains(errMsg, "dial tcp")
}
func isErrOpWrite(err error) bool {
ne, ok := err.(*net.OpError)
if !ok {
r... |
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
Routes()
log.Println("listener : Started : Listening on : 4000")
http.ListenAndServe(":4000", nil)
/*
1.监听TCP网络地址, 然后通过handler调用服务来处理连接请求
2.已接受连接被配置为启用TCP保持连接
3.handler通常为nil; 此时, 使用默认ServeMux
*/
}
//为网络服务设置路由 ~ 配置路由
func Ro... |
package equinix
import (
"context"
"fmt"
"log"
"testing"
"github.com/equinix/ecx-go/v2"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)
const (
priPortEnvVar = "TF_ACC_FABR... |
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
type Place struct {
ID int `json: "id"`
Location string `json: "name"`
SMID int `json: "smid"`
}
func getPlaceHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
location, _ := store.GetPlace(vars["location"])
fmt.Println(... |
package services
import "testing"
var mockRequester IRequester = &struct{}{}
var subject = UsersService{}
func TestGetUsersOk(t *testing.T) {
_requester = mockRequester
response := subject.GetUsers()
if response == nil {
t.Fail()
}
}
|
package routes
import (
"github.com/gofiber/fiber/v2"
"github.com/lucas-stellet/fiber-todo/controllers"
)
// TodoRoute ...
func TodoRoute(route fiber.Router) {
route.Get("", controllers.GetTodos)
route.Get(":id", controllers.GetTodo)
route.Post("", controllers.CreateTodo)
}
|
package history
import (
"context"
"time"
)
type Status int
const (
Success Status = iota
Failure Status = iota
)
type Historizer interface {
SaveSuccessfulQuery(ctx context.Context, cypher, sql string, duration time.Duration) error
SaveFailedQuery(ctx context.Context, cypher, sql string, err error) error
}
... |
// Copyright 2020 Adam Chalkley
//
// https://github.com/atc0005/go-lockss
//
// Licensed under the MIT License. See LICENSE file in the project root for
// full license information.
package main
import (
"errors"
"flag"
"fmt"
"os"
"time"
"github.com/apex/log"
"github.com/atc0005/go-lockss/internal/config"
... |
package main
import (
"fmt"
"html/template"
"io"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/parnurzeal/gorequest"
"github.com/patrickmn/go-cache"
"github.com/tidwall/gjson"
)
var cacheDuration = time.Second * ... |
package pool
import (
"testing"
"time"
)
func Test_queueImpl_put(t *testing.T) {
t.Run("Put on Queue", func(t *testing.T) {
q := queueImpl{}
q.put(&workerImpl{
id: "1",
queuedAt: time.Now(),
run: func() error {
return func(id string) error {
return nil
}("1")
},
})
if len(q... |
/*
* This file is part of impacca. Copyright (C) 2013 and above Shogun <shogun@cowtech.it>.
* Licensed under the MIT license, which can be found at https://choosealicense.com/licenses/mit.
*/
package utils
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/Master... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.