text stringlengths 11 4.05M |
|---|
package entity
import (
"time"
)
type UmsAdminLoginLog struct {
Id int64 `json:"id" xorm:"pk autoincr BIGINT(20) 'id'"`
AdminId int64 `json:"admin_id" xorm:"default NULL BIGINT(20) 'admin_id'"`
CreateTime time.Time `json:"create_time" xorm:"default 'NULL' DATETIME 'create_time'"`
Ip st... |
package dictionary
func Search() {
}
|
package session_utils
import (
"goslib/logger"
"goslib/redisdb"
)
type Session struct {
Uuid string
AccountId string
ServerId string
SceneId string
ConnectAppId string
GameAppId string
Token string
}
func Find(accountId string) (*Session, error) {
uuid := "session:" + accountI... |
package cart
import "testing"
func TestAddAndGetProductsInCart(t *testing.T) {
c := New()
c.Add("")
c.Add("みかん")
products := c.GetAll()
if len(products) != 2 {
t.Fatalf("商品の数が想定と違う。(商品数:%d)", len(products))
}
if products[0] != "りんご" && products[1] != "りんご" {
t.Error("りんごがカートに入っていない。")
t.Log("カートの中身:", p... |
//Package Dbcache database
package base
import (
"sync"
)
var DbCache = &CacheModel{BaseModel{Mutex: new(sync.Mutex)}}
type CacheModel struct {
BaseModel
}
|
package rabbitmq
import (
"crypto/md5"
"errors"
"fmt"
"queueman/libs/aliyun"
"strings"
"sync"
amqpReconnect "github.com/isayme/go-amqp-reconnect/rabbitmq"
)
// Config configure for rabbitmq
type Config struct {
Scheme string // amqp or amqps
Host string
Port int32
User string... |
/*
Copyright © 2019 The Falco Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... |
package main
import (
"flag"
"os"
"io/ioutil"
"text/template"
"gopkg.in/yaml.v2"
"github.com/Masterminds/sprig"
)
var (
datafileFlag = flag.String("data", "", "Datafile")
tmplFlag = flag.String("tmpl", "", "Template")
tmpl []byte
data map[interface{}]interface{}
)
func init() {
flag.Parse()
stat, ... |
package pandorasbox
import (
"path/filepath"
"github.com/capnspacehook/pandorasbox/vfs"
)
func IsAbs(path string) bool {
if _, ok := ConvertVFSPath(path); ok {
return vfs.IsAbs(path)
}
return filepath.IsAbs(path)
}
func Clean(path string) string {
if vfsPath, ok := ConvertVFSPath(path); ok {
path = vfsPa... |
package center
import (
"net/http"
"sync"
"time"
"github.com/golang/glog"
"github.com/gorilla/websocket"
"github.com/empirefox/ic-client-one-wrap"
"github.com/empirefox/ic-client-one/connector"
"github.com/empirefox/ic-client-one/storage"
"github.com/empirefox/ic-client-one/wsio"
)
type central struct {
w... |
package test
import (
"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/etf1/kafka-transformer/pkg/transformer"
)
type unstableTransformer struct {
passthrough transformer.Transformer
}
// NewUnstableTransformer creates a transformer which will panic when a message is equal to "panic"
func NewUnstabl... |
package Extract
import (
"fmt"
"sort"
)
const NKeyword = 10
const d = 0.85f
const max_iter = 200
const min_diff = 0.001f
type TextRankKeyword struct {
}
func NewTextRankKeyword() (rcvr *TextRankKeyword) {
rcvr = &TextRankKeyword{}
return
}
func (rcvr *TextRankKeyword) GetKeyword(title string, content string) (s... |
package scanner
import "encoding/json"
//Source identifies the provider of external scans
type Source struct {
Name string `json:"name"`
URL string `json:"url"`
}
//ExternalScan is a representation of a scan result not performed by the Ion system
type ExternalScan struct {
Coverage *ExternalCoverage `j... |
// Copyright 2018 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 单数
// ----------------- 超时的动态规划 -------------------
func nthUglyNumber(n int) int {
countOfGottenUglyNumber := 1
isUglyNumber := make(map[int]bool)
isUglyNumber[1] = true
readingNumber := 1
for countOfGottenUglyNumber < n {
readingNumber++
// 这还能进行一些去冗余优化
if readingNumber%2 == 0 && isUglyNumber[read... |
package main
/*
Problem 7:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
*/
import ( "fmt"
"math" )
func is_prime(n int) bool {
if ( n < 4 && n > 1 ) { return true }
if ( n % 2 == 0 ) { return false }
... |
package googlevision
import (
"fmt"
"os"
"google.golang.org/api/vision/v1"
"github.com/kaneshin/pigeon"
"github.com/kaneshin/pigeon/credentials"
"github.com/lucasb-eyer/go-colorful"
"github.com/nats-io/nuid"
"github.com/zquestz/visago/visagoapi"
)
func init() {
visagoapi.AddPlugin("googlevision", &Plugin{}... |
package bounds
import (
"runtime"
"res"
)
type Boundkey_t int
const (
B_ASPACE_T_K2USER_INNER Boundkey_t = iota
B_ASPACE_T_USER2K_INNER
B_BITMAP_T_APPLY
B_ELF_T_ELF_LOAD
B_FS_T_FS_NAMEI
B_FS_T_FS_OP_RENAME
B_FS_T__ISANCESTOR
B_FUTEX_T_FUTEX_START
B_IMEMNODE_T_BMAPFILL
B_IMEMNODE_T__DESCAN
B_IMEMNODE_T_... |
package querylog
import (
"encoding/json"
"gopkg.in/natefinch/lumberjack.v2"
)
type QueryLogger interface {
Write(*Entry) error
}
// easyjson:json
type Entry struct {
Time int64
Origin string
Name string
Qtype uint16
Rcode int
Answers int
Targets []string
LabelName string... |
package models
import (
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego"
"math/big"
)
type User struct {
Id int `json:"id" orm:"column(id)"`
Addr string `json:"addr" orm:"column(addr)"`
CreateAt string `json:"create_at" orm:"column(create_at)"`
Status int `json:"status" orm:"column(s... |
// Copyright 2016 Google Inc. 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 applicable... |
package rp_kit
import (
"os"
"strings"
)
//获取环境变量值(不区分大小写)
func EnvExistsValue(name, value string) bool {
v := os.Getenv(name)
if v == "" {
return false
}
v = strings.ToLower(v)
value = strings.ToLower(value)
vs := strings.Split(v, ",")
for _, item := range vs {
if item == value {
return true
}
}
... |
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func readMultiLines() string {
var str string
input := bufio.NewScanner(os.Stdin) //Creating a Scanner that will read the input from the console
for input.Scan() {
if input.Text() == "" {
break
}
str += input.Text()
}
return str
}
func main() {
... |
package distances
import (
"testing"
)
func TestEditDistance(t *testing.T) {
t.Run("Simple DNA Example with len 5 and 6", func(t *testing.T) {
//Test Cases
seqA := "BCACD"
seqB := "DBADAD"
want := 4
assertDistance(t, want, seqA, seqB)
})
t.Run("One Sequence Empty Should be only insertions", func(t *te... |
package game
const (
asteroidSpeed = 100
asteroidSpin = 2
)
var asteroidPoints = []float32{
-10, 0,
-5, 7,
-3, 4,
1, 10,
5, 4,
10, 0,
5, -6,
2, -10,
-4, -10,
-4, -5,
-10, 0,
}
type Asteroid struct {
*Sprite
parent bool
}
func newAsteroid() *Asteroid {
new_asteroid := &Asteroid{
parent: true,
}
... |
package gobinassethandler
import (
"goabinsample/swaggerassets"
"net/http"
"path/filepath"
"strings"
"github.com/goadesign/goa"
"github.com/mattetti/filebuffer"
"golang.org/x/net/context"
)
// GobinAssetHandler go-bindataでバイナリ化したAssetを参照するためのFileHandler
func GobinAssetHandler(path, filename string) goa.Handl... |
package concurrent
import (
"fmt"
"testing"
"time"
)
var maxWorker = 10 // 最多10个工作者
var maxJobs = 100000
func TestDispatcher_Start(t *testing.T) {
workerQueue := make(chan chan interface{}, maxWorker)
workers := make([]*Worker, 0)
for i := 0; i < maxWorker; i++ {
workers = append(workers, NewWorker(i, worker... |
/*
Given a string containing only the characters x and y, find whether there are the same number of xs and ys.
balanced("xxxyyy") => true
balanced("yyyxxx") => true
balanced("xxxyyyy") => false
balanced("yyxyxxyxxyyyyxxxyxyx") => true
balanced("xyxxxxyyyxyxxyxxyy") => false
balanced("") => true
balanced("x") => false... |
/**
* Create a Munki manifest based on a template
* License: Apache 2.0
* Author: Antti Pettinen / Intelligent Apps GmbH
* Last Modified Date: 08.05.2019
* Last Modified By: Antti Pettinen
*/
package main
import (
"os"
"github.com/groob/plist"
"flag"
"fmt"
"path/filepath"
)
type manifestTemplate struct {
... |
package cmd
import (
"fmt"
"log"
"os"
"text/tabwriter"
"github.com/HakShak/sanemame/db"
"github.com/boltdb/bolt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// categoriesCmd represents the categories command
var categoriesCmd = &cobra.Command{
Use: "categories",
Short: "List categories from Catve... |
package config
import (
"github.com/golang/glog"
"os"
"strconv"
)
type EnvKey string
const (
LocalPort EnvKey = "PENELOPE_PORT"
PprofActiveEnv EnvKey = "PPROF_ACTIVE"
DefaultBucketStorageClass EnvKey = "DEFAULT_BUCKET_... |
package runner
import (
"io/ioutil"
"gopkg.in/yaml.v2"
)
// ConfigFile is the config file.
type ConfigFile struct {
Server Server `yaml:"server"`
Data `yaml:",inline"`
}
// Server is the connection details.
type Server struct {
URL string `yaml:"url"`
Port string `yaml:"port"`
}
// Data of BMC resources.
... |
package controller
import (
"encoding/json"
"fmt"
"net/http"
"github.com/ksw95/GoIndustrialProject/API/models"
"github.com/labstack/echo"
"golang.org/x/crypto/bcrypt"
)
//New User Account Creation
func (dbHandler *DBHandler) Register(c echo.Context) {
//Receive parameters from client
user := models.Account{}... |
package bot
import "fmt"
type StatusCommand struct {
}
func (c *StatusCommand) Execute(args []string) (string, error) {
fmt.Printf("Status command executed with %s", args)
fmt.Println()
cl := CommandLine{[]string{}, []Option{}}
cl.Parse(args, options)
var err error
if c.verify(&cl) {
_, err = RunCommand(&c... |
// Slice using literals
/*
You can create a slice using the slice literal.
The creation of slice literal is just like an array literal,
but with one difference you are not allowed to specify
the size of the slice in the square braces[].
*/
package main
import "fmt"
func main() {
// Creating a slice
va... |
package main
import (
"context"
"encoding/json"
"fmt"
"html/template"
"net/http"
"os"
"cloud.google.com/go/pubsub"
"contrib.go.opencensus.io/exporter/stackdriver"
"contrib.go.opencensus.io/exporter/stackdriver/monitoredresource"
"contrib.go.opencensus.io/exporter/stackdriver/propagation"
"github.com/go-chi... |
package main
type Player struct {
entity *Entity
}
func NewPlayer() *Player {
player := &Player{}
player.entity = NewEntity("Player")
player.entity.glyph = NewGlyph('@')
return player
}
|
// Copyright 2018 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 nntp
// Implementation of linked-list queues
type Queue struct {
first, last *queueNode
}
type queueNode struct {
data interface{} // payload of specific type
Next *queueNode
}
// Create an empty queue.
func NewQueue() *Queue {
return &Queue{}
}
// Is q empty?
func (q *Queue) Empty() bool {
return q.fi... |
package main
import (
"fmt"
)
func main() {
ca := "L fdph, L vdz, L frqtxhuhg"
for i, c := range ca {
if c >= 'a' && c <= 'z' {
c = c - 3
if c < 'a' {
c = c + 26
}
} else if c >= 'A' && c <= 'Z' {
c = c - 3
if c < 'A' {
c = c + 26
}
}
fmt.Printf("%v %c\n", i, c)
}
}
|
package main
import "fmt"
type TradeType int32
const (
TradeType_NULL TradeType = iota
TradeType_BUY
TradeType_SELL
)
type CallType int32
const (
CallType_NULL CallType = iota
CallType_CALL
CallType_PUT
CallType_FUTURE
)
type Trade struct {
StrikePrice float64
Premium float64
OpenInterest float64
TradedV... |
package main
import (
flag "github.com/ogier/pflag"
// "io"
"bufio"
"fmt"
"os"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func processInputFile(fileName string) {
f, err := os.Open(fileName)
check(err)
defer f.Close()
scanner := bufio.NewScanner(f)
lineNo := 0
for scanner.Scan() {
fmt.Print... |
package piscine
func Concat(str1 string, str2 string) string {
strConcat := str1 + str2
return strConcat
}
|
package main
import (
//"fmt"
//"os"
"net/http"
"text/template"
"math/rand"
"time"
)
type tempData struct {
GuessNo int
MaxNumber int
//UserGuess int
}
//Code adapted from: https://gobyexample.com/reading-files
func checkError(e error) {
if e != nil {
panic(e)
}
}
func templateHandler(w htt... |
package auth
import (
"errors"
)
type Adapter interface {
Get(interface{}) (string, error)
}
type KeycloakAdapter struct {
fieldName string
}
func NewKeycloakAdapter(fieldName string) *KeycloakAdapter {
return &KeycloakAdapter{fieldName: fieldName}
}
func (k KeycloakAdapter) Get(d interface{}) (result string, ... |
package ch01
import (
"sort"
)
// Given a slice with 'n' elemenents & a value 'x', find two elements in the list that sums to 'x'
// Hint:
// Approach 1: sort the list
// Approach 2: Using a hash table
func Find2Sum(in []int, x int) []int {
var res []int
cpy := make([]int, len(in))
copy(cpy, in)
sort.Slice(cpy... |
package main
import "fmt"
func Foo() (x int, y int) {
return
}
func Bar() (x, y int) {
x = 42
return
}
func Foobar() (x, y int) {
fmt.Println(x, y)
x, y = 42, 23
return
}
func main() {
fmt.Println(Foo())
fmt.Println(Bar())
fmt.Println(Foobar())
}
|
/*
* @lc app=leetcode.cn id=19 lang=golang
*
* [19] 删除链表的倒数第 N 个结点
*/
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
// @lc code=start
func removeNthFromEnd(head *ListNode, n int) *ListNode {
if head == nil {
return nil
}
var fast, slow *ListNode
fast = head
slow = head
for... |
package openstack_ssh
import (
"github.com/rackspace/gophercloud"
"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs"
)
func FindKeyPairByName(cli *gophercloud.ServiceClient, name string) (*keypairs.KeyPair, error) {
result := keypairs.Get(cli, name)
keypair, err := result.Extract()
if er... |
package TLSSign
/*
#cgo CFLAGS: -I./
#cgo LDFLAGS: -L $GOPATH/src/TLSSign -lsigcheck -ldl
#include <stdlib.h>
#include "sigcheck.h"
#include "multi_thread.h"
*/
import "C"
import (
"errors"
"unsafe"
)
// 签名设置结构体
type TLSSignConf struct {
AccType int
Identifier string
AppId3rd string
... |
package html
import (
utils "github.com/kevinbarbary/go-lms/utils"
"net/http"
"strconv"
)
const SIGNED_OUT = 1
const SIGN_OUT_FAIL = 2
const SIGNED_IN = 3
var messages = map[int]string{
1: "You are now signed-out",
2: "Sign-out failed!",
3: "You are now signed-in",
}
var kinds = map[int]string{
1: "success",... |
package main
import (
"os"
"github.com/charly3pins/eShop/domain"
"github.com/charly3pins/eShop/infrastructure/postgres"
)
func main() {
connectionOptions := postgres.ConnectionOptions{
Host: os.Getenv("POSTGRES_HOST"),
Port: os.Getenv("POSTGRES_PORT"),
User: os.Getenv("POSTGRES_USER"),
Passwo... |
/*
Create a function that filters out an array of state names into two categories based on the second parameter.
Abbreviations abb
Full names full
Examples
filterStateNames(["Arizona", "CA", "NY", "Nevada"], "abb")
➞ ["CA", "NY"]
filterStateNames(["Arizona", "CA", "NY", "Nevada"], "full")
➞ ["Arizona", "Ne... |
package main
import (
"context"
"flag"
"fmt"
"github.com/google/subcommands"
"github.com/sirupsen/logrus"
"github.com/terassyi/mycon/cmd"
"os"
)
var (
debug bool
)
func init() {
flag.BoolVar(&debug, "debug", false, "debug mode")
}
func main() {
subcommands.Register(subcommands.FlagsCommand(), "")
//subco... |
package mdb
/*
#cgo CFLAGS: -pthread -W -Wall -Wno-unused-parameter -Wbad-function-cast -O2 -g
#cgo freebsd CFLAGS: -DMDB_DSYNC=O_SYNC
#cgo openbsd CFLAGS: -DMDB_DSYNC=O_SYNC
#cgo netbsd CFLAGS: -DMDB_DSYNC=O_SYNC
#include <stdlib.h>
#include <stdio.h>
#include "lmdb.h"
#define LMDBGO_SET_VAL(val, size, data) *(val) ... |
package main
import (
"sync"
)
type MyMutex sync.Mutex
/**
* created: 2019/5/13 9:38
* By Will Fan
*/
func main() {
var mtx MyMutex
mtx.Lock()
mtx.Unlock()
}
|
// SILVER - Service Wrapper
//
// Copyright (c) 2014 PaperCut Software http://www.papercut.com/
// Use of this source code is governed by an MIT or GPL Version 2 license.
// See the project's LICENSE file for more information.
//
package run
import (
"os"
"testing"
"time"
)
func TestExecGUIProgram(t *testing.T) {
... |
package main
import (
"archive/zip"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
func main() {
workdir := "data"
fetchTECData(workdir)
}
func fetchTECData(dest string) {
zip_db := "TEC_CF_CSV.zip"
zipFile := filepath.Join(dest, zip_db)
unzipDir := filepath.Join(dest, "unzipped")
fmt.Pr... |
package appsetting
import (
md "github.com/ebikode/eLearning-core/model"
)
// ValidationFields struct to return for validation
type ValidationFields struct {
Name string `json:"name,omitempty"`
// SKey string `json:"s_key,omitempty"`
Value string `json:"value,omitempty"`
Comment string `json:"comment,omitemp... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//241. Different Ways to Add Parentheses
//Given a string of numbers and operators, return all possible results from computing all the different possib... |
package v039
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/msgservice"
)
const (
ModuleName = "metadata"
SpecModuleName = "spec"
)
... |
package tools
import "math"
// Ramp represents a exponential ramp
type Ramp struct {
min float64
dev float64
exp float64
steps int
index int
acc float64
inc float64
}
// NewRamp creates a new ramp
func NewRamp(steps int, min float64, max float64, exp float64) *Ramp {
return &Ramp{
min: min,
d... |
package apierr
import "testing"
func TestErrorsWithCreatesNewInstance(t *testing.T) {
var errs Errors
// do not assign result
errs.WithRateLimit("")
errs.WithUnauthorized("")
if len(errs) != 0 {
t.Fatalf("expected 0 errors, got %d", len(errs))
}
errs = errs.With(Error{
Type: "t1",
Code: "c1",
})
if ... |
package config
import (
"os"
"strconv"
"github.com/sirupsen/logrus"
)
const (
// LogLevelEnvVar is the name of the environment variable that controls
// the log level of the application logger
LogLevelEnvVar = "LOG_LEVEL"
// PortEnvVar is the name of the environment variable that controls the
// value of th... |
package main
import (
"fmt"
"math"
"strconv"
"strings"
"time"
util "github.com/verlandz/clustering-phone/utility"
dist "github.com/verlandz/clustering-phone/utility/distance"
evalc "github.com/verlandz/clustering-phone/utility/evaluate_cluster"
initc "github.com/verlandz/clustering-phone/utility/initial_clus... |
package tuplespace
import (
"fmt"
log "github.com/alecthomas/log4go"
"go/ast"
"go/parser"
"go/token"
"reflect"
"strconv"
)
// TODO: Add support for indexes
type TupleMatcher struct {
ast *ast.Expr
Expr string
Index []string
}
func MustMatch(expr string, args ...interface{}) *TupleMatcher {
m, err := Ma... |
package dynamic_programming
import (
"testing"
)
func Test_maxSubArray(t *testing.T) {
// nums := []int{-2,1,-3,4,-1,2,1,-5,4}
nums := []int{1, 2}
res := maxSubArray2(nums)
if res != 3 {
t.Error(res)
}
}
|
package game
import (
"github.com/Rompei/lgb/field"
"github.com/Rompei/lgb/options"
"github.com/Rompei/lgb/twitter"
"github.com/Rompei/lgb/utils"
"github.com/cheggaaa/pb"
"gopkg.in/kyokomi/emoji.v1"
"net/url"
"time"
)
// Game object
type Game struct {
stream *twitter.Stream
field *field.Field
twee... |
package websocket
import (
log "github.com/Sirupsen/logrus"
"github.com/gorilla/websocket"
"time"
)
const (
writeWait = time.Second
pongWait = 500 * time.Millisecond
pingPeriod = (pongWait * 9) / 10 // Must be < pongWait
maxMessageSize = 4096
)
func NewWebsocketConn(ws *websocket.Conn) *Websock... |
package powerdns_test
import (
"github.com/joeig/go-powerdns/v3"
)
func ExampleNewClient() {
_ = powerdns.NewClient("http://localhost:8080", "localhost", map[string]string{"X-API-Key": "apipw"}, nil)
}
|
package api
import (
"github.com/jpurdie/authapi/pkg/api/invitation"
invitationl "github.com/jpurdie/authapi/pkg/api/invitation/logging"
invitationt "github.com/jpurdie/authapi/pkg/api/invitation/transport"
"github.com/jpurdie/authapi/pkg/api/organization"
orgl "github.com/jpurdie/authapi/pkg/api/organization/log... |
package centrifuge
import (
"errors"
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/centrifugal/centrifuge-go/internal/proto"
"github.com/jpillora/backoff"
)
type disconnect struct {
Reason string
Reconnect bool
}
// Describe client connection statuses.
const (
DISCONNECTED = iota... |
package main
import (
"bufio"
"fmt"
"io"
"log"
"math"
"os"
"strconv"
)
func main() {
if len(os.Args) < 2 {
log.Fatal("missing file as input")
}
file, err := os.Open(os.Args[1])
if err != nil {
log.Fatalf("could not read file: %s", err.Error())
}
var (
fileReader = bufio.NewReader(file)
totalP... |
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
const testo = `cominciò a gridar la fiera bocca,
E ’l duca mio ver lui: «Anima sciocca,
quand’ira o altra passion ti tocca!
Raphél maì amèche zabì almi,
cui non si convenia più dolci salmi.
tienti col corno, e con quel ti disfoga?????`
//acc... |
package aboki_africa_assessment
import (
"context"
"time"
)
const bonus = 50
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt time.Time `json:"deleted_at"`
}
type... |
package priorityqueue
import (
"errors"
)
const (
capacity = 10
)
// PriorityQueue represents Priority Queue data structure that holds a heap
// and a map that holds values as key and list of indexes as values
type PriorityQueue struct {
heap []int
hashMap map[int][]int
heapSize int
heapCapaci... |
package sessions
import (
"fmt"
"time"
cache "github.com/patrickmn/go-cache"
"golang.org/x/oauth2"
)
type MemStore struct {
entries *cache.Cache
}
func NewMemStore(sessionDuration time.Duration, purgeInterval time.Duration) *MemStore {
return &MemStore{
entries: cache.New(sessionDuration, purgeInterval),
}... |
// Copyright 2013-2014 go-diameter authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package diamtype
import "fmt"
// DiameterURI Diameter Type.
type DiameterURI OctetString
func DecodeDiameterURI(b []byte) (DataType, error) {
ret... |
package theme
import (
"github.com/emicklei/go-restful"
api "github.com/emicklei/go-restful-openapi"
. "grm-service/util"
"tile-manager/dbcentral/etcd"
"tile-manager/dbcentral/pg"
)
type ThemeSvc struct {
SysDB *pg.SystemDB
DynamicDB *etcd.DynamicDB
AuthDB *pg.AuthDB
BaseDir string
}
func (s ThemeSv... |
package main
import (
"fmt"
"time"
)
func main() {
i := 10
switch i {
case 1:
fmt.Println("uno")
case 2:
fmt.Println("dos")
case 3:
fmt.Println("tres")
case 10:
fmt.Println("diez")
}
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("weekend bitch")
default:
fmt.Prin... |
package awssqs
import (
"context"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/args"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"g... |
package global
type config struct {
LogFile string `toml:"logfile" validate:"required"`
Port int `toml:"port" validate:"required"`
StaticPath string `toml:"static_path" validate:"required"`
}
|
// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT
package printer
import "unsafe"
import "syscall"
var _ unsafe.Pointer
var (
modwinspool = syscall.NewLazyDLL("winspool.drv")
procGetDefaultPrinterW = modwinspool.NewProc("GetDefaultPrinterW")
procClosePrinter = modwinspool.NewProc("ClosePrinter")
... |
package main
import (
"encoding/gob"
"fmt"
"log"
"net/http"
"os"
conf "github.com/rest_service_task/impl/config"
"github.com/rest_service_task/impl/db"
"github.com/rest_service_task/impl/handlers"
"github.com/rest_service_task/impl/sessions"
"github.com/rest_service_task/impl/structs"
)
func main() {
conf... |
package main
import (
"fmt"
"math/rand"
"time"
)
type dice struct {
petals int
face [3]string
}
func main() {
d := [6]dice{
{
0,
[3]string{
" | | ",
" | * | ",
" | | ",
},
}, {
0,
[3]string{
" | *| ",
" | | ",
" |* | ",
},
}, {
2,
[3]string{
"... |
package main
import (
"testing"
"reflect"
"fmt"
)
func TestNewAccount(t *testing.T) {
var s = types("hello world")
var s1 = types(25)
res := NewAccount(s, 12)
res1 := NewAccount(s1, 12)
stringType := reflect.TypeOf(res).Name()
numType := reflect.TypeOf(res1).Name()
if "string" != stringType {
fmt.Println(... |
package split_string
import "strings"
func Split(str, sep string)(ret []string) {
index := strings.Index(str, sep)
if index >= 0 {
ret = append(ret, str[:index])
str = str[index+1:]
index = strings.Index(str, sep)
}
ret = append(ret, str)
return
}
|
package ovsdb
import (
"errors"
"testing"
ovs "github.com/socketplane/libovsdb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestCreateLogicalSwitch(t *testing.T) {
t.Parallel()
anErr := errors.New("err")
api := new(mockTransact)
odb := Client(client{api})
selectOp := [... |
package pointerutil
func IPtr(i int) *int {
return &i
}
func I8Ptr(i int8) *int8 {
return &i
}
func I16Ptr(i int16) *int16 {
return &i
}
func I32Ptr(i int32) *int32 {
return &i
}
func I64Ptr(i int64) *int64 {
return &i
}
func UPtr(u uint) *uint {
return &u
}
func U8Ptr(u uint8) *uint8 {
return &u
}
func ... |
package storage
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
type Storage interface {
UpdateDoc(ctx context.Context, collection string, doc string, update firestore.Update) error
}
type Store struct {
Client *firestore.Client
}
func (s Store) UpdateDoc(ctx context.Context, collection string, doc... |
/*
* @lc app=leetcode.cn id=1742 lang=golang
*
* [1742] 盒子中小球的最大数量
*/
// @lc code=start
package main
func countBalls(lowLimit int, highLimit int) int {
box := make(map[int]int)
for i := lowLimit; i < highLimit+1; i++ {
j := i
sum := 0
for j > 0 {
sum += j % 10
j /= 10
}
box[sum]++
}
count := 0... |
package OSXKeyboard
/*
#cgo LDFLAGS: -framework Carbon
extern int listen();
*/
import "C"
import (
"errors"
"github.com/GianlucaGuarini/go-observable"
)
// flag variable to check whether the c code was already called
var isListening = false
var o = observable.New()
// Listen start listening the keyboard events
... |
package main
import (
"fmt"
"go/types"
"io"
"io/ioutil"
"os"
"path/filepath"
"unicode"
"unicode/utf8"
"bytes"
"os/exec"
"golang.org/x/tools/go/loader"
"golang.org/x/tools/imports"
)
//go:generate bash -c "(echo package main; echo; echo 'const ConvertStr = `'; sed 1s/runtime/main/ ../runtime/convert.go;... |
package main
import (
"context"
"log"
"github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc"
"google.golang.org/grpc"
"github.com/betterDuanjiawei/go-grpc-example/pkg/gtls"
pb "github.com/betterDuanjiawei/go-grpc-example/proto"
zipkinot "github.com/openzipkin-contrib/zipkin-go-opentracing"
"github.com/openzi... |
package types
import (
"bytes"
"fmt"
"strconv"
"time"
"github.com/irisnet/irishub/codec"
"github.com/irisnet/irishub/modules/params"
sdk "github.com/irisnet/irishub/types"
)
var _ params.ParamSet = (*Params)(nil)
const (
// Default parameter namespace
DefaultParamSpace = "stake"
// Delay, in blocks, betw... |
package uaaclient
import (
"bytes"
"fmt"
"net/http"
"strings"
)
const clientEndpoint = "/clients/"
// Clients ...
type Clients struct{ u *UaaClient }
// Clients ...
func (u *UaaClient) Clients() *Clients { return &Clients{u} }
// Create ...
func (c *Clients) Create(t *Token, client *Client) (bool, error) {
b,... |
package action
import (
"regexp"
"strconv"
"strings"
"github.com/chitoku-k/ejaculation-counter/supplier/infrastructure/client"
"github.com/chitoku-k/ejaculation-counter/supplier/service"
"github.com/pkg/errors"
)
var (
MpywRegex = regexp.MustCompile(`(?:mpyw|まっぴー|実務経験)(?:\s*(\d+)\s*連)?(?:が|ガ|ガ)[チチ][ャャ]`)
)
... |
package grouppolicy
import (
"encoding/json"
"errors"
"fmt"
"strings"
ps "github.com/ao-com/go-powershell"
"github.com/ao-com/go-powershell/backend"
)
type Client struct {
}
// IsGroupPolicyModuleInstalled
// 判断是否安装了powershell的组策略模块
func IsGroupPolicyModuleInstalled() (bool, error) {
cmd := "if (Get-Module ... |
package proxy
import (
"context"
"encoding/json"
"sync"
"github.com/google/uuid"
)
// Proxy service
type Proxy struct {
mutex sync.Mutex
request map[string]chan struct{}
sendNext func(ctx context.Context, data []byte) error
}
// Handler to requests
func (p *Proxy) Handler(ctx context.Context) (requestUUID... |
package API
import (
"Work_5/Service"
"Work_5/object"
"github.com/gin-gonic/gin"
"net/http"
)
func AnswerQuestion(ctx *gin.Context) {
//绑定user,question,article参数
var user object.User
var question object.Question
var article object.Article
ctx.ShouldBind(&user)
ctx.ShouldBind(&question)
ctx.ShouldBind(&art... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.