text stringlengths 11 4.05M |
|---|
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
scan := bufio.NewScanner(os.Stdin)
scan.Scan()
n, _ := strconv.Atoi(scan.Text())
gem := map[rune]int{}
for i := 0; i < n; i++ {
scan.Scan()
line := scan.Text()
for _, r := range line {
if gem[r] != i {
continue
} else {
... |
package main
import (
"fmt"
"strings"
)
var _ Match = (*OrMatch)(nil)
type OrMatch struct {
SubMatch []Match
}
func (om *OrMatch) AssembleMatch(counter *IDCounter, ruleEndLabel, actionLabel string) ([]string, error) {
orAsm := []string{
"# Or",
}
for i, match := range om.SubMatch {
matchAsm, err := match... |
package main
import (
"fmt"
"math/rand"
)
// 不稳定的选择排序
func selectSort(nums []int) {
for i:=0;i<len(nums);i++{
minIndex,minNumber := i,nums[i]
for t:=i+1;t<len(nums);t++{
if minNumber>nums[t]{
minIndex,minNumber = t,nums[t]
}
}
nums[i],nums[minIndex] = nums[minIndex],nums[i]
}
}
// -----------... |
package models
import (
"testing"
)
func TestProjectRequest_ToJSON(t *testing.T) {
projectRequest := ProjectRequest{}
_, err := projectRequest.ToJSON()
if err != nil {
t.Errorf("Expected the Project to cast to JSON")
}
}
func TestGetProjectRequest(t *testing.T) {
tests := map[string]struct {
project *Proje... |
package goSolution
func totalNQueens(n int) int {
ret := make([][]string, 0)
columns := (1 << n) - 1 // y
diag0 := 0 // x + y
diag1 := 0 // x - y + n - 1
board := make([][]bool, n)
for i := 0; i < n; i++ {
board[i] = make([]bool, n)
}
initLg2Map(n << 1)
SolveNQueens(0, n, columns, diag0, diag1, board, &ret... |
// Copyright 2020 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package agent
import (
"fmt"
"net/http"
"sync"
"github.com/clivern/walrus/core/backup"
"github.com/clivern/walrus/core/model"
"github.com/clivern/walrus/core/modul... |
package main
import (
"fmt"
)
// multiple closure iteration function :v cool, without passing any param btw
// fungsi ini akan mengembalikan ((int, bool), bool)
func IntClosureIterator(int_data []int) (func() (int, bool), bool){
// fungsi ini akan terus dijalankan melalui for loop
// sampai sehabisnya int_data
... |
package service
import (
"context"
"crypto/tls"
"net"
"net/http"
"time"
"github.com/go-ocf/cqrs/eventbus"
cqrsEventStore "github.com/go-ocf/cqrs/eventstore"
"github.com/go-ocf/kit/log"
oapiStore "github.com/go-ocf/cloud/cloud2cloud-connector/store"
"github.com/go-ocf/cloud/cloud2cloud-gateway/store"
"goog... |
package erratum
// Use opens a resouce and handles different error scenarios
func Use(o ResourceOpener, input string) (err error) {
r, err := o()
for err != nil {
if _, ok := err.(TransientError); !ok {
return err
}
r, err = o()
}
defer func() {
if rec := recover(); rec != nil {
if _, ok := rec.(Frob... |
package sqly
import (
"context"
"errors"
"fmt"
"testing"
)
func TestCapsule_Exec(t *testing.T) {
db, err := New(opt)
if err != nil {
t.Error(err)
}
capsule := NewCapsule(db)
ctx := context.TODO()
_, err = capsule.StartCapsule(ctx, true, func(ctx context.Context) (interface{}, error) {
query := "DROP TAB... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package export
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"os"
"strconv"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/go-sql-driver/mysql"
"github.com/pingcap/errors"
"... |
package main
import (
"net/http"
)
func handlerRoot(w http.ResponseWriter, r *http.Request) {
// TODO not this
http.Redirect(w, r, "/v1/", 301)
}
func handlerFavicon(w http.ResponseWriter, r *http.Request) {
return
}
|
package c24_break_mt19937_stream_cipher
import (
"bytes"
"math/rand"
"testing"
"time"
"github.com/vodafon/cryptopals/set1/c1_hex_to_base64"
)
func TestEncodeMT19937(t *testing.T) {
plaintext := []byte("some text")
seed := uint32(rand.Intn(maxSeed))
ciphertext := EncodeMT19937(plaintext, seed)
if bytes.Equal... |
// +build version
package main
import (
"fmt"
"k0s.io/k0s/pkg/version"
)
func main() {
fmt.Print(version.Version.JsonString())
fmt.Print(version.Version.YAMLString())
}
|
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"github.com/mailway-app/config"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
const (
API_BASE_URL = "https://apiv1.mailway.app"
)
var (
SERVICES = []string{
"mailout",
"maildb",
"auth",
"forwarding",
"frontli... |
package main
import "fmt"
func send(v chan<- int) {
v <- 10
close(v)
}
func main() {
c := make(chan int)
go send(c)
v, ok := <-c
fmt.Println(v, ok)
// This will fail if the channel is not closed because the reading operation will lock
// and the main routine will not be able to continue - deadlock.
v, ok... |
package main
import (
"github.com/OwnHeroNet/discordify-go/cmd"
)
func main() {
cmd.Execute()
}
|
package tokens
import (
"encoding/json"
"errors"
"net/http"
"github.com/connext-cs/pub/etcd"
"github.com/connext-cs/pub/log"
"strconv"
)
const (
SecretKey = "welcome to use connextpaas!"
)
const USERIDHEADER = "userid"
const USERTYPEHEADER = "usertype"
type Enum_UserType uint8
const (
User_None Enum_UserT... |
package _152_Maximum_Product_Subarray
func maxProduct(nums []int) int {
return maxProductDP1(nums)
}
func maxProductDP1(nums []int) int {
if len(nums) == 0 {
return 0
}
currMax, currMin := make([]int, len(nums)), make([]int, len(nums))
currMax[0], currMin[0] = nums[0], nums[0]
max := nums[0]
for i := 1; i < ... |
package calendar
import (
"booking-calendar/rpc"
"booking-calendar/utils"
"errors"
"github.com/google/uuid"
)
const (
BookAppointment rpc.Method = "bookAppointment"
CancelAppointment rpc.Method = "cancelAppointment"
CheckAvailability rpc.Method = "checkAvailability"
GetAppointments rpc.Method = "getAppoin... |
/*
* Copyright 2016-2020 Fraunhofer AISEC
*
* 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 ... |
package LatticeReduction
import (
"fmt"
"math/big"
)
// Lattice basis for big.Int sized values
type BigBasis [][]*big.Int
var (
bigOne = big.NewInt(1)
)
func bigIntToFloat(in *big.Int) float64 {
rat := new(big.Rat)
rat.SetFrac(in, bigOne)
f, _ := rat.Float64()
return f
}
func (b BigBasis) Copy() Basis {
o ... |
package data
import (
"context"
"encoding/json"
"regexp"
"strings"
"time"
"github.com/ardanlabs/graphql"
"github.com/pkg/errors"
)
// This is the schema for the application. This could be kept in a file
// and maintained for wider use. In these cases I would use gogenerate
// to hardcode the contents into the... |
package ifth
import (
"math/rand"
"time"
)
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
const hLetters = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789" //humanity letters
const (
Random = iota
AutoIncrement
)
var kv map[byte]int //map rune to index of letters
var... |
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compli... |
/*
Copyright 2015 Google Inc. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file or at
https://developers.google.com/open-source/licenses/bsd
*/
// package cdd represents the Cloud Device Description format described here:
// https://developers.google... |
package sim
import (
"math"
"math/rand"
"time"
)
type Simulacrum struct {
sim *Simulation
rng *rand.Rand
}
func NewSimulacrum(sim *Simulation) *Simulacrum {
rng, _ := sim.Rng()
return &Simulacrum{
sim: sim,
rng: rng,
}
}
func (s *Simulacrum) Sim() *Simulation {
return s.sim
}
func (s *Simulacrum) Rng(... |
package main
// Shape interface
// type 'name' interface { methods() returnValue }
type Shape interface {
Area() float64
}
// to 'implement' just name the structs's method with the same name of the interface
|
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package stream_test
import (
"testing"
"github.com/pingcap/tidb/br/pkg/stream"
"github.com/stretchr/testify/require"
)
func TestDecodeKVEntry(t *testing.T) {
var (
pairs = map[string]string{
"db": "tidb",
"kv": "tikv",
"company": ... |
package main
//切片
import "fmt"
/*
元素类型为 T 的切片表示为: []T。
通过 a[start:end] 这样的语法创建了一个从 a[start] 到 a[end -1] 的切片。
在上面的程序中,第 9 行 a[1:4] 创建了一个从 a[1] 到 a[3] 的切片。因此 b 的值为:[77 78 79]。
*/
/*
下面是创建切片的另一种方式:
*/
//func main() {
//
// c := []int{76, 77, 78, 79, 80}
// fmt.Println(c)
// // 在上面的程序中,第 9 行 c := []int{6, 7, 8} 创建了一个长度... |
package main
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
var tld, strout string
var visited map[string]bool
var f1file *os.File
func processPage(s string) {
visited[s] = true
doc, err := goquery.NewDocument(s)
if err != nil {
fmt.Println("\nPage - ", s, " NOT FOUND")... |
package pack
import (
"KServer/library/kiface/imongo"
"KServer/library/kiface/iredis"
"KServer/library/mongo"
"KServer/library/redis"
"KServer/manage/config"
)
type IDb interface {
Redis() iredis.IRedisPool
Mongo() imongo.IMongo
}
type Db struct {
IRedisPool iredis.IRedisPool
IMongo imongo.IMongo
}
fun... |
// Azure Service Bus implementation of the Service Bus interface.
package asb
import (
"encoding/json"
"fmt"
"github.com/michaelbironneau/asbclient"
"mvp/integration"
"time"
)
const(
ENDPOINT = "service.bus.endpoint"
ROOT_KEY_NAME = "service.bus.root.key.name"
ROOT_KEY_VALUE = "service.bus.root.key.value"
)
... |
package main
import "./miner"
import "io/ioutil"
import "os"
import "strings"
func main(){
serverIP := os.Args[1]
// Grab pubKey and privKey from key-pairs.txt
keyBytes, _ := ioutil.ReadFile("./key-pairs.txt")
keyString := string(keyBytes[:])
privKey := strings.Split(keyString, "\n")[0]
pubKey := strings.Spl... |
package cmd
import (
"net/http"
)
func NotificationList() error {
res, err := executeJsonCmd(http.MethodGet, "notifications", params{}, nil)
if err != nil {
return err
}
output(res)
return nil
}
func NotificationRead(id string) error {
res, err := executeStringCmd(http.MethodPost, "notifications/"+id+"/read... |
package main
import (
"flag"
"fmt"
"runtime"
"time"
"github.com/brunoga/context"
"github.com/brunoga/workerpool"
"github.com/brunoga/workerpool/worker"
)
var (
flagNumWorkers = flag.Int("num_workers", runtime.NumCPU(),
"number of workers to use")
flagMaxNumber = flag.Uint64("max_number", 10,
"max number... |
package fuel
import (
"math"
)
func CalcFuel(mass int) int {
fuel := int(math.Floor(float64(mass)/3)) - 2
if fuel > 0 {
fuel += CalcFuel(fuel)
}
return int(math.Max(float64(fuel), 0.0))
}
|
package hooks
type thing struct {
text string
i int
i8 int8
i16 int16
i32 int32
i64 int64
u uint
u8 uint8
u16 uint16
u32 uint32
u64 uint64
}
func (t *thing) SetText(tstr string) {
t.text = tstr
}
type hooker interface {
Sethook(*Hook) bool
Process(*thing) *thing
preprocess(*thing) bool... |
package main
import (
"context"
"testing"
"time"
"github.com/robustirc/robustirc/internal/ircserver"
"github.com/robustirc/robustirc/internal/outputstream"
"github.com/robustirc/robustirc/internal/robust"
"gopkg.in/sorcix/irc.v2"
)
// TestPlumbing exercises the code paths for storing messages in outputstream
... |
package cache
import (
"bytes"
"io/ioutil"
"math/rand"
"os"
"testing"
)
func TestFSGenerateFilename(t *testing.T) {
fs, err := NewFS()
if err != nil {
t.Fatalf("Could not create FS: %s", err)
}
key := make([]byte, 32)
for i := range key {
key[i] = byte(i % 256)
}
path := fs.generateFilename("", KIND_I... |
// This file was generated for SObject ContentDocumentHistory, API Version v43.0 at 2018-07-30 03:47:17.642784027 -0400 EDT m=+3.985540014
package sobjects
import (
"fmt"
"strings"
)
type ContentDocumentHistory struct {
BaseSObject
ContentDocumentId string `force:",omitempty"`
CreatedById string `force:",... |
// Package cmd is the parent package of all viztransform commands.
package cmd
import (
"flag"
"fmt"
"os"
)
// Fail with error err.
func Fail(err error) {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
// Init command with description u by setting a usage func.
func Init(u string) {
flag.Usage = func() {
f... |
/*
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, so... |
package contextawarereader
import (
"context"
"io"
)
type CancellableReader struct {
delegate io.Reader
ctx context.Context
}
func (r *CancellableReader) Read(p []byte) (n int, err error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
return r.delegate.Read(p)
}
func NewCancellableReader(ctx co... |
package reconciler
import (
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/operator-framework/api/pkg/operators/v1alpha1"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/queueinformer"
)
// SyncRegistryUpdateInterval returns a duration to use when requeuing the catalog source... |
package collector
import (
"errors"
"net/http"
"strconv"
"unsafe"
"github.com/huaweicloud/cloudeye-exporter/logs"
"github.com/huaweicloud/golangsdk"
"github.com/huaweicloud/golangsdk/openstack"
"github.com/huaweicloud/golangsdk/openstack/autoscaling/v1/groups"
"github.com/huaweicloud/golangsdk/openstack/bloc... |
package search
import (
"fmt"
"io"
)
func PrintfRequestHandler(wr io.Writer) func(r Request) error {
return func(r Request) error {
fmt.Fprintf(wr, "Received search request with echo back ID %v\n", r.EchoBackID)
return nil
}
}
func PrintfResponseHandler(wr io.Writer) func(r Response) error {
return func(r R... |
package main
import "github.com/MeztliRA/gemit/cmd"
func main() {
cmd.Execute()
}
|
package config_test
import (
"code.cloudfoundry.org/cli/plugin/pluginfakes"
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pivotal-cf/spring-cloud-services-cli-plugin/config"
"github.com/pivotal-cf/spring-cloud-services-cli-plugin/httpclient/httpclientfakes"
"github.com/pivotal-cf/sp... |
package logic
import "fmt"
type logger struct {
p Printer
verbose bool
}
func (l *logger) Error(format string, a ...interface{}) {
str := fmt.Sprintf(format, a...)
l.p.Print("<red>%s</>\n", str)
}
func (l *logger) Verbose(format string, a ...interface{}) {
if l.verbose {
l.p.Print(format, a...)
}
}
f... |
// HTTP helpers
package httph
import (
"context"
"net/http"
"net/url"
"github.com/gotidy/app/pkg/log/hlog"
"github.com/gotidy/app/pkg/scope"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type server struct {
Server *http.Server
Addr *url.URL
Metrics bool
}
type Option func(opts *server)
... |
package main
import "fmt"
func main() {
var x,y,z string
x="Dr. Strange"
y= "Modon Lal"
z= "Robin Hood"
fmt.Println(x)
fmt.Println(y)
fmt.Println(z)
}
|
package wrapper
import (
"strings"
)
const PathParamsKey = "path_params"
func CurlyToColon(path string) string {
path = strings.Replace(path, "{", ":", -1)
path = strings.Replace(path, "}", "", -1)
return path
}
|
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
//
// 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 ... |
package main
import "fmt"
func main() {
var a [5]int
fmt.Println("Empty 5 element array ", a)
a[4] = 100
fmt.Println("set: ", a)
fmt.Println("get: ", a[4])
/* As in Python the built in function len gives the length of the array */
fmt.Println("Len of a array: ", len(a))
/* Initializing and declaring an arr... |
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func wrapPrometheusMetrics(handler http.Handler) http.Handler {
counter := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "s3proxy_api_requests_total",
He... |
package merchant
import (
"context"
"tpay_backend/adminapi/internal/common"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"tpay_backend/model"
"tpay_backend/utils"
"github.com/tal-tech/go-zero/core/logx"
)
type AddMerchantLogic struct {
logx.Logger
ctx context.Context
svcCt... |
// Copyright (c) 2020 Xiaozhe Yao & AICAMP.CO.,LTD
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package utilities
import "testing"
func TestCheckError(t *testing.T) {
type args struct {
err error
errorMessage string
}
tests := []struct {
name string
... |
package middleware
import (
"fmt"
"log"
"net/http"
"time"
)
func Logger(next http.HandlerFunc, name string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() {
log.Printf("%s\t%s\t%s\t%s", r.Method, r.RequestURI, name, time.Since(start))
if err ... |
package main
import "fmt"
func main() {
var escolhaCerta int
fmt.Scanf("%d\n", &escolhaCerta)
respostasCertas := 0
for i := 0; i < 5; i++ {
var escolha int
fmt.Scanf("%d", &escolha)
if escolha == escolhaCerta {
respostasCertas++
}
}
fmt.Println(respostasCertas)
}
|
package service
import (
"context"
"fmt"
"net/http"
"github.com/go-ocf/cloud/cloud2cloud-connector/store"
)
type LinkedCloudsHandler struct {
linkedClouds []store.LinkedCloud
}
func (h *LinkedCloudsHandler) Handle(ctx context.Context, iter store.LinkedCloudIter) (err error) {
var s store.LinkedCloud
for iter... |
package mapper
import (
"github.com/jackc/pgx"
"github.com/neuronlabs/errors"
"github.com/neuronlabs/neuron-core/class"
)
var pqMapping = map[string]errors.Class{
// Class 02 - No data
"02": class.QueryValueNoResult,
"P0002": class.QueryValueNoResult,
// Class 08 - Connection Exception
"08": class.Reposi... |
package env_test
import (
"testing"
"github.com/nasermirzaei89/env"
"github.com/stretchr/testify/assert"
)
func TestGetInt(t *testing.T) {
def := 12
res := env.GetInt("V1", def)
assert.Equal(t, def, res)
t.Setenv("V1", "invalid")
res = env.GetInt("V1", def)
assert.Equal(t, def, res)
t.Setenv("V1", "14"... |
package newredis
import (
"strings"
"strconv"
)
type fn func(s *Server, conn Conn, cmd Command) error
var commandMap = make(map[string]fn)
func registerCmd(cmd string, f fn) {
commandMap[cmd] = f
}
func DoCmd(s *Server, conn Conn, cmd Command) error {
c := strings.ToLower(string(cmd.Args[0]))
f, found := comm... |
// Copyright 2013 Benjamin Gentil. All rights reserved.
// license can be found in the LICENSE file (MIT License)
package zlang
import (
"fmt"
"github.com/go-llvm/llvm"
//"strconv"
)
type Parser struct {
Input string
Module llvm.Module
Builder llvm.Builder
l *Lexer
currentItem LexItem... |
package service
import (
"github.com/parsaakbari1209/Chatapp-oauth-api/domain"
)
// OAuth interface defines the available service methods.
type OAuth interface {
Refresh(refreshToken string) (newAccessToken, newRefreshToken string, e error)
Create(userID string) (accessToken, refreshToken string, e error)
Verify(... |
package model
import (
"time"
)
type Post struct {
Id int `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
CreatedDate time.Time `json:"createdDate"`
UpdatedDate time.Time `json:"updatedDate"`
Skills string `json:"skills,omitempty"`
Budget ... |
package models
// MsgData - The model to Map the message received from MQ
type MsgData struct {
Offers []Offers `json:"offers"`
}
// Offers - Model to hold Offers object
type Offers struct {
Hotel Hotel `json:"hotel"`
Room Room `json:"room"`
RatePlan RatePlan `json:"rate_plan"`
}
// Hotel - Model t... |
package state
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"go.uber.org/zap"
"github.com/s-matyukevich/capture-criminal-tg-bot/src/common"
dbpkg "github.com/s-matyukevich/capture-criminal-tg-bot/src/db"
"github.com/s-matyukevich/capture-criminal-tg-bot/src/helpers"
)
type Report struct {
... |
package main
import (
"fmt"
)
func main() {
tômortadecansaço := true
if tômortadecansaço {
fmt.Println("um dia eu gostaria de ir pra cama")
}
}
|
package server
import (
. "github.com/batchcorp/plumber/validate"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/batchcorp/plumber-schemas/build/go/protos/common"
)
var _ = Describe("Server", func() {
Context("CustomError", func() {
It("Returns error wrapper", func() {
err := CustomError... |
package usecase
import (
"errors"
"github.com/huf0813/pembukuan_tk/entity"
"github.com/huf0813/pembukuan_tk/repository/sqlite"
"github.com/huf0813/pembukuan_tk/utils"
)
type UserUseCase struct {
UserRepo sqlite.UserRepo
Hash utils.Hashing
}
type UserUseCaseInterface interface {
GetUsers() ([]entity.User, ... |
package main
import (
"fmt"
"math"
"os"
)
type token struct {
name string
value int
index int
start_id int
end_id int
}
var roman = map[string]int{
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
var error_message = map[string]string{
"lexical_error": "Quid dicis? You... |
package main
import (
"testing"
)
func TestGetagFromPath(t *testing.T) {
tag, _ := getagFromPath("bari_cities")
if tag != "cities" {
t.Errorf("Expected 'cities', but got '%v'\n", tag)
}
}
|
package main
import "fmt"
func main() {
num := 2
switch {
case num == 1:
fmt.Println(1)
case num == 2:
fmt.Println(2)
default:
fmt.Println("No Number")
}
}
|
package workspace
import (
"fmt"
"net/url"
"os"
"path"
"strings"
"bldy.build/build/label"
"github.com/pkg/errors"
)
const (
// BUILDFILE is the name of the file that keeps targets
BUILDFILE = "BUILD"
)
var (
// ErrNotAWorkspace is returned when the given URL is not a workspace
ErrNotAWorkspace = errors.N... |
package meta
import "time"
// APIVersion represents the API and major version thereof with which this
// version of the Brigade SDK is compatible.
const APIVersion = "brigade.sh/v2"
// TypeMeta represents metadata about a resource type to help clients and
// servers mutually head off potential confusion over types (... |
/*
Given a positive int64eger, print64 that many Hamming numbers, in order.
Rules:
Input will be a positive int64eger n≤1,000,000
Output should be the first n
terms of https://oeis.org/A051037
Execution time must be <1 minute
This is code-golf; shortest code wins
*/
package main
import "fmt"
func main() {... |
package plugin
import (
"strings"
"github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
"github.com/gogo/protobuf/protoc-gen-gogo/generator"
)
func (p *OrmPlugin) generateDefaultServer(file *generator.FileDescriptor) {
for _, service := range file.GetService() {
svcName := generator.CamelCase(service.GetName()... |
package main
import "fmt"
import "crypto/sha1"
import "os"
import "log"
import "strconv"
func main() {
if len(os.Args) != 2 && len(os.Args) != 3 {
fmt.Printf("Usage:%s file length\n", os.Args[0])
return
}
var err error
var length int = 102400000
if len(os.Args) == 3 {
length, err = strconv.Atoi(os.Args[2]... |
package main
import (
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
// =====================================================
// getVote - retrieve vote metadata from chaincode state
// =====================================================
func (vc *VoteChaincode... |
package main
import "fmt"
func main() {
var n int
fmt.Scanf("%d", &n)
people := 5
sum := 0
for day := 0; day < n; day++ {
people = people / 2
sum += people
people *= 3
}
fmt.Println(sum)
}
|
package logic
import (
"errors"
"fmt"
"math/rand"
"sync"
"sync/atomic"
v1 "fxkt.tech/bj21/api/bj21/v1"
)
const (
statusIdle = "idle"
statusGaming = "gaming"
)
type Table struct {
Name string
Seq string
P1, P2 *Player
Pk Poker
Status string
round ... |
package _2130_Maximum_Twin_Sum_of_Linked_List
import (
"math"
"github.com/shadas/leetcode_notes/utils/linkedlist"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func pairSum(head *linkedlist.IntListNode) int {
return pairSumSlice(head)
}
func p... |
/*
https://developer.github.com/v3/issues
*/
package githubLib
import (
"encoding/json"
)
type Issue struct {
ID int
Url string
Labels_url string
Comments_url string
Events_url string
html_url string
Number int
State string
Title string
Body string
Us... |
package main
import (
"log"
"net"
"net/http"
"os"
pb "github.com/binjamil/keyd/grpc"
"github.com/binjamil/keyd/service"
"github.com/gorilla/mux"
"google.golang.org/grpc"
)
func main() {
grpcEnabled := os.Getenv("GRPC_ENABLED")
err := service.InitializeTransactionLog()
if err != nil {
panic(err)
}
if... |
package controllers
import (
"github.com/skrbug/GoWeb/common"
"github.com/skrbug/GoWeb/datamodels"
"github.com/skrbug/GoWeb/services"
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
"strconv"
)
type OrderController struct {
Ctx iris.Context
OrderService services.IOrderService
}
func (o *Orde... |
// nolint
package auth
import (
"fmt"
"testing"
"github.com/irisnet/irishub/codec"
"github.com/irisnet/irishub/modules/params"
"github.com/irisnet/irishub/store"
sdk "github.com/irisnet/irishub/types"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tenderm... |
package solution
/*
Problem: Given a string s, find the longest palindromic substring in s.
Constraints:
1 <= s.length <= 1000
s consist of only digits and English letters (lower-case and/or upper-case),
*/
// madam, adda, babab, bb
// s consist of only digits and English letters (lower-case and/... |
package decider
import (
"errors"
"github.com/open_sesame/decider/openalpr"
"github.com/open_sesame/utils"
)
type LicencePlatesDecider struct {
config* LicencePlatesDeciderConfig
alpr* openalpr.Alpr
}
func (_ LicencePlatesDecider) NewDecider(options *[]interface{}) (Decider, error) {
if len((*options)) == 0 {
... |
package main
import (
"fmt"
"log"
"os/exec"
"strconv"
"github.com/itchyny/volume-go"
)
const (
showingTime = "300"
)
func main() {
vol, err := volume.GetVolume()
if err != nil {
log.Fatalf("get volume failed: %+v", err)
}
fmt.Printf("current volume: %d\n", vol)
if vol == 100 {
message := "volume: " ... |
package solutions
import (
"fmt"
"testing"
)
func TestMaxSubArray(t *testing.T) {
t.Run("Test maxSubArray", func(t *testing.T) {
var tests = []struct {
input []int
want int
}{
{
[]int{-2, 1, -3, 4, -1, 2, 1, -5, 4},
6,
},
}
for _, v := range tests {
t.Run(fmt.Sprintf("input=%v, want... |
package internal
import (
"fmt"
"runtime"
"github.com/go-playground/validator"
"github.com/gofiber/fiber/v2"
)
type (
errorLocation struct {
File string
Line int
}
customError struct {
Location *errorLocation
Message string
Original error
}
Error customError
)
const (
ErrBEEmail = "Er... |
package sample_data
import (
"math/rand"
"time"
"github.com/psinthorn/gostore/pb"
)
// by default random will use fix seed to create then some of random value will be remain the same
// we can fix it by tell random to use diffenrent seed to run
// by using below code
func init() {
rand.Seed(time.Now().UnixNano()... |
package miner
import (
"fmt"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
xc "github.com/filecoin-project/go-state-types/exitcode"
"github.com/ipfs/go-cid"
"golang.org/x/xerrors"
"github.com/filecoin-project/specs-actors/actors/util/adt"
)
func LoadSectors(store ... |
package main
import (
"os"
"os/exec"
"path"
"testing"
"time"
"gopkg.in/fsnotify.v1"
)
// Setup & Mocks
// ----------------------------------------------
var gopath = os.Getenv("GOPATH")
type mockResponder struct {
changeDetected bool
}
func (mresp *mockResponder) onChange(r *reloadr, event fsnotify.Event) {... |
package typeindex
import (
"github.com/g-harel/gothrough/internal/extract"
"github.com/g-harel/gothrough/internal/typeindex/cases"
"github.com/g-harel/gothrough/internal/types"
)
// InsertValue adds a value to the index.
func (idx *Index) InsertValue(location extract.Location, val types.Value) {
idx.results = app... |
package main
import (
"strconv"
)
//REVIEW STRUCT//
//type Review struct {
// date string `json: "date", db:"day"`
// store_id int `json: "sid", db:"store_id"`
// answers bitarray.BitArray `json: "answers", db:"answers"`
// feedback string `json: "feedback", db:"feedback"`
//}
func (store *dbStore) GetReview(locati... |
package helper
import (
"strings"
)
type ProxAddress struct {
IP string `json:"IP"`
Port string `json:"Port"`
}
var sorted []ProxAddress
// GetUrls returns URL list to scrape
func GetUrls() ([]string, error) {
var a []string
a[0] = "test"
a[1] = "ing"
return a, nil
}
func SplitProxy(list []string) {
f... |
package collector
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/huaweicloud/cloudeye-exporter/logs"
"github.com/huaweicloud/golangsdk/openstack/ces/v1/metricdata"
"github.com/huaweicloud/golangsdk/openstack/ces/v1/metrics"
"github.com/prometheus/clie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.