text stringlengths 11 4.05M |
|---|
package trie
import "testing"
func TestTrie(t *testing.T) {
trie := New()
trie.Insert("hills")
trie.Insert("hill")
trie.Insert("hello")
trie.Insert("")
t.Log(trie)
t.Log(trie.Find("hil"))
t.Log(trie.Find("hill"))
t.Log(trie.Find("hills"))
t.Log(trie.Find(""))
t.Log(trie.Completion("hi"))
t.Log(trie.Comp... |
/*
* 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... |
/*
* Copyright 2017 StreamSets 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... |
// This file was generated for SObject UserShare, API Version v43.0 at 2018-07-30 03:47:24.30264581 -0400 EDT m=+10.645651703
package sobjects
import (
"fmt"
"strings"
)
type UserShare struct {
BaseSObject
Id string `force:",omitempty"`
IsActive bool `force:",omitempty"`
LastModifiedByI... |
package todo
import (
"net/http"
"github.com/dlockamy/goRouter/config"
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
type Todo struct {
Slug string `json:"slug"`
Title string `json:"title"`
Body string `json:"body"`
}
func Routes(configuration *config.Config) *chi.Mux {
router := c... |
/* SPDX-License-Identifier: Apache-2.0
* Copyright (c) 2019 Intel Corporation
*/
package ngcnef_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
const NefTestCfgBasepath = "../../test/nef/configs/"
const NefTestJSONBasepath = "../../test/nef/nef-cli-scripts/json/"
const NefTIFApiP... |
package postgres
import (
"context"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/suite"
"github.com/vitalyisaev2/buildgraph/config"
"github.com/vitalyisaev2/buildgraph/storage"
)
var (
stubLogger = logrus.New()
)
// integration tests for PostgreSQL-backed storage
type storageSuite stru... |
package main
import (
"bufio"
"database/sql"
"fmt"
"io"
"log"
"os"
"strconv"
_ "github.com/go-sql-driver/mysql"
)
var (
db *sql.DB
err error
)
//パッケージ修飾子を_にすることでエクスポートされた名前は見えない
func init() {
fmt.Println("init()")
//sql.Openはデータベースへの接続を行わない(直観に反して)
//データストアへのコネクションは必要になった時に初めて遅延評価される
//取得したDBオブジェクトがア... |
package entity
// Entry represents entry entity.
type Entry struct {
Title string `json:"title"`
URL string `json:"url"`
}
|
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/luuphu25/data-sidecar/util"
)
func init() {
ticker = overrideTicker
}
func overrideTicker(time.Duration) <-chan time.Time {
x := make(chan time.Time, 2)
x <- time.Now()
close(x)
return x
}
func SimpleHandleFunc(w ht... |
package collectors_test
import (
"errors"
"io/ioutil"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/cloudfoundry/bosh-cli/director"
"github.com/cloudfoundry/bosh-cli/director/directorfakes"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/log"
"github... |
package subscriber
import (
"fmt"
"github.com/lfmexi/tcpgateway/events"
)
// NewKeyBasedEventSubscriberFactory creates a new event subscriber factory based on keys
func NewKeyBasedEventSubscriberFactory(eventSource events.EventSource) events.EventSubscriberFactory {
return &keyBasedEventSubscriberFactory{
event... |
package parser
import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"github.com/tomarrell/lbadd/internal/parser/ast"
"github.com/tomarrell/lbadd/internal/parser/scanner/token"
)
func TestSingleStatementParse(t *testing.T) {
inputs := []struct {
Name string
Query string
... |
package models_test
import (
"path"
"testing"
"github.com/cloudfoundry-incubator/notifications/config"
"github.com/cloudfoundry-incubator/notifications/models"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestModelsSuite(t *testing.T) {
RegisterFailHandler(Fail)
RunSp... |
/**
* Example library to provide a go implementation of the recursive ackermann function.
* This library can be loaded in PHP using PHP-FFI (https://www.php.net/manual/en/book.ffi.php).
*
* 2 variants of the function are provided:
*
* ackermann(n, m) using integers as input and output
* ackermann_json using json... |
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Copyright 2015 Andrew Stuart
// Copyright 2018 Sebastien Carlier
// Use of this source code is governed by The MIT License (MIT).
package sse
import (
"fmt"
"bufio"
"bytes"
"github.com/go-errors/errors"
"io"
"net/http"
"strconv"
"time"
... |
package main
import (
"./config"
"./driver"
"./fsm"
"./network"
"./network/localip"
"./nodeMapCompiler"
"./targetFloorAssigner"
"fmt"
"time"
"os"
"syscall"
"os/exec"
"os/signal"
)
func initializeLiftData() config.Lift {
var lift config.Lift
id, err := localip.LocalIP()
if err == nil {
lift = config.... |
package Geek
func findTheDifference(s string, t string) byte {
return byte(getSum(t) - getSum(s))
}
func getSum(s string) int {
sum := 0
for i := 0; i < len(s); i++ {
sum += int(s[i])
}
return sum
}
/*
题目链接: https://leetcode-cn.com/problems/find-the-difference/
总结:
1. 这题比较geek的就是,不使用哈希,而是记录字符和,最后相减就能得到不同的... |
package gcalbot
import (
"fmt"
"github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1"
"google.golang.org/api/calendar/v3"
)
type InviteReaction string
const (
InviteReactionYes InviteReaction = "Yes 👍"
InviteReactionNo InviteReaction = "No 👎"
InviteReactionMaybe InviteReaction = "Maybe 🤷"... |
package repositories
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/auth0.v5/management"
"github.com/ariel17/railgun/api/repositories/auth0"
)
func TestAuth0Repository_GetByID(t *testing.T) {
t.Run("ok", func(t *testing.T) {
id := "still-fake"
r := NewUsersRepositoryAuth0().(*a... |
package redirection
import (
"context"
"fmt"
"net/url"
"sort"
)
// HostWhitelist returns a host whitelist function for the given mapper. The
// whitelist function will return a non-nil error if the given host name is not
// whitelisted by the mapper.
//
// In order for a host to be whitelisted the mapper must pro... |
package segment
import (
"bufio"
"fmt"
"strings"
"testing"
"github.com/gioui/uax/internal/tracing"
)
func init() {
corpusRunes = []rune(corpus)
}
func TestWhitespace1(t *testing.T) {
tracing.SetTestingLog(t)
//
seg := NewSegmenter()
seg.Init(strings.NewReader("Hello World!"))
for seg.Next() {
p1, p2 :=... |
package postFilters
import (
"sync"
"github.com/Laisky/go-fluentd/libs"
)
type PostFilterItf interface {
SetUpstream(chan *libs.FluentMsg)
SetMsgPool(*sync.Pool)
SetCommittedChan(chan<- *libs.FluentMsg)
Filter(*libs.FluentMsg) *libs.FluentMsg
DiscardMsg(*libs.FluentMsg)
}
type BaseFilter struct {
upstreamC... |
package main
import (
"fmt"
)
type IFace interface {
SetSomeField(newValue string)
GetSomeField() string
}
type Implementation struct {
someField string
}
func (i *Implementation) GetSomeField() string {
return i.someField
}
func (i *Implementation) SetSomeField(newValue string) {
i.someField = newValue
}
f... |
package rpubsub
import (
"context"
"io/ioutil"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/sirupsen/logrus"
"github.com/batchcorp/plumber-schemas/build/go/protos/args"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber/validate"
)
var _ = Describe... |
package helper
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
const (
DefaultTimeout = 5 * time.Second
PortRange = 500
PortStartRange = 9002
MaxRetries = 5
)
var (
mu sync.Mutex
)
func Get(host, url string, time... |
package component
import "encoding/xml"
//EncMessage 微信加密消息固定格式
type EncMessage struct {
XMLName xml.Name `xml:"xml"`
ToUserName string `xml:"-"` // 开发者微信号
Encrypt string // 加密的消息报文
MsgSignature string // 报文签名
TimeStamp string // 时间戳
Nonce string // 随机数
}
type AuthNotifyResponse... |
package manager
import (
"fmt"
"io"
"os"
"time"
minio "github.com/minio/minio-go"
)
func (m *Manager) uploadJob(name string, size int64, file io.Reader) (string, error) {
jobName := fmt.Sprintf("%s-%s", name, time.Now().Format(time.RFC3339))
metadata := map[string]string{
"filename": name,
"size": fmt... |
package newrelic
import (
"context"
"github.com/b2wdigital/goignite/pkg/log"
"github.com/b2wdigital/goignite/pkg/transport/client/redis/v7"
r "github.com/go-redis/redis/v7"
"github.com/newrelic/go-agent/v3/integrations/nrredis-v7"
)
type Integrator struct {
options *Options
}
func NewIntegrator(options *Optio... |
package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"time"
"github.com/aca/go-kubectx/config"
"github.com/aca/go-kubectx/fzfutil"
"github.com/spf13/pflag"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/kubernetes"
_ "k8s... |
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"ms/sun/shared/helper"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// Group represents a row from 'sun_chat.group'.
... |
package battle
import (
"context"
"github.com/go-kit/kit/log"
"github.com/jace-ys/go-library/postgres"
pb "github.com/jace-ys/super-smash-heroes/services/battle/api/battle"
)
type Server interface {
Init(ctx context.Context, server pb.BattleServiceServer) error
Serve() error
Shutdown(ctx context.Context) err... |
package hue
import (
"encoding/json"
"errors"
"io"
)
func isError(body io.Reader) bool {
var e Error
err := json.NewDecoder(body).Decode(&e)
if err != nil || len(e) == 0 || e[0].Error.Type == 0 {
return false
}
return true
}
func getError(body io.Reader) error {
var e Error
err := json.NewDecoder(body).D... |
package view
import (
projectmenu "projja_telegram/command/current_project/menu"
"projja_telegram/command/util"
"projja_telegram/model"
)
func WorkWithProject(botUtil *util.BotUtil, project *model.Project) {
msg := projectmenu.MakeProjectMenu(botUtil.Message, project)
botUtil.Bot.Send(msg)
for update := range ... |
package main
import (
"container/heap"
// "fmt"
"math/rand"
"testing"
)
func TestCappedPriorityQueue(t *testing.T) {
pq := make(CappedPriorityQueue, 0, 5+1)
heap.Init(&pq)
for i := 0; i < 100; i++ {
randNum := rand.Intn(200) - 100
item := &Item{
value: randNum,
priority: randNum,
}
heap.Push(&... |
package main
import "fmt"
//import _ "包的路径"
//import m "github.com/Q1mi/studygo/pkg_test"
// 包变量可见性
var aa = 100 // 首字母小写,外部包不可见,只能在当前包内使用
// 首字母大写外部包可见,可在其他包中使用
const Mode = 1
type person struct { // 首字母小写,外部包不可见,只能在当前包内使用
name string
}
// 首字母大写,外部包可见,可在其他包中使用
func Add(x, y int) int {
return x + y
}
func age1... |
package utils
import (
"app-auth/db"
"app-auth/iam"
"app-auth/types"
"fmt"
"time"
uuid "github.com/satori/go.uuid"
"context"
"log"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/mongo/options"
)
type TeamUtil struct {
TeamName string `json:"team_name"`
Description stri... |
package sensu
import (
"fmt"
"github.com/bitly/go-simplejson"
"github.com/streadway/amqp"
"io"
"log"
"time"
)
type Keepalive struct {
q MessageQueuer
config *Config
close chan bool
logger *log.Logger
interval time.Duration
started bool
}
func NewKeepalive(w io.Writer) *Keepalive {
k := new(Keepa... |
package v2
import (
"github.com/tealeg/xlsx"
)
// 描述一个表单
type Sheet struct {
*xlsx.Sheet
Row int // 当前行
Column int // 当前列
file *File // 指向父级
}
// 取行列信息
func (self *Sheet) GetRC() (int, int) {
return self.Row + 1, self.Column + 1
}
// 获取单元格 cursor=行, index=列
func (self *Sheet) GetCellData(cursor, index ... |
// Package queue implements support for reading and writing to message queues.
package queue
import (
"context"
)
// Queue wraps the set of methods for reading and writing to a queue.
//
// A major limitation of this interface is that it does not provide a method of
// acknowledging received messages, so if a servic... |
package routes
import (
handleTask "github.com/AnthuanGarcia/RestApiGo/src/handlers/tasks"
"github.com/gin-gonic/gin"
)
// Routes - Generacion de Rutas
type Routes struct{}
// StartGin - Deploy Api
func (c Routes) StartGin() {
r := gin.Default()
api := r.Group("/prueba")
{
api.GET("/tasks/:id", handleTask.Ha... |
package job
import (
sj "github.com/bitly/go-simplejson"
"github.com/donnie4w/go-logger/logger"
"math/rand"
"time"
)
type TestCollector struct {
id int
}
func (p *TestCollector) Init(ctx *sj.Json, id int) error {
p.id = id
return nil
}
func (p *TestCollector) Collect(item Item) error {
logger.Debugf("collec... |
package adapter
import (
"encoding/base64"
"sort"
"github.com/giantswarm/microerror"
"github.com/giantswarm/aws-operator/service/controller/legacy/v29/key"
"github.com/giantswarm/aws-operator/service/controller/legacy/v29/templates"
)
type GuestInstanceAdapter struct {
Cluster GuestInstanceAdapterCluster
Ima... |
package favourite
import (
"context"
user "proximity/apis/grpc/generated/user"
"proximity/config"
log "proximity/pkg/utils/logger"
)
// FavouriteInterface is implemented by any value that contains the required methods
// makes Favourite mockable
type FavouriteInterface interface {
Get(GetRequest) (*GetResponse, ... |
package fsm
import (
"bytes"
"fmt"
)
const highlightingColor = "#00AA00"
// MermaidDiagramType the type of the mermaid diagram type
type MermaidDiagramType string
const (
// FlowChart the diagram type for output in flowchart style (https://mermaid-js.github.io/mermaid/#/flowchart) (including current state)
Flow... |
/*
Copyright 2019 The Kubernetes 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, ... |
// Copyright (c) 2022 Cisco and/or its affiliates.
// 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 l... |
package main
var QUAYPATH string = "quay.io/"
var QUAYIO string = "https://quay.io/api/v1/repository/"
|
// Copyright 2014 Rana Ian. All rights reserved.
// Use of this source code is governed by The MIT License
// found in the accompanying LICENSE file.
package ora_test
import (
"fmt"
"testing"
)
func TestStmt_Exe_table_create_alter_drop(t *testing.T) {
tableName := tableName()
// create table
stmt, err := testS... |
package rest
import (
"net/http"
"github.com/go-chi/render"
"github.com/go-playground/errors"
"github.com/go-playground/validator/v10"
"github.com/goware/errorx"
multierror "github.com/hashicorp/go-multierror"
"github.com/phogolabs/log"
)
func errorf(r *http.Request, err error) error {
err = errorChain(r, er... |
package factories
import (
"github.com/barrydev/api-3h-shop/src/common/connect"
"github.com/barrydev/api-3h-shop/src/connections"
"github.com/barrydev/api-3h-shop/src/model"
)
func GetOrderAndTotalItemWithSession(query *connect.QueryMySQL) (map[string]int, map[string]*model.Order, error) {
connection := connectio... |
// Package netease provides
package netease
import (
"encoding/json"
"fmt"
"ncm-dl/common"
"ncm-dl/logger"
"net/http"
"net/url"
"strings"
)
const (
WeAPI = "https://music.163.com/weapi"
SongUrlAPI = WeAPI + "/song/enhance/player/url"
SongAPI = WeAPI + "/v3/song/detail"
)
type SongUrlParams struc... |
// Copyright (c) 2020 Tailscale Inc & 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 router
import (
"log"
winipcfg "github.com/tailscale/winipcfg-go"
"github.com/tailscale/wireguard-go/device"
"github.com/tailscale/wir... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package azurestack
import (
"context"
"fmt"
"strings"
oi "github.com/Azure/azure-sdk-for-go/services/preview/operationalinsights/mgmt/2015-11-01-preview/operationalinsights"
om "github.com/Azure/azure-sdk-for-go/serv... |
// pd-reassign-all reassigns all Pagerduty incidents from one user to another, either directly or via re-escalating.
package main
import (
"errors"
"flag"
"log"
"os"
"github.com/GeoNet/pagerduty-jobs/internal/finduser"
pagerduty "github.com/PagerDuty/go-pagerduty"
)
var (
InvalidValueError = errors.New("Inval... |
package main
import "testing"
func benchmarkMendelbrot(size float64, b *testing.B) {
for n := 0; n < b.N; n++ {
createImg(size, 200)
}
}
// Basic benchmarks
func BenchmarkMendelbrot50(b *testing.B) { benchmarkMendelbrot(50, b) }
func BenchmarkMendelbrot200(b *testing.B) { benchmarkMendelbrot(200, b) }
func Benc... |
package movie
type Movies interface {
GetCharge() float64
GetPoit() int
}
const (
REGULAR = 0 //0
NEW_RELEASE =1 //1
CHILDRES =2 // 2
)
type Movie struct {
Title string //片名
PriceCode int //价格代号
}
//func (m Movie) GetTitle() string {
// return m.Title
//}
//
//func (m Movie) Ge... |
package main
/*
@Time : 2020-03-25 16:52
@Author : audiRStony
@File : 10_carInterface.go
@Software: GoLand
*/
import (
"fmt"
)
/*定义具有价值的不同事物的"合同" */
type Valuable interface {
GetValue() float32
}
type StockPosition struct {
ticker string
sharePrice float32
count float32
}
// 获取stock的值(价格)
func (s Stock... |
package api
import (
"net/http"
"github.com/gin-gonic/gin"
)
//A user of the system
type Usuario struct {
ID uint `json:"id" gorm:"primary_key"`
Email string `json:"email"`
Login string `json:"Login"`
Password string `json:"Password"`
}
func GetUsuario(c *gin.Context) {
c.JSON(http.StatusOK, gi... |
package wemvc
import "testing"
func Test_genFriendlyActionName(t *testing.T) {
if genFriendlyActionName("GetIndex") != "get-index" {
t.Fatal("Failed")
}
if genFriendlyActionName("GET_Index") != "get-index" {
t.Fatal("Failed")
}
if genFriendlyActionName("GetUser___Info_") != "get-user-info" {
t.Fatal("fail... |
package main;
import (
"time"
"fmt"
"net"
"strings"
// "log"
"os"
// "sync"
)
func IsPortOpen(host string,port int, timeout time.Duration, retry bool)(ok bool,err error){
addr := fmt.Sprintf("%s:%d",host,port);
_, err = net.DialTimeout("tcp",addr,timeout)
// defer conn.Close();
if err != nil{
if strings.... |
// Copyright 2020 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("list: os.FileMode")
showMode := func(msg string, mode os.FileMode) {
fmt.Println(mode, msg)
}
mods := map[string]os.FileMode{
"ModeAppend": os.ModeAppend,
"ModeCharDevice": os.ModeCharDevice,
"ModeDevice": os.ModeDevice,
"ModeDir": ... |
package core
// Generator generates random string
// This string later will be used as a row ID in database
type Generator interface {
GenerateID() string
}
|
package order
import (
"createorder/datarepository/mysql/order_db"
"createorder/utils/errors"
"github.com/jinzhu/gorm"
)
func (orderReq *CreateOrderReq) OrderSave() (*Order, *errors.RestErr) {
db := order_db.GetSqlConn()
createOrder := Order{}
createOrder.UserId = orderReq.UserId
createOrder.ProductId = orderR... |
package local
import (
"reflect"
"testing"
)
func TestParseLabels(t *testing.T) {
set, unSet := ParseLabels("foo,!bar,baz")
expectedSet := map[string]bool{"foo": true, "baz": true}
expectedUnSet := map[string]bool{"bar": true}
if !reflect.DeepEqual(expectedSet, set) {
t.Fatalf("\nExpected %+v\nGot: %+v\n", ... |
package main
import (
_ "github.com/terraform-providers/terraform-provider-azurestack"
)
|
package index
import (
"math"
"sort"
"strings"
"fmt"
)
// Index is an inverted index.
type Index struct {
dictionary map[string]PostingsList
docCount int
}
func (idx Index) String() string {
keys := make([]string, 0, len(idx.dictionary))
for k := range idx.dictionary {
keys = append(keys, k)
}
sort.... |
package manifests
import (
"bytes"
"context"
"fmt"
"io"
"net"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/apimachinery/pkg/util/yaml"
k8syaml "sigs.k8s.io/yaml"
aiv1beta1 ... |
package main
type policyList struct {
Policy []struct {
Name string `json:"name"`
URL string `json:"url"`
} `json:"policy"`
}
type contentPolicy struct {
RemotePath string `json:"remotePath"`
ListenerPolicy string `json:"listenerPolicy"`
Name string `json:"name"`
VirtualPath string `json:"virtualP... |
package datasource
import (
"github.com/bbcloudGroup/gothic/database"
"github.com/jinzhu/gorm"
)
type Admin struct {
*gorm.DB
}
func NewAdmin() Admin {
return Admin{database.G()}
}
type User struct {
gorm.Model
Username string `gorm:"size:100;unique_index;not null;"`
Password string `gorm:"size:100;not null... |
/*
* Copyright 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://www.apache.org/licenses/LICENSE-2.0
*
* or in the "... |
package generator
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/pkg/errors"
"io/ioutil"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
func generateManagedPolicies(ctx context.Context) ([]*policyF... |
package transform
func (r *AST) writeFilters() []Filter {
var filters []Filter
for _, scalar := range r.Scalars {
p := r.pick(
scalar+"FieldUpdateOperationsInput",
"Nullable"+scalar+"FieldUpdateOperationsInput",
)
if p == nil {
continue
}
var fields []Method
for _, field := range p.Fields {
/... |
package user
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"golang.org/x/crypto/bcrypt"
"github.com/gin-gonic/gin"
"github.com/javiercbk/jayoak/http/response"
"github.com/javiercbk/jayoak/http/session"
"github.com/javiercbk/jayoak/models"
"github.com/volatiletech... |
package collector
import (
"bytes"
"io/ioutil"
"encoding/xml"
"github.com/prometheus/common/log"
"github.com/prometheus/client_golang/prometheus"
)
const (
// Subsystem(s).
profile = "profile"
)
var (
brickDuration = prometheus.NewDesc(
prometheus.BuildFQName(namespace, profile, "brick_duration"),
"Time... |
package aws
import (
"time"
)
type Face struct {
Device int64
MaxAge int64
MinAge int64
Gender string
GenderConf float64
Smile bool
SmileConf float64
Emotions []string
Created time.Time
}
|
/*
GoLang code created by Jirawat Harnsiriwatanakit https://github.com/kazekim
*/
package kbank
import (
"github.com/mitchellh/mapstructure"
)
func (c *defaultClient) TestSSL() (*TestSSLResponse, error) {
if c.kBankSvc == nil {
return nil, ErrKBankConfigNotDefined
}
req, err := c.kBankSvc.NewTestSSLRequest... |
package template
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
// Store is a directory that contains multiple templates.
type Store struct {
dir string
}
// OpenStore returns a new Store for the passed dir. It will also create the
// dir if it doesn't exist.
func OpenStore(dir string) (Store, error) {... |
/*
*
* @brief XCoin API-call sample script (for Go)
*
* @author btckorea
* @date 2017-04-14
*
* @note
* Make sure current system time is correct.
* If current system time is not correct, API request will not be processed normally.
*
* rdate -s time.nist.gov (if necessary)
*
*/
package main
import (
"os"... |
// +build windows
package gmx
import (
"fmt"
"net"
)
// on windows we can't use a unix socket. so we use TCP sockets and let the user keep track of what port number is being used by which process
func localSocket() (net.Listener, error) {
listener, err := net.ListenTCP("tcp", localSocketAddr())
if err == nil {
... |
package main
import "fmt"
func main() {
var l [4]int
updateArray(&l)
fmt.Println(l)
}
func updateArray(list *[4]int) {
index := 0
for i := 10; index < len(list); i += 2 {
list[index] = i
index++
}
}
|
// generated by stringer -type=ZookeeperEvent; DO NOT EDIT
package gozoo
import "fmt"
const _ZookeeperEvent_name = "ZooCreatedEventZooDeletedEventZooChangedEventZooChildEventZooSessionEventZooNotWatchingEventZooUnknownEvent"
var _ZookeeperEvent_index = [...]uint8{0, 15, 30, 45, 58, 73, 92, 107}
func (i ZookeeperEv... |
package udig
import (
"fmt"
"github.com/miekg/dns"
"net"
"regexp"
"strconv"
)
var (
// For parsing ASN records, eg. "13335 | 104.28.16.0/20 | US | arin | 2014-03-28"
asnRecordPattern = regexp.MustCompile(`([0-9]+) \| (.+) \| ([A-Z]+) \| (.+) \| (.+)`)
// For parsing AS records e.g. "13335 | US | arin | 2010-0... |
package manageIPTables
import (
"fmt"
"net/http"
"network"
"os/exec"
"proxy/proxy"
)
func UpdateIPTables(request *http.Request) {
IPAddressToAdd := request.PostFormValue("IPAddressToAdd")
IPAddressToDelete := request.PostFormValue("IPAddressToDelete")
if IPAddressToAdd != "" {
addNewSlaveToIPTables(IPAddres... |
package spa
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
)
func Test_pathPrefix(t *testing.T) {
assert := require.New(t)
type args struct {
domainName string
host string
}
tests := []struct {
name string
args args
wan... |
package main
import (
"fmt"
"io/ioutil"
"sort"
"strings"
)
var testLines = strings.Split(
`/->-\
| | /----\
| /-+--+-\ |
| | | | v |
\-+-/ \-+--/
\------/ `, "\n")
var fun = strings.Split(
`/->-\
| /-+-\
| | | |
\-+-/ |
\---/`, "\n",
)
const (
up = "^"
down = "v"
left = "<"
right... |
package main
import (
"os"
"github.com/joho/godotenv"
"context"
"log"
pb "github.com/angelospillos/coinsorchestrator/proto"
"google.golang.org/grpc"
)
func main() {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
coinsOrchestratorHost := getEnv("COINS_ORCHESTRATOR... |
package util
import (
"bytes"
"fmt"
)
// TableToCsv ...
func TableToCsv(num int, table map[string][]string) ([]byte, error) {
if table == nil {
return nil, fmt.Errorf("Table is nil")
}
return listToCsv(tableToList(num, table)), nil
}
func tableToList(num int, table map[string][]string) [][]stri... |
package common_enum
const (
REDIS_KEY_API_PROXY_CACHE = "proxy_api_" //api接口缓存前缀
REDIS_KEY_API_PROXY_AUTH_CHECK = "proxy_auth_check_" //默认的授权插件对应的缓存token key
REDIS_KEY_API_PROXY_LIMITING = "proxy_api_limiting_" //某个应用接口的限流
)
|
package file
import (
"encoding/json"
log "github.com/golang/glog"
"go-restapi/helper"
"go-restapi/models"
"io/ioutil"
"os"
)
type FileSource struct {
usersList []models.User
}
type jsonContent struct {
/* note Unmarshal accept exportable properties */
Users []models.User `json:"users"`
}
func (src *FileSo... |
package main
import (
"fmt"
"reflect"
"regexp"
"strings"
)
func p(a ...interface{}) {
fmt.Println(a...)
}
func main() {
type StoMTest struct {
Name string
Age *int
}
i := 2
p := &i
a := StoMTest{
"NoPointer",
p,
}
b := structToMap(a)
fmt.Println(b)
}
func structToMap(v interface{}) map[stri... |
package day6
func SplitIntoEvenAndOdd(input string) (even, odd string) {
for i, char := range input {
if i%2 == 0 {
even += string(char)
} else {
odd += string(char)
}
}
return
}
|
package main
import "github.com/forestgiant/eff"
var Invader1 = [][]eff.Point{
{
eff.Point{X: 0, Y: 6},
eff.Point{X: 0, Y: 5},
eff.Point{X: 0, Y: 4},
eff.Point{X: 10, Y: 6},
eff.Point{X: 10, Y: 5},
eff.Point{X: 10, Y: 4},
eff.Point{X: 1, Y: 3},
eff.Point{X: 2, Y: 2},
eff.Point{X: 9, Y: 3},
eff.Po... |
/*
A package contains multiple files and multiple diectories
*/
package apackage
import "fmt"
func A() {
fmt.Println("Hello Calling from A function of apackage")
}
func B() {
fmt.Println("Hello Calling from B function of apackage")
}
|
package server
import (
"fmt"
"github.com/siddontang/ledisdb/client/go/ledis"
"testing"
"time"
)
func now() int64 {
return time.Now().Unix()
}
func TestExpire(t *testing.T) {
// test for kv, list, hash, set, zset, bitmap in all
ttlType := []string{"k", "l", "h", "s", "z", "b"}
var (
expire string
expi... |
package mocks
import (
"net/url"
model "github.com/geeksheik9/sheet-CRUD/models"
"go.mongodb.org/mongo-driver/bson/primitive"
)
//MockCharacterDB is the mock struct for testing
type MockCharacterDB struct {
SheetsToReturn []model.ForceCharacterSheet
SheetToReturn *model.ForceCharacterSheet
ErrorToReturn erro... |
package main
import (
"context"
"fmt"
"os"
"time"
"flag"
"github.com/jackc/pgx"
)
func main() {
domain := flag.String("d", "", "Domain name")
flag.Parse()
if *domain == "" {
fmt.Fprintf(os.Stderr, "Domain flag is not defined\n")
flag.PrintDefaults()
os.Exit(1)
}
conn, err := pgx.Connect(context.Back... |
package sys
import (
"errors"
"testing"
"github.com/cilium/ebpf/internal/unix"
qt "github.com/frankban/quicktest"
)
func TestObjName(t *testing.T) {
name := NewObjName("more_than_16_characters_long")
if name[len(name)-1] != 0 {
t.Error("NewBPFObjName doesn't null terminate")
}
if len(name) != unix.BPF_OBJ... |
// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Sample objects creates, list, deletes objects and runs
// other similar operations on them by using the Google Storage API.
// More documentation is available... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.