text stringlengths 11 4.05M |
|---|
package gofizzbuzz
import (
"fmt"
"math"
)
// GoFizzBuzz returns a string
// based on a set of simple rules
func GoFizzBuzz(i int) (w string) {
f := float64(i)
switch {
case math.Mod(f, 15) == 0:
return "fizzbuzz"
case math.Mod(f, 5) == 0:
return "buzz"
case math.Mod(f, 3) == 0:
return "fizz"
}
return ... |
package piscine
func BasicAtoi2(s string) int {
var afterZero, count int
for _, i := range s {
if i < '0' || i > '9' {
return 0
}
for j := '0'; j < i; j++ {
count++
}
afterZero = afterZero*10 + count
count = 0
}
return afterZero
}
|
//go:build !adalnk && windows
// +build !adalnk,windows
/*
* 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.
* ... |
package core
import (
"fmt"
"os"
)
const (
defaultDbName = "data.db"
)
var (
snippetStore *SnippetDatabase
)
func init() {
defaultDataDir, err := defaultAppDataDir()
if err != nil {
panic(fmt.Errorf("Failed to initialize database: %s", err))
}
if _, err := os.Stat(defaultDataDir); os.IsNotExist(err) {
e... |
package state
import (
"fmt"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/s-matyukevich/capture-criminal-tg-bot/src/common"
dbpkg "github.com/s-matyukevich/capture-criminal-tg-bot/src/db"
)
type Show struct {
bot *tgbotapi.BotAPI
db *dbpkg.DB
}
func (s *Show) Process(update... |
package main
import (
"database/sql"
"log"
"github.com/nvm-academy/go-102-packages/repository"
"github.com/nvm-academy/go-102-packages/server"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// open a connection pool to the database and bum out
// if an error is encountered
db, err := sql.Open("mysql", "... |
package util
import (
"reflect"
"testing"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
pvcToPodsCache = NewPVCToPodsCache()
pod1 = &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Namespace: "test",
Name: "pod1",
},
Spec: v1.PodSpec{
Volumes: []v1.Volume{
... |
package main
func goNorth(square int, value int) int {
return (square + value) % GRID_SIZE
}
func goEast(square int, value int) int {
dest := square
for i := 0; i < value; i++ {
if square < GRID_WIDTH*GRID_EDGE {
dest = square + GRID_WIDTH
} else {
dest = square + 1 - (GRID_WIDTH * GRID_EDGE)
}
}
ret... |
package main
import (
"io/ioutil"
"os"
"testing"
"github.com/boltdb/bolt"
)
func TestCreateDirs(t *testing.T) {
pwd, err := os.Getwd()
if err != nil {
t.Errorf("Unable to get current working directory: %s", err)
}
config := conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cat... |
package golist
import "fmt"
type node struct {
data int
next *node
}
type list struct {
head *node
tail *node
}
func NewList() list {
return list{head: nil, tail: nil}
}
func (l *list) AppendToTail(d int) {
tmp := &node{data: d, next: nil}
if l.head == nil {
l.head = tmp
l.tail = tmp
} else {
l.tail.... |
package handler
import (
"context"
"github.com/valyala/fasthttp"
elastic "gopkg.in/olivere/elastic.v5"
)
type GeoQueryHandler struct {
ElasticClient *elastic.Client
Context context.Context
}
// request handler in net/http style, i.e. method bound to MyCustomHandler struct.
func (h *GeoQueryHandler) Handl... |
package main
import (
"ewallet/database"
"ewallet/routes"
"fmt"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/spf13/viper"
"log"
"net/http"
)
func GetEnvironmentVariable(key string) string {
viper.SetConfigFile(".env")
err := viper.ReadInConfig()
if err != nil {
log.Fatalf("Error while reading c... |
package controllers
import (
"github.com/astaxie/beego/httplib"
"time"
)
type MainController struct {
BaseController
}
func (c *MainController) Get() {
headers := []string{"x-request-id",
"x-b3-traceid",
"x-b3-spanid",
"x-b3-parentspanid",
"x-b3-sampled",
"x-b3-flags",
"x-ot-span-context"}
req := h... |
package group
import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/proto/group"
"context"
)
func (s *groupServer) GroupApplicationResponse(_ context.Context, pb *group.GroupApplicationResponseReq) (*group.GroupApplicationResponseResp, error) {
... |
package conf
import (
"krpc/codec"
"time"
)
const MagicNumber = 0x3bef5b
// Option Client tell Server, what kind of CodeType to use, then use this type to decode/encode.
type Option struct {
MagicNumber int // marks this is a krpc request
CodeType codec.CodeType // client may choose dif... |
package monitors
import (
"github.com/lixiangzhong/dnsutil"
)
func dnsMonitor(address string, expectation string) bool {
var dig dnsutil.Dig
dig.SetDNS(address)
a, err := dig.A(expectation)
if err != nil {
return false
}
if len(a) <= 0 {
return false
}
return true
}
|
package credentials
import (
"testing"
"github.com/Mindslave/skade/backend/pkg/generate"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
)
func TestPassword(t* testing.T) {
password := generate.RandomString(8)
wrongPassword := generate.RandomString(8)
hash, err := CreateHash(password)
req... |
package isocket
/*
封包数据和拆包数据
直接面向TCP连接中的数据流,为传输数据添加头部信息,用于处理TCP粘包问题。
*/
type IDataPack interface {
GetHeadLen() uint32 //获取包头长度方法
Pack(data []byte) ([]byte, error) //封包方法
Unpack(binaryData []byte) (IMessage, error) //拆包方法
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"syscall"
)
//Awstoken struct to hold content of system generated json file in ~/.aws/cli/cashe/<filename.json>
type Awstoken struct {
AssumedRoleUser AssumedRoleUser
Credentials Credentials
ResponseMetadata Respo... |
package dao
import (
"github.com/therudite/api/models/feedback"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Feedback struct {
Mongo *mgo.Database
}
func (this *Feedback) InsertFeedback(feedback *models.Feedback) (bool, error) {
err := this.Mongo.C("feedback").Insert(feedback)
if err != nil {
return fals... |
package http_handlers
import (
"github.com/go-martini/martini"
"net/http"
)
func Routes() func(
martini.Context,
martini.Params,
http.ResponseWriter,
*http.Request,
) {
return HttpHandler(
[]string{},
func(h *Http) {
routes := make([]map[string]interface{}, 0)
for _, route := range Router.All() {
... |
package v3
import (
envoy_cluster "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
envoy_endpoint "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
envoy_listener "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
envoy_route "github.com/envoyproxy/go-control-plane/en... |
package cri
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"github.com/caos/orbos/internal/operator/nodeagent/dep"
)
func (c *criDep) ensureCentOS(runtime string, version string) error {
errBuf := new(bytes.Buffer)
defer errBuf.Reset()
cmd := exec.Command("yum", "--assumeyes", "remove", "docker",
"docker... |
package controllers
import "github.com/robfig/revel"
type Application struct {
*rev.Controller
}
func (c Application) Index() rev.Result {
greeting := "Hello World!"
return c.Render(greeting)
}
func (c Application) Hello(myName string) rev.Result {
return c.Render(myName)
}
|
package main
// Package strings adalah package yang berisikan function function untuk memanipulasi tipe data string
import (
"fmt"
"strings"
)
func main() {
// mengecek apakah string di params1 mengandung string yg di params2
fmt.Println(strings.Contains("Muhammad Zhuhry", "Zhuhry"))
fmt.Println(strings.Contain... |
package models
import (
"encoding/json"
"html/template"
"io/ioutil"
"log"
"time"
)
const FILENAME = "blog.csv"
type Blog struct {
ID int64 `json:"id"`
Title string `json:"title,omitempty"`
Details string `json:"details,omitempty"`
Comment int `json:"comment"`
View int `json:"view"`
... |
package test_helpers
import (
"fmt"
. "github.com/onsi/gomega"
"net/http"
)
func RegisterCache(
session_key string,
headers http.Header,
) (
cache_map map[string]interface{},
request *Request,
) {
header_cloned := CloneHeaders(headers)
header_cloned.Set(
"Authorization",
fmt.Sprintf(
"SessionKey %s", ... |
// Package xmlsec is a wrapper around the xmlsec1 command
// https://www.aleksey.com/xmlsec/index.html
package xmlsec
import (
"bufio"
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
)
const (
attrNameResponse = `urn:oasis:names:tc:SAML:2.0:protocol:Response`
attrNameAssertion = `ur... |
package textbox
import (
"sync"
)
type Dependencies struct {
sync.RWMutex
m map[*Box]map[*Box]struct{}
}
func NewDependencies() *Dependencies {
return &Dependencies{
m: make(map[*Box]map[*Box]struct{}),
}
}
func (d *Dependencies) Add(box, depend *Box) {
d.Lock()
defer d.Unlock()
m, ok := d.m[depend]
if !... |
/*
Intro
A friend posed this question today in a slightly different way - "Can a single [Python] command determine the largest of some integers AND that they aren't equal?".
While we didn't find a way to do this within reasonable definitions of "a single command", I thought it might be a fun problem to golf.
Challe... |
package main
import (
"github.com/azer/logger"
"errors"
"time"
)
var log = logger.New("e-mail")
func main() {
log.Info("Sending an e-mail", logger.Attrs{
"from": "foo@bar.com",
"to": "qux@corge.com",
})
err := errors.New("Too busy")
log.Error("Failed to send e-mail. Error: %s", err, logger.Attrs{
"fro... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"github.com/TheAndruu/git-leaderboard/models"
)
func main() {
repoStats := getRepoOriginsFromGit()
repoStats.Commits = getRepoCommits()
submitRepoStats(&repoStats)
// TODO: Show URL... |
package main
import (
"container/list"
)
//拓扑排序判断是否有环,重点是建立图的邻接表,里面保存每个节点的入度
//首先将所有入度为0的节点放入队列,然后对该节点的邻接节点减1,如果减到0
//也放入队列,循环至队列为空,若所有节点都进入队列,则说明无环返回true
//否则即说明有些节点因为有环而无法放进队列,此时numCourses就不为0
func canFinish(numCourses int, prerequisites [][]int) bool {
type GraphNode struct {
val int //node的值
count ... |
package common
import (
"net"
)
var (
SendAmount = "SEND AMOUNT"
GetBalance = "BALANCE"
SendMessage = "SEND MESSAGE"
// Transaction status
TxnIncorrect = "INCORRECT"
TxnSuccess = "SUCCESS"
)
var ClientPortMap = map[int]int{
1: 8000,
2: 8001,
3: 8002,
}
type Block struct {
EventSourceId int ... |
package states
import (
"context"
b64 "encoding/base64"
"encoding/json"
"errors"
"fmt"
derrors "github.com/direktiv/direktiv/pkg/flow/errors"
"github.com/direktiv/direktiv/pkg/model"
"github.com/direktiv/direktiv/pkg/util"
)
func init() {
RegisterState(model.StateTypeSetter, Setter)
}
type setterLogic stru... |
package shared
import "math/big"
type DoormanUpdater struct {
Id string `json:"id"`
Timestamp int64 `json:"timestamp"`
Probabilities []*big.Rat `json:"probabilities"`
}
type UpdateHandlerFunc func(m *DoormanUpdater) error
|
// Copyright 2020. Akamai Technologies, Inc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed t... |
package cfg
// RemoteVPS contains parameters for the VPS
type RemoteVPS struct {
Name string `toml:"name"`
IP string `toml:"IP"`
User string `toml:"user"`
PEM string `toml:"pemfile"`
Branch string `toml:"branch"`
SSHPort string `toml:"ssh_port"`
Daemon ... |
package types
import "strings"
// SurveyAnswer holds survey answer.
type SurveyAnswer struct {
Device string `survey:"mfa-device"`
Code string `survey:"mfa-code"`
}
// CleanAnswers cleans answers.
func (s *SurveyAnswer) CleanAnswers() {
if strings.Contains(s.Device, ": ") {
s.Device = strings.Split(s.Device, ... |
package service
import (
"context"
"os/exec"
"path"
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/epyphite/html2pdf/pkg/models"
)
//HTML2PDF Main service structure
type HTML2PDF struct {
Config models.Config
}
//Setup Will setup basic directories
func (H2 *HTM... |
package gsettings_test
import (
"testing"
gsettings "github.com/9glt/go-gsettings"
)
func TestExternal(t *testing.T) {
gsettings.Reset()
value, err := gsettings.Get("key")
if err == nil {
t.Fatal()
}
if value != "" {
t.Fatal()
}
gsettings.Set("key", "value")
value, err = gsettings.Get("key")
if err !=... |
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/ONSdigital/florence/config"
"github.com/ONSdigital/florence/service"
"github.com/ONSdigital/log.go/log"
"github.com/pkg/errors"
)
const serviceName = "florence"
var (
// BuildTime represents the time in which the service was built
Buil... |
package gosdk
import (
"github.com/dgrijalva/jwt-go"
"net/http"
)
type server struct {
token *jwt.Token
tokenExist bool
}
var serverInstance = &server{tokenExist: false}
var tokenData map[string]interface{}
func GetServerInstance(header http.Header) *server {
token1 := GetBearerToken(header)
if token1 !... |
package common
const (
letterA = 65
letterZ = 90
lettera = 97
letterz = 122
)
// Cleaner is an interface to clean objects
type Cleaner interface {
Clean(a string) string
}
// NewWordCleaner returns new WordCleaner instance
func NewWordCleaner() *WordCleaner {
return &WordCleaner{}
}
// WordCleaner implements ... |
package devices
import (
"fmt"
"os"
"sort"
"strconv"
"strings"
"github.com/cheynewallace/tabby"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/foundriesio/fioctl/client"
"github.com/foundriesio/fioctl/subcommands"
)
var (
deviceNoShared bool
deviceByTag ... |
package object
import (
"strconv"
"testing"
)
func TestStringMapKey(t *testing.T) {
testCases := []struct {
val1 Mappable
val2 Mappable
diff1 Mappable
diff2 Mappable
}{
{
val1: &String{Value: "Hello World"},
val2: &String{Value: "Hello World"},
diff1: &String{Value: "My name is johnny"},
... |
package main
import (
"fmt"
"math"
)
// https://leetcode-cn.com/problems/string-to-integer-atoi/
func myAtoi(s string) int {
N, i := len(s), 0
if N == 0 {
return 0
}
for ; i < N && s[i] == ' '; i++ {
}
if i >= N || s[i] != '-' && s[i] != '+' && (s[i] < '0' || s[i] > '9') {
return 0
}
res, sign := int64... |
package config
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMetricsManager(t *testing.T) {
ctx := context.Background()
src := NewStaticSource(&Config{
Options: &Options{
Metrics... |
package main
import (
"time"
)
func init() {}
type Configuration struct {
Database struct {
Server string `json:"server"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
Database string `json:"database"`
} `json:"database"`
Port int `json:"port"`
Log ... |
package main
import (
"reflect"
"testing"
)
var die = Die{0}
func TestRollDie(t *testing.T) {
die.rollDie()
firstRoll := die.getValue()
die.rollDie()
secondRoll := die.getValue()
if firstRoll == secondRoll {
t.Error("roll die function should not give you the same values ")
}
}
func TestDisplay(t *testing.... |
package main
import "fmt"
func main() {
foo()
defer foo1()
foo2()
}
func foo() {
fmt.Println("Hello1")
}
func foo1() {
fmt.Println("Hello2")
}
func foo2() {
fmt.Println("Hello3")
} |
package main
import (
"net"
"bufio"
"fmt"
"strconv"
)
//Constants
const PORT = 8080
// define new structure corresponding to each session
type session struct {
// Registered connections.
connections [] net.Conn
// Corresponding names of registered connections
names [] string
}
// define ne... |
package testutils
import (
"context"
"testing"
"github.com/multiformats/go-multiaddr"
)
func Test_NewPrivateKey(t *testing.T) {
if pk := NewPrivateKey(t); pk == nil {
t.Fatal("should not be nil")
}
}
func Test_NewSecret(t *testing.T) {
if secret := NewSecret(t); secret == nil {
t.Fatal("should not be nil"... |
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package dochandler performs document operation processing and document resolution.
//
// During operation processing it will use configured validator to validate document operation and then it will call
// batch wr... |
package validate
import "reflect"
// FilterRule definition
type FilterRule struct {
// fields to filter
fields []string
// filter name list
filters []string
// filter args. { index: "args" }
filterArgs map[int]string
}
type funcMeta struct {
fv reflect.Value
name string
// readonly cache
numIn int
nu... |
package main
import (
"log"
"net"
"tag-service/server"
"google.golang.org/grpc/reflection"
pb "tag-service/proto"
grpc "google.golang.org/grpc"
)
func main() {
port := "8888"
s := grpc.NewServer()
pb.RegisterTagServiceServer(s, server.NewTagServer())
reflection.Register(s)
lis, err := net.Listen("tcp",... |
package shortener
import (
"bytes"
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"github.com/stretchr/testify/assert"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
func TestGetURL(t *testing.T) {
db, path := setupDatabase(t)
shortServer := ShortServer{DB: db, URL: "easy.xyz... |
package main
import "fmt"
type Stack struct {
top *Element
size int
}
type Element struct {
value interface{}
next *Element
}
// стекийн урт
func (s *Stack) Len() int {
return s.size
}
// стекийн оройд элемент нэмэх
func (s *Stack) Push(value interface{}) {
s.top = &Element{value, s.top... |
package login
//cv propiedades tipo clave: valor
type cv map[string]string
var usuarios = make(map[string]map[string]string)
func init() {
usuarios = map[string]map[string]string{
"juan": cv{"pwd": "123", "nvl": "1"},
"maria": cv{"pwd": "123", "nvl": "1"},
"luis": cv{"pwd": "123", "nvl": "2"},
}
}
//me ... |
/*
Copyright 2017 The Kubernetes Authors.
SPDX-License-Identifier: Apache-2.0
*/
package oimcsidriver
import (
"context"
"fmt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/container-storage-interface/spec/lib/go/csi"
)
func (od *oimDriver) CreateVolume(ctx context.Context, req *... |
package testrail
import (
"fmt"
"net/url"
)
// Run represents a Run
type Run struct {
AssignedToID int `json:"assignedto_id"`
BlockedCount int `json:"blocked_count"`
CompletedOn int `json:"completed_on"`
Config string `json:"config"`
ConfigIDs []int `json:"config_ids"`
CreatedBy i... |
package main
//region Usings
import "github.com/ravendb/ravendb-go-client"
//endregion
var globalDocumentStore *ravendb.DocumentStore
func main() {
createDocumentStore()
createDatabase()
enableRevisions("collection1","collection2")
globalDocumentStore.Close()
}
func createDocumentStore() (*ravendb.D... |
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gluang/GenBook/docs"
)
var (
version string
commit string
date string
)
func main() {
args := os.Args
if len(args) == 2 && (args[1] == "--version" || args[1] == "-v") {
fmt.Printf("Release version : %s\n",... |
package main
import "fmt"
func main() {
// x := 8
// fmt.Println("My first variable, well not really but whatever", x)
// var (
// x = 10
// y = 12
// z = 15
// )
fmt.Println("Let me multiply convert C => F for you")
var celciusInput float64
fmt.Scanf("%f", &celciusInput)
output := (celciusInput * (9.0... |
package inmemory
import (
"github.com/Tanibox/tania-core/src/assets/query"
"github.com/Tanibox/tania-core/src/assets/storage"
"github.com/gofrs/uuid"
)
type ReservoirReadQueryInMemory struct {
Storage *storage.ReservoirReadStorage
}
func NewReservoirReadQueryInMemory(s *storage.ReservoirReadStorage) query.Reserv... |
// Copyright (C) 2019 Cisco Systems Inc.
// Copyright (C) 2016-2017 Nippon Telegraph and Telephone Corporation.
//
// 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.... |
/*
Copyright 2021 The KubeVela 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 main
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"fmt"
"io"
)
func main() {
h256 := sha256.New()
io.WriteString(h256, "anziguoer")
fmt.Printf("anziguoer => sha256: %x \n", h256.Sum(nil))
h1 := sha1.New()
io.WriteString(h1, "anziguoer")
fmt.Printf("anziguoer => sha1: %x \n", h1.Sum(nil))
... |
package gameencoder
// crc表
var crcTable = [...]uint32{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d... |
// Declarando variavel com package scope.
// Toda variavel
package main
import "fmt"
var nome string
var idade int
var peso float64
var solteiro bool
func main() {
fmt.Printf("%v, %T\n", nome, nome)
fmt.Printf("%v, %T\n", idade, idade)
fmt.Printf("%v, %T\n", peso, peso)
fmt.Printf("%v, %T\n", solteiro,... |
package integration_test
import (
"fmt"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"time"
"github.com/blang/semver"
"github.com/cloudfoundry/libbuildpack/cutlass"
"github.com/cloudfoundry/libbuildpack/packager"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("deploy a staticfil... |
package entity
type Herd struct {
LabYaks []LabYak `xml:"labyak"`
}
type HerdPayload struct {
Herd []LabYakPayload `json:"herd"`
}
|
package frida_go
type ScriptOptions struct {
Name string
Runtime FridaScriptRuntime
} |
/*
以 Unix 风格给出一个文件的绝对路径,你需要简化它。或者换句话说,将其转换为规范路径。
在 Unix 风格的文件系统中,一个点(.)表示当前目录本身;此外,两个点 (..) 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。更多信息请参阅:Linux / Unix中的绝对路径 vs 相对路径
请注意,返回的规范路径必须始终以斜杠 / 开头,并且两个目录名之间必须只有一个斜杠 /。最后一个目录名(如果存在)不能以 / 结尾。此外,规范路径必须是表示绝对路径的最短字符串。
示例 1:
输入:"/home/"
输出:"/home"
解释:注意,最后一个目录名后面没有斜杠。
示例 2:
输入... |
// Using already Existing Slice
/*
For creating a slice from the given slice first you need to
specify the lower and upper bound, which means slice can take
elements from the given slice starting from the lower bound to
the upper bound. It does not include the elements above from the upper bound.
*/
package ma... |
package models
type User struct {
Model
Firstname string `json:"firstname`
Lastname string `json: "lastname"`
}
func (u *User) TableName() string {
return "user"
}
|
package deal
var publicKey = `-----BEGIN Pubkey-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk+89V7vpOj1rG6bTAKYM
56qmFLwNCBVDJ3MltVVtxVUUByqc5b6u909MmmrLBqS//PWC6zc3wZzU1+ayh8xb
UAEZuA3EjlPHIaFIVIz04RaW10+1xnby/RQE23tDqsv9a2jv/axjE/27b62nzvCW
eItu1kNQ3MGdcuqKjke+LKhQ7nWPRCOd/ffVqSuRvG0YfUEkOz/6UpsPr6vrI331
hWRB4... |
package main
import (
"fmt"
)
func makeEvenGenerator() func() int {
i := 0
return func() int {
i += 2
return i
}
}
func appendStr() func(string) string {
h := "Hello"
g := func(m string) string {
h = h + " " + m
return h
}
return g
}
func main() {
nextEven := makeEvenGenerator()
fmt.Println("initi... |
package imageProcess
import (
"fmt"
"github.com/mojocn/primitive/primitive"
"github.com/nfnt/resize"
"log"
"math/rand"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"time"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
//ProccessImage
//mode 0=combo 1=triangle 2=rect 3=ellipse 4=c... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
package main
import (
"flag"
"net/http"
"github.com/golang/glog"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/danielfm/crypto-exporter/collector"
)
var (
// VERSION set by build script
VERSION = "UNKNOWN"
addr = flag.Str... |
package controllers
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"github.com/shimastripe/gouserapi/db"
"github.com/shimastripe/gouserapi/models"
"github.com/shimastripe/gouserapi/server"
"testing"
)
var uuid string
func TestGetUsers(t *testing.T) {
response := httptest.NewRec... |
package logger
import "testing"
func TestInfo(t *testing.T) {
Info("test")
}
|
package models
import (
"encoding/hex"
"errors"
"math/big"
"github.com/appditto/pippin_nano_wallet/libs/utils"
"github.com/appditto/pippin_nano_wallet/libs/utils/ed25519"
"golang.org/x/crypto/blake2b"
)
// StateBlock is a block from the nano protocol
type StateBlock struct {
Type string `json:"type"... |
package util
import (
"gin_example/src/gin-blog/pkg/logging"
"github.com/astaxie/beego/validation"
)
/** 输出 valid Error */
func PrintValidError(errs []*validation.Error) {
for _, err := range errs {
logging.Info(err.Key, err.Message)
}
}
|
package main
import (
"fmt"
"io"
"os"
)
func main() {
args := os.Args
index := len(args) - 1
fileToOpen := args[index]
if index == 0 || index > 1 {
fmt.Println("Program only accepts one and only one argument. Check your command and try again.")
os.Exit(1)
}
//Easy way to do things:
/*
bs, err := io... |
package knob
import (
"fmt"
"reflect"
)
func PrintKnobs(e interface{}) error {
// e must be a pointer to struct.
ptr := reflect.ValueOf(e)
if ptr.Kind() != reflect.Ptr {
return fmt.Errorf("knob: expected a pointer to struct but was %v", reflect.TypeOf(e))
}
v := ptr.Elem()
if v.Kind() != reflect.Struct {
... |
package middleware
import (
"fmt"
"net/http"
"os"
"github.com/44t4nk1/jwt-go/api/models"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
var mySigningKey = []byte(os.Getenv("ACCESS_SECRET"))
func IsAuthorised(endpoint func(c *gin.Context)) gin.HandlerFunc {
return gin.HandlerFunc(func(c *gin.Conte... |
package main
import (
"context"
"fmt"
"log"
multipb "github.com/golang-grpc-snippet/drill_exercise_1/multiplication/protobuf"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("Error : %v", err)
}
c := multipb.NewMultiServic... |
/*
File describe gateway for working with vehicle data in database.
Author: Igor Kuznetsov
Email: me@swe-notes.ru
(c) Copyright by Igor Kuznetsov.
*/
package models
type VehicleGateway interface {
GetVehicleDict() (Vehicles, error)
AddVehicle(VehicleRec) error
}
type VehicleRec struct {
GpsID int `json:"g... |
package main
import (
"fmt"
"github.com/gudongkun/single_common"
"github.com/gudongkun/single_common/custom_gorm"
"github.com/gudongkun/single_common/jaeger"
"github.com/gudongkun/single_ucenter/enlight_ucenter_client"
"github.com/gudongkun/single_ucenter/enlight_ucenter_client/proto/user"
"github.com/gudongkun... |
// 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... |
// test-syncMap project main.go
package main
import (
"fmt"
"sync"
)
func main() {
fmt.Println("Hello World!")
var scene sync.Map
scene.Store("")
}
|
package core
import (
"strconv"
)
//operation
type Operation interface {
Run()
}
//simplest operation
type operation func()
func (o operation) Run() {
o()
}
//task
type Task struct {
Done chan bool
Operation Operation
}
func NewFuncTask(f func()) *Task {
return NewTask(operatio... |
package webservice
import (
"encoding/json"
"io/ioutil"
)
// 程序配置
type Config struct {
BackServiceTls bool `json:"backServiceTls"`
WsPort int `json:"wsPort"`
WsReadTimeout int `json:"wsReadTimeout"`
WsWriteTimeout int `json:"wsWriteTimeout"`
WsInChannelSize int `j... |
package main
func main() {}
func search(x []int, k int) int {
i := 0
basePos := 0
for i < len(x)-1 {
if x[i]-x[basePos] < k {
} else if x[i]-x[basePos] == k {
} else {
}
}
return -1
}
|
/*
* Copyright (C) 2019 Rohith Jayawardene <gambol99@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.... |
package guard
import (
"testing"
"time"
floc "gopkg.in/workanator/go-floc.v1"
"gopkg.in/workanator/go-floc.v1/run"
)
func TestTimeout(t *testing.T) {
const ID int = 1
f := floc.NewFlow()
s := floc.NewState(nil)
// Make timeout in 1 seconds with the job which should finish prior
// the timeout
job := run.... |
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func test() {
filename := "/tmp/fstab"
open, err := os.Open(filename)
if err != nil {
panic(err)
}
r := bufio.NewReader(open)
for {
readString, err := r.ReadString('\n')
if err == io.EOF {
return
}
if err != nil {
panic(err)
}
i... |
// Copyright (C) 2015 Scaleway. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.
package commands
import (
"fmt"
"os"
"github.com/scaleway/scaleway-cli/pkg/config"
)
// LogoutArgs are flags for the `RunLogout` function
type LogoutArgs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.