text stringlengths 11 4.05M |
|---|
package main
import (
"fmt"
)
func catMouseGame(graph [][]int) int {
N := len(graph)
dp := make([][][]int, N)
for i := range graph {
dp[i] = make([][]int, N)
for j := range graph {
dp[i][j] = make([]int, N+N)
for k := range dp[i][j] {
dp[i][j][k] = -1
}
}
}
return whoWins(graph, 1, 2, 0, dp)
... |
package main
import (
"time"
c "github.com/dlapiduz/govcode.org/common"
"github.com/go-martini/martini"
"github.com/martini-contrib/cors"
"github.com/martini-contrib/gzip"
"github.com/martini-contrib/render"
)
func main() {
m := App()
m.Run()
}
func App() *martini.ClassicMartini {
m := martini.Classic()
... |
package base58
import (
"testing"
"github.com/c2nc/gosys/crypto/uuid"
)
var (
uid []byte
token string
encoder = Ripple
)
// generate shorted UUID in base58 enconding
func generateToken() string {
return Encode(uuid.GenerateBytesUUID(), encoder)
}
func BenchmarkEncode(b *testing.B) {
for i := 1; i < b.N; i++... |
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package service
import (
"context"
"fmt"
"github.com/bqxtt/book_online/api/adapter"
"github.com/bqxtt/book_online/api/model/entity"
"github.com/bqxtt/book_online/rpc/clients/rpc_user"
"github.com/bqxtt/book_online/rpc/model/base"
"github.com/bqxtt/book_online/rpc/model/userpb"
"strconv"
)
type IUserService in... |
package gate
import (
"hub000.xindong.com/rookie/rookie-framework/protobuf"
"hub000.xindong.com/rookie/rookie-framework/log"
)
type MsgHandler interface {
Unmarshal(int, []byte, string) (protobuf.CSRequest, error)
Marshal(resp protobuf.CSResponse) (*Message, error)
}
type Processor struct {
g *WSGate
Route... |
package cmd
import (
// 3rd Party
"github.com/spf13/cobra"
)
// Represents the create labels command
var createLabelsCmd = &cobra.Command{
Use: "create",
Short: "Creates a new set of github labels",
Run: GithubLabelCreatorHandler,
}
func init() {
createLabelsCmd.Flags().StringVarP(&Application, "applicatio... |
package db
import (
"github.com/pkg/errors"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/YusukeKishino/go-blog/config"
)
func ConnectDB(conf *config.AppConfig) (*gorm.DB, error) {
var logLebel logger.LogLevel
if config.IsDev() {
logLebel = logger.Info
} else {
logLebel = logger... |
package pgsql
import (
"bytes"
"encoding/hex"
"time"
)
const (
dateLayout = "2006-01-02"
timeLayout = "15:04:05.999"
timetzLayout = "15:04:05.999-07:00"
timestampLayout = "2006-01-02 15:04:05.999"
timestamptzLayout = "2006-01-02 15:04:05.999-07"
)
var noZone = time.FixedZone("", 0)
func... |
package records
import (
"strings"
"github.com/coredns/caddy"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
clog "github.com/coredns/coredns/plugin/pkg/log"
"github.com/miekg/dns"
)
var log = clog.NewWithPlugin("records")
func init() { plugin.Register("records", setup) }
fu... |
package model
import (
"testing"
)
var U User
func loginUser() User {
var u User
u.Username = "naughtydevelopement"
u.Password = "12341234"
return u
}
func TestSignUpUser(t *testing.T) {
//config.Init()
//Init()
//db.LogMode(true)
//U = loginUser()
//up, err := SignUp(U)
//if err != nil {
// t.Error(err... |
// Copyright 2015 Alexey Martseniuk. All rights reserved.
// Use of this source code is governed by a MIT license
// that can be found in the LICENSE file.
package linq_test
import (
"bytes"
"fmt"
"github.com/zx48/linq"
)
func Example() {
res, err := linq.FromSequence(2, 3, 5).Where(func(v linq.T) bool {
retu... |
package main
import (
"fmt"
)
func main() {
fmt.Println(suggestedProducts([]string{
"mobile", "mouse", "moneypot", "monitor", "mousepad",
}, "mouse"))
}
func suggestedProducts(products []string, searchWord string) [][]string {
t := Constructor()
for _, p := range products {
t.Insert(p)
}
var ans [][]stri... |
package main
import (
"fmt"
"myGo/genereate/shell/types"
)
func main() {
var pl types.PersonList
pl = append(pl, &types.Person{Name: "Jane", Age: 32})
pl = append(pl, &types.Person{Name: "Ed", Age: 27})
pl2 := pl.Filter(func(p *types.Person) bool {
return p.Age > 30
})
for _, p := range pl2 {
fmt.Println... |
package visagoapi
import (
"fmt"
"sort"
"strings"
)
const (
// ColorsFeature is the value to enable the color features.
ColorsFeature = "colors"
// FacesFeature is the value to enable the face detection features.
FacesFeature = "faces"
// TagsFeature is the value to enable the tagging features.
TagsFeature... |
package gorm_test
import (
"fmt"
gorm "github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"log"
"sync"
"testing"
"time"
)
type (
PersonX struct {
ID uint32 `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"`
Name string `gorm:"size:255;not null;unique" json:"Name"`
Nickname... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package utils
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
type testWriter struct {
fn func(string)
}
func (t *testWriter) Write(p []byte) (int, error) {
t.fn(string(p))
return len(p), nil
}
func TestProgress(t *testi... |
// Copyright 2017 Vector Creations Ltd
//
// 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 agre... |
package sdl
type SDL_TouchID int64
type SDL_FingerID int64
type SDL_Finger struct {
Id SDL_FingerID
X float32
Y float32
Pressure float32
}
|
package game
import (
"fmt"
"math/rand"
)
// GeneratePlayers generate players
func GeneratePlayers() []Player {
var roles = basicConfiguration()
roles = shuffle(roles)
players := make([]Player, len(roles))
for i, r := range roles {
players[i].role = r
players[i].id = i + 1
}
for _, v := range players {
... |
package main
import (
"../lib/libocit"
"encoding/json"
"fmt"
"os"
"path"
"time"
)
type ServerConfig struct {
TSurl string
CPurl string
Debug bool
}
//public variable
var pub_config ServerConfig
var pub_casedir string
//TODO the following container function should move the the container service
func apply_... |
package mat
import (
"fmt"
"github.com/stretchr/testify/assert"
"math"
"testing"
)
func TestRotateX(t *testing.T) {
point := NewPoint(0, 1, 0)
halfQuarterRotation := RotateX(math.Pi / 4)
fullQuarterRotation := RotateX(math.Pi / 2)
p2 := MultiplyByTuple(halfQuarterRotation, point)
assert.Equal(t, 0.0, p2.Get... |
package todo
import (
"context"
"fmt"
)
type SessionRepo interface {
NextID(context.Context) (SessionID, error)
Pull(context.Context) (*Session, error)
Push(context.Context, *Session) error
Delete(context.Context) error
}
func NewSession(id SessionID, userID UserID) (*Session, error) {
s := new(Session)
if ... |
package configs
import (
"fmt"
"github.com/gomodule/redigo/redis"
"os"
)
var (
redisConn redis.Conn
redisErr error
)
func InitRedis() {
var port = os.Getenv("REDIS_PORT")
redisConn, redisErr = redis.Dial("tcp", "localhost:"+port)
if redisErr != nil {
fmt.Println("Redis Connection Error:", err.Error())
r... |
package websocket
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
func upgrade(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) {
conn, ... |
/*
Copyright 2019 Packet 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 writing, software
dis... |
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package main
import (
//"io/ioutil"
"log"
"net/http"
"net/url"
)
func main() {
//Get方法
resp, err := http.Get("http://localhost:8000/")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
//body, err := ioutil.ReadAll(resp.Body)
//_, err = http.PostForm("http://localhost:8000/PostForm",
//url.Value... |
package main
import (
"fmt"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
var head, tmpNode, nextNode *ListNode
for ;l1 != nil && l2 ... |
package main
import (
"io"
"io/ioutil"
"net/http"
)
type RawTransactionResponse struct {
Success bool `json:"success"`
ErrMsg string `json:"errmsg"`
}
func sendRawTransaction(tx io.Reader) (resp RawTransactionResponse, err error) {
for _, endpoint := range esploras() {
w, errW := http.Post(endpoint+"/tx",... |
package main
import (
"fmt"
"github.com/bitmaelum/bitmaelum-suite/internal"
"github.com/bitmaelum/bitmaelum-suite/internal/config"
"github.com/bitmaelum/bitmaelum-suite/internal/container"
"github.com/bitmaelum/bitmaelum-suite/pkg/address"
"github.com/sirupsen/logrus"
)
type options struct {
Config string `sh... |
// generated by stringer -type=ZookeeperError; DO NOT EDIT
package gozoo
import "fmt"
const _ZookeeperError_name = "ZooOkZooSystemErrorZooRuntimeInconsistencyErrorZooDataInconsistencyErrorZooConnectionLossErrorZooMarshallingErrorZooUnimplementedErrorZooOperationTimeoutErrorZooBadArgumentsErrorZooInvalidStateErrorZoo... |
package main
import (
"fmt"
"log"
"os"
"os/exec"
"strconv"
"syscall"
"time"
)
func main() {
var cmdstr string
var sampletime int
if len(os.Args) >= 2 {
fmt.Println(os.Args[1])
cmdstr = os.Args[1]
} else {
fmt.Println("/usr/bin/yes")
cmdstr = "/usr/bin/yes"
}
if len(os.Args) >= 3 {
var err er... |
package peach
import (
"fmt"
)
var (
drivers = make(map[string]Driver)
)
//RegistDriver regist driver
func RegistDriver(name string, driver Driver) {
if nil == driver {
panic("driver is nil")
}
drivers[name] = driver
}
//GetDriver return Driver by DriverName
func GetDriver(name string) (Driver, error) {
dri... |
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/gofiber/fiber"
"github.com/jinzhu/gorm"
"os"
)
import "github.com/superDeano/media-directory/media"
import "github.com/superDeano/media-directory/dao"
func main() {
app := fiber.New()
setUpAppRoutes(app)
setUpDatabase()
defer closeD... |
package main
import "fmt"
func main() {
var price = map[string]int{"chicken_nugget": 2000, "sate": 3000}
fmt.Println("Sate ayam ", price["sate"])
}
|
package events
import (
"encoding/json"
"fmt"
)
var validProjectEventActions = map[string]string{
ProjectAdded: ProjectAdded,
VersionAdded: VersionAdded,
VulnerabilityAdded: VulnerabilityAdded,
}
// ProjectEventAction represents possible actions related to a project event
type ProjectEventAction str... |
package runner
// This file contains the implementation of functions related to AWS.
//
// Especially functions related to the credentials file handling
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/go-stack/stack"
"github.com/karlmutch/errors"... |
package main
//func main() {
// res := time.Now()
//fmt.Println(res)
//fmt.Println(res.Year())
//fmt.Println(int(res.Month()))
//fmt.Println(int(res.Weekday()))
//fmt.Println(res.Hour())
//fmt.Println(res.Minute())
//fmt.Println(res.Second())
//格式化日志或者时间
//fmt.Printf("%02d/%02d/%02d %02d:%02d:%02d\n",res.Year(),res.M... |
package oauth2
import "crypto/rsa"
// Grant type interface.
type GrantTypeInterface interface {
// Return the grant identifier that can be used in matching up requests.
GetIdentifier() GrantType
// TODO Respond to an incoming request.
RespondToAccessTokenRequest(request *RequestWapper, responseType ResponseTypeIn... |
package domain
// Neighbor is the format that represents a neighbor in FAISS
type Neighbor struct {
ID uint64 `json:"id"`
Score float32 `json:"score"`
}
// Neighbors represents a list of Neighbor
type Neighbors []Neighbor |
//+build ignore
package main
import (
"flag"
"fmt"
"log"
"math"
"math/big"
"os"
"text/template"
"github.com/pkg/errors"
)
func main() {
var out string
flag.StringVar(&out, "o", "extra_test.go", "test cases output path")
flag.Parse()
if err := dumpTest(out); err != nil {
log.Fatalf("%+v", err)
}
}
fu... |
package cloudflare
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// AccessOrganization represents an Access organization.
type AccessOrganization struct {
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time ... |
package main
import (
"fmt"
"os"
)
func main() {
fmt.Printf("Starting program\n")
var files []*os.File
var fileNames []string
for {
n := len(fileNames)
name := fmt.Sprintf("%d.test.txt", n)
os.Remove(name)
f, err := os.Create(name)
if err != nil {
fmt.Printf("opening file %s failed with %s\n", name... |
/*
Challenge
Given a positive integer n, count the number of n×n binary matrices (i.e. whose entries are 0 or 1) with exactly two 1's in each rows and two 1's in each column.
Here are a few examples of valid matrices for n=4:
1100 1100 1100
1100 0011 0110
0011 1100 0011
0011... |
/*
* Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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://... |
package s3seek_test
import (
"bufio"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/brentp/go-athenaeum/s3seek"
)
func TestRead(t *testing.T) {
sess := session.Must(session.NewSession())
svc := s3.New(sess, aws.NewConfig().... |
package store
type Type string
const (
Type_Devices Type = "devices"
Type_Device Type = "device"
Type_Resource Type = "resource"
)
type Subscription struct {
SubscriptionID string
Type Type
LinkedAccountID string
DeviceID string
Href string
SigningSecret string
}
|
package db
import (
"sync"
"github.com/go-redis/redis/v8"
)
var (
rdb *redis.Client
once sync.Once
)
func ConnectRedis() {
once.Do(func() {
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
})
}
func PoolRDB... |
package account
import (
"errors"
)
type Account struct {
Username string
Balance float64
Transactions []Transaction
}
func (a *Account) Transfer(to string, amt float64) error {
return a.Withdraw(amt)
}
func (a *Account) Withdraw(amt float64) error {
if a.Balance < amt {
return errors.New("not enoug... |
package main
import (
"fmt"
"math/big"
"os"
"strconv"
"time"
)
var t0, t1 time.Time
var fib_number string
func fibonacci(n int) []*big.Int {
var fib_arr []*big.Int
if n == 0 {
fib_arr = append(fib_arr, big.NewInt(0))
} else {
fib_arr = append(fib_arr, big.NewInt(0), big.NewInt(1))
sum := big.NewInt(0)
... |
package main
import (
"code.google.com/p/go.crypto/bcrypt"
"crypto/rand"
"fmt"
"github.com/johnnylee/ttlib"
"log"
"os"
)
func printUsage() {
fmt.Println("")
fmt.Printf("Usage: %v <directory> <user_name>\n",
os.Args[0])
fmt.Println("")
fmt.Println("directory:")
fmt.Println(" The directory in which to s... |
package lessorio
const (
GroupName = "lessor.io"
)
|
package adventutilities
import (
"io/ioutil"
"strconv"
"strings"
"log"
)
func Check(e error) {
if e != nil {
panic(e)
}
}
func CheckResult(testName string, actual int, expected int)(success bool){
if(actual == expected){
log.Println("Test:", testName, "successful, actual",actual,"== expected",expected)
... |
package main
import (
"fmt"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func max2(a, b int) int {
if a > b {
return a
}
return b
}
func min2(a, b int) int {
if a < b {
return a
}
return b
}
func bstSum(root *TreeNode, maxBSTSize *int) (bool, int, int, int) {
if root.Left =... |
package routes
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/davelaursen/idealogue-go/Godeps/_workspace/src/github.com/gorilla/mux"
"github.com/davelaursen/idealogue-go/services"
)
// RegisterIdeaRoutes registers the /ideas endpoints with the router.
func RegisterIdeaRoutes(r *mux.Router, enc Encoder, ideaS... |
package template
import "encoding/json"
const TemplateTypeButton TemplateType = "button"
// ButtonTemplate is a template
type ButtonTemplate struct {
TemplateBase
Text string `json:"text,omitempty"`
Buttons []Button `json:"buttons,omitempty"`
}
func (ButtonTemplate) Type() TemplateType {
return TemplateTyp... |
package conversion
import (
"encoding/json"
"strconv"
"strings"
"time"
)
const (
DATE_TIME_FORMAT_STRING string = "2006-01-02 15:04:05"
)
/*
ToString 获取变量的字符串值
浮点型 3.0将会转换成字符串3, "3"
非数值或字符类型的变量将会被转换成JSON格式字符串
*/
func ToString(value interface{}) string {
if value == nil {
return ""
}
switch value.(type)... |
package testdata
import (
"io/ioutil"
"path/filepath"
"testing"
)
// LoadExampleAnalyseRequest reads the example request from exampleAnalyseRequest.json
func LoadExampleAnalyseRequest(t *testing.T) []byte {
return loadTestdata(t, "exampleAnalyseRequest.json")
}
// LoadExampleRequest reads the example request fro... |
//go:build !js
// Package checkbox provides a checkbox connected to a query parameter.
package checkbox
import (
"fmt"
"html/template"
"net/url"
"strconv"
"github.com/shurcooL/htmlg"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// New creates the HTML for a checkbox instance. Its checked value is d... |
package main
import (
"fmt"
"time"
)
func main() {
var no = 10
switch {
case no < 0:
fmt.Println(no, " is negative")
default:
fmt.Println(no, " is positive")
}
no = -11
switch no % 2 {
case 1:
fmt.Println(no, " is odd")
case 0:
fmt.Println(no, " is even")
default:
fmt.Println(no, " is negat... |
package main
import (
"fmt"
"os"
)
func main() {
word := os.Args[1]
greet := "greetings"
switch l := len(word); word {
case "hi":
fmt.Println("Very formal")
fallthrough
case "hello":
fmt.Println("Hi, yourself")
case "farewell":
case greet:
fmt.Println("Salutations!")
case "goodbye", "bye":
fmt.Pri... |
package diamond
import (
"errors"
"strings"
)
const testVersion = 1
// Given a letter, print a diamond like this:
// Diamond for letter 'C':
// ··A·· 2 0 2 C - A = 2
// ·B·B· 1 1 1
// C···C 0 3 0
// ·B·B· 1 1 1
// ··A·· 2 0 2
func Gen(char byte) (string, error) {
if char < 'A' || char > 'Z' {
return... |
package main
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/lxc/lxd/shared"
)
// Loader functions
func containerKVMCreate(d *Daemon, args containerArgs) (container, error) {
fmt.Println("Creating KVM container...")
// Create the container struct
c := &containerKVM{
&containerLXC{
daemon: ... |
package thorf
import (
"bytes"
"strings"
"testing"
)
// These tests were borrowed from the excellent exercism.io "forth" exercise:
// https://github.com/exercism/go/tree/5446524b6/exercises/forth
func runTest(input string) (string, error) {
var buf bytes.Buffer
m := NewMachine(&buf)
err := m.Eval(strings.NewR... |
package main
import (
"CCServer.com/cccompress"
"CCServer.com/ccconvert"
"flag"
"fmt"
"image"
"image/jpeg"
"image/png"
"log"
"os"
"time"
)
var (
bConvert bool
iQuality int
sSrc string
sDst string
bCompress bool
bDecompress bool
bOverWrite bool
iMode int
iWorkerNum int
sTarget ... |
/*
Copyright © 2023 SUSE LLC
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 initialize
import (
"github.com/gin-gonic/gin/binding"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
"shop-web/user-api/global"
customValidator "shop-web/user-api/validator"
)
func BindingValidate() {
if v, ok := binding.Validator.Engine().(*validator.Valida... |
package main
import (
"fmt"
)
func main() {
// const norm1 = 2
// const norm3 = 4
// const norm2 string = "asd";
// var area int
// area = norm1 * norm3
// fmt.Printf("面积是 : %d", area)
// const(
// read = 1
// face = 2
// less = 3
// )
// const (
// a = 1
// b = 2
// c = 3
// )
// fmt.Printl... |
package compute
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// NATRule represents a Network Address Translation (NAT) rule.
// NAT rules are used to forward IPv4 traffic from a public IP address to a server's private IP address.
type NATRule struct {
ID string `json:"id"`
NetworkDomainI... |
package sgs
import (
"io/ioutil"
"net/http"
"strconv"
)
type authSrvPrx interface {
setServerURI(string)
vclient(clientID int, token string) bool
enableTestClients(bool)
}
type sgasPrx struct {
serverURI string
testEnabled bool
}
func (me *sgasPrx) enableTestClients(enabled bool) {
me.testEnabled = enabl... |
package model
// Image model.
type Image struct {
File string `json:"file" bson:"file" binding:"required"`
AssignedCategories []string `json:"assignedCategories" bson:"assignedCategories"`
ProposedCategories []string `json:"proposedCategories" bson:"proposedCategories"`
StarredCategory *string ... |
package leaflet
import (
"sync"
"github.com/gowasm/gopherwasm/js"
)
// NewCoordinate creates a new coordinate
func NewCoordinate(lat, lng float64) *Coordinate {
return &Coordinate{
lat: lat,
lng: lng,
}
}
func (c *Coordinate) JSValue() js.Value {
c.valueOnce.Do(func() {
v := gL.Call("latLng", c.lat, c.ln... |
package common
import (
"errors"
"os"
"path/filepath"
"strings"
"unicode/utf8"
"github.com/joho/godotenv"
)
const (
// EmailSuffix is the accepted email suffix.
EmailSuffix = "@mastersny.org"
// MaxRecipients is the maximum amount of recipients on one post.
MaxRecipients = 10
// MaxImages is the maximum... |
package main
import (
"fmt"
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World 👋!")
})
app.Get("/:name", func(c *fiber.Ctx) error {
return c.JSON(&fiber.Map{
"Message": fmt.Sprintf("Hello %s", c.Params("name")),
... |
package main
import (
"context"
"fmt"
"log"
"time"
"golang.org/x/sync/errgroup"
)
func main() {
// 1つのサブタスクでエラーが発生したときに他の全てのサブタスクをキャンセルできる
// withcontext使わない場合はGroup()を使う
eg, ctx := errgroup.WithContext(context.Background())
ps := []string{"tom", "jhon", "yam"}
for _, p := range ps {
eg.Go(func() error {... |
// 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 i... |
// -----------------------------------------------------------------------------
// Web package used for encapsulating web controllers.
// -----------------------------------------------------------------------------
package controller
import (
"bytes"
"encoding/gob"
"godistributed-rabbitmq/common"
"godistributed-... |
package file
import "io"
func SetOsCreate(f func(name string) (closer io.WriteCloser, err error)) {
osCreate = f
}
|
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package libService
import "io"
type IFormatter interface {
Format(name, version string) IFormatter
WriteOut(writer io.Writer) error
}
// 格式化信息结构体
type FormatterStruct struct {
PackageName string
ImportList map[string]ImportItem
Name string
StructName string
Version string
FieldList []Field
}
... |
package main
import (
"encoding/json"
"log"
"net/http"
"net/url"
"text/template"
)
var homeTemplate = template.Must(template.ParseFiles("home.html"))
var searchURL = "http://elastic:9200/codecivil/article/_search"
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
homeTemplate.... |
package node
import "go-neural_network/bookForm"
type Book struct {
Form
}
func CreateBook(entity DataEntity) (book FormInterface) {
book = &Book{}
book.Init(bookForm.CollectionProperties)
for key, value := range entity.Properties {
book.SetProperty(key, value)
}
book.SetResult(entity.Result)
return
}
func... |
package routers
import (
"github.com/barrydev/api-3h-shop/src/common/response"
"github.com/barrydev/api-3h-shop/src/controllers"
"github.com/gin-gonic/gin"
)
func BindUser(router *gin.RouterGroup) {
router.POST("/register", func(c *gin.Context) {
handle := response.Handle{Context: c}
handle.Try(controllers.... |
package health
import (
"github.com/square/p2/pkg/types"
)
// Result stores the health state of a service.
type Result struct {
ID types.PodID
Node types.NodeName
Service string
Status HealthState
}
// ResultList is a type alias that adds some extra methods that operate on the list.
type ResultList []R... |
package transactions
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/flow-hydraulics/flow-wallet-api/configs"
"github.com/flow-hydraulics/flow-wallet-api/datastore"
"github.com/flow-hydraulics/flow-wallet-api/errors"
"github.com/flow-hydraulics/flow-wallet-api/flow_helpers"
"github.com/flow-hydraul... |
package handler
import (
"HumoAcademy/models"
"github.com/gin-gonic/gin"
"net/http"
)
func (h *Handler) adminSignUp (c *gin.Context) {
var input models.Admin
if err := c.BindJSON(&input); err != nil {
NewErrorResponse(c, http.StatusBadRequest, "bad","invalid input body")
return
}
id, err := h.services.Ad... |
package function
import (
"net/http"
"net/http/httptest"
"testing"
)
//
//import (
// "bytes"
// "github.com/buger/jsonparser"
// "io/ioutil"
// "log"
// "net/http"
// "net/http/httptest"
// "testing"
//)
func TestGet(t *testing.T) {
t.Log("testing GET....")
}
func TestPost(t *testing.T) {
t.Log("testing POST.... |
package query
import (
"time"
"github.com/gofrs/uuid"
)
type FarmEventQuery interface {
FindAllByID(farmUID uuid.UUID) <-chan QueryResult
}
type FarmReadQuery interface {
FindByID(farmUID uuid.UUID) <-chan QueryResult
FindAll() <-chan QueryResult
}
type ReservoirEventQuery interface {
FindAllByID(reservoirUI... |
package crypto
import (
"crypto/aes"
"crypto/cipher"
)
func AESDecryptBytes(payload []byte) ([]byte, error) {
iv, cipherText := payload[:16], payload[16:]
block, err := aes.NewCipher([]byte("fx6v22kwCjm9oasmMnymhpVJa6H4Xpkc"))
if err != nil {
return []byte{}, err
}
aesgcm, err := cipher.NewGCMWithNonceSize... |
package statik
//This just for fixing the error in importing empty github.com/ColorPlatform/color-sdk/client/lcd/statik
|
package kvdecoder
import (
"fmt"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/hashing"
"github.com/iotaledger/wasp/packages/kv"
... |
package tar
import (
"archive/tar"
"fmt"
"io"
"os"
gopath "path"
fp "path/filepath"
"strings"
)
type Extractor struct {
Path string
Progress func(int64) int64
}
func (te *Extractor) Extract(reader io.Reader) error {
tarReader := tar.NewReader(reader)
// Check if the output path already exists, so we ... |
package main
import (
"fmt"
"net"
"net/http"
"net/http/fcgi"
)
type FastCGIServer struct{}
func (s FastCGIServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/html")
str := fmt.Sprintf("<b>RequestURI</b>:%s<br />\n<b>User-Agent</b>:%s\n",
r... |
package main
import (
"fmt"
"time"
"github.com/docker/distribution/manifest/schema1"
"github.com/docker/distribution/notifications"
"gopkg.in/mgo.v2/bson"
)
// ProcessEventPullOrPush returns a key->value map (bson.M) that can be
// used to upsert (aka. insert or update) a statistics document about a
// reposito... |
package main
import "fmt"
type CPU struct{}
type Memory struct{}
type SolidStateDrive struct{}
func (cpu CPU) freeze() {
fmt.Println("Freezing processor")
}
func (cpu CPU) jump(position string) {
fmt.Println("Jumping to:", position)
}
func (cpu CPU) execute() {
fmt.Println("Executing")
}
fu... |
package queries
import (
"github.com/graphql-go/graphql"
"go_graphql/petstore/db"
"go_graphql/petstore/types"
"log"
"strconv"
)
//GetOwnerQuery queries and replies with single query
func GetOwnerQuery() *graphql.Field {
return &graphql.Field{
Type: types.OwnerType,
Description: "Get single Owner",
... |
// nil.
package main
import "fmt"
func main() {
var ss []string
fmt.Printf("ss==nil:%v\n", ss == nil)
fmt.Println("len", len(ss))
fmt.Println(ss[:] == nil)
}
|
package models
// the request model for Comment Parsing
type CommentParsingRequest struct {
PackageName string // the package name to search for comments
Tokens []string // the tokens/words to search for
}
// the result model for Comment Parsing
type CommentParsingResult struct {
PackageName string ... |
package zabbix
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
var (
UserPostTemplate = `{
"jsonrpc": "2.0",
"method": "user.create",
"params": {
"alias": "%v",
"passwd": "%v",
"usrgrps": [
{
"usrgrpid": "%v"
}
],
"user_medias": [
{
"mediatypeid": "1",
"sendt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.