text stringlengths 11 4.05M |
|---|
package mycirculardeque
import "container/list"
type MyCircularDeque struct {
l *list.List
size int
}
/** Initialize your data structure here. Set the size of the deque to be k. */
func Constructor(k int) MyCircularDeque {
return MyCircularDeque{
l: list.New(),
size: k,
}
}
/** Adds an item at the fro... |
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSleep(t *testing.T) {
api := &timer{}
api.Sleep(0)
}
func TestTimerMiddleware(t *testing.T) {
context := createFakeGinContext()
timerMiddleware(context)
_, ok := context.Get("timerAPI")
assert.True(t, ok)
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package utils
import (
"context"
// Used to embed api_wrapper.js in string variable `systemDataProviderJs`.
_ "embed"
"chromiumos/tast/errors"
"chromiumos/tast/local/c... |
package main
import (
"github.com/ohmyray/my-blog/model"
"github.com/ohmyray/my-blog/route"
)
func main() {
model.InitConnection()
route.InitRouter()
}
|
package main
import (
"fmt"
"encoding/hex"
"encoding/base64"
)
func main() {
hex_string := "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
byte_slice, _ := hex.DecodeString(hex_string)
base64_string := base64.StdEncoding.EncodeToString(byte_slice)
fmt.Println(... |
package keyadmin
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"reflect"
"strings"
)
type ConfigType struct {
DataUri string `json:"data_uri"`
PublicKeyDir string `json:"public_key_dir"`
PrivateKeyDir string `json:"private_key_dir"`
Way []string `json:"way"`
KeyLength int ... |
// Copyright (c) 2016-2019 Uber 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... |
package eventchannel
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBuildEndpointSender(t *testing.T) {
requestBody := make([]byte, 10)
server := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer req.Body.Clos... |
package config
import (
"flag"
"fmt"
"math/rand"
"net"
"strings"
"time"
)
// AppConf 应用全局参数
var AppConf appConf
func init() {
var mode string
flag.BoolVar(&AppConf.Debug, "debug", false, "调试模式,默认:false")
flag.StringVar(&AppConf.IP, "ip", "", "监听的IP地址,默认:127.0.0.1")
flag.IntVar(&AppConf.Port, "port", 0, "服务... |
package main
import (
"fmt"
)
type Person struct{
first_name string
last_name string
dateofbirth string
sex string
country string
}
type Employee struct{
Person
section string
work_years int
}
func (p *Person) String() string {
return fmt.Sprintf("Name : %s %s, M/F : %s", p.first_name, p.last_nam... |
package gui
import (
"image/color"
"math"
"github.com/jameshiew/fractal-explorer/internal/draw"
"github.com/jameshiew/fractal-explorer/internal/mandelbrot"
)
var (
red = color.RGBA64{R: 65535, A: 65535}
green = color.RGBA64{G: 65535, A: 65535}
blue = color.RGBA64{B: 65535, A: 65535}
)
// darkBlend is quit... |
package util
import (
"fmt"
"github.com/muesli/cache2go"
"time"
)
type myStruct struct {
text string
moreData []byte
}
func CacheUtil() {
cache := cache2go.Cache("myCache")
val := myStruct{"This is a test!", []byte{}}
cache.Add("someKey", 5*time.Second, &val)
res, err := cache.Value("someKey")
if err =... |
package requests
import (
"fmt"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
)
// LoadCustomData Load custom user data.
//
// Arbitrary JSON data can be stored for a User. This API call
// retrieves that data for a (optional) given scope.
// See {api:UsersCont... |
package model
import (
"encoding/json"
"fmt"
"math"
"testing"
"github.com/kylelemons/godebug/pretty"
)
func TestNewDataPoint(t *testing.T) {
p := NewDataPoint(1000, 0.1)
if p.Timestamp() != 1000 {
t.Fatalf("\nExpected: %+v\nActual: %+v", 1000, p.Timestamp())
}
if p.Value() != 0.1 {
t.Fatalf("\nExpecte... |
package persistence
import (
"database/sql"
"fmt"
"fp-dynamic-elements-manager-controller/internal/logging/structs"
"github.com/jmoiron/sqlx"
"time"
)
const (
BatchTable = "element_batches"
)
type ElementBatchRepo struct {
db *sqlx.DB
log *structs.AppLogger
}
func NewElementBatchRepo(appDb *sqlx.DB, logger... |
package storage
import (
"log"
"code.google.com/p/gcfg"
)
type blog struct {
Title string
Subtitle string
Owner string
ArticlesPerPage int
DataBase string
}
type captcha struct {
Public string
Private string
}
type comments struct {
Maxlen int
Enabled bool
}
type smt... |
package innerSortImplTest
import (
"AlgorithmPractice/src/DataStructure/sort/innerSort/innerSortImpl"
"AlgorithmPractice/src/UnitTest/DataStructureTest/sortTest/innerSortTest"
"testing"
)
func TestBucketSort(t *testing.T) {
innerSortTest.SortSQLTest(t, &innerSortImpl.BucketSort{})
/* grammar: 判断数组是否相等
a := []i... |
package connector
import (
"daerclient"
"logger"
"majiangclient"
"pockerclient"
"rpc"
)
//匹配房公共
func (self *CNServer) EnterRoomREQ(conn rpc.RpcConn, msg rpc.EnterRoomREQ) error {
logger.Info("client call EnterRoomREQ begin")
p, exist := self.getPlayerByConnId(conn.GetId())
if !exist {
return nil
}
// p.w... |
/*
Copyright 2017 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, s... |
package datagramsession
import (
"bytes"
"context"
"fmt"
"io"
"net"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
"github.com/cloudflare/cloudflared/packet"
)
// TestCloseSession makes sure a session will stop... |
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dns
import (
"context"
"io/ioutil"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"chromiumos/tast/common/crypto/certificate"
"chromiumos/tast/commo... |
package balance
import (
"testing"
)
func TestHashing(t *testing.T) {
hash := New(10, nil)
hash.Add("9", "2", "8")
testCases := map[string]string{
"10": "10",
"13": "13",
"29": "29",
"20": "20",
}
for k, v := range testCases {
if hash.Get(k) != v {
t.Errorf("Asking for %s, get %s", v, hash.Get(k... |
package graylogger
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"sync"
"testing"
"bou.ke/monkey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
var testInit = Init{
//GraylogHost: "127.0.0.1",
//GraylogPort: 12201,
//GraylogProvider: "TestService",
... |
package services
import (
"net/http"
"github.com/rwbailey/microservices/mvc/domain"
"github.com/rwbailey/microservices/mvc/utils"
)
type itemsService struct{}
var (
ItemsService itemsService
)
func (*itemsService) GetItem(itemId int64) (*domain.Item, *utils.ApplicationError) {
return nil, &utils.ApplicationEr... |
package insertSort
// 插入排序
func insertSort(arr []int) {
for i := 1; i < len(arr); i++ {
current := arr[i]
preindex := i - 1
for preindex >= 0 && arr[preindex] > current {
arr[preindex+1] = arr[preindex]
preindex--
}
arr[preindex+1] = current
}
} |
// +build !js
package math4g
import (
"math"
)
const (
uvnan uint32 = 0x7F800001
)
func NaN() Scala {
return Scala(math.Float32frombits(uvnan))
}
func IsNaN(x Scala) bool {
return x != x
}
func Cbrt(x Scala) Scala {
return Scala(math.Cbrt(float64(x)))
}
|
package codequalitybinding
import (
"alauda.io/devops-apiserver/pkg/apis/devops/v1alpha1"
devopsclient "alauda.io/devops-apiserver/pkg/client/clientset/versioned"
"alauda.io/diablo/src/backend/api"
"github.com/golang/glog"
"k8s.io/apimachinery/pkg/apis/meta/v1"
)
func toDetails(codeQualityBinding *v1alpha1.CodeQ... |
package main
import (
"fmt"
"os"
"runtime"
"time"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/net"
"github.com/shirou/gopsutil/v3/mem"
)
type LSysInfo struct {
MemAll uint64
MemFree uint64
MemUsed u... |
package tests
import (
M "github.com/ionous/sashimi/compiler/model"
. "github.com/ionous/sashimi/script"
"github.com/ionous/sashimi/util/ident"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)
//
// create a single subclass called stories
func TestRelation(t *testing.T) {
... |
package release
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/blang/semver/v4"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
_ "k8s.io/klog/v2" // integration tests set glog flags.
)
func TestGetUpdates(t *testing.T) {
arch := "te... |
package main
import (
"fmt"
)
func main() {
t := []float32{1.2,3.2,5.4}
fmt.Println(Sum(t))
}
func Sum(arrF []float32) (s float32) {
for _, v := range arrF {
s += v
}
return
}
|
package dao
import (
"ego-user-service/utils/uuid"
"errors"
"fmt"
"github.com/go-log/log"
userInfoProto "github.com/qianxunke/ego-shopping/ego-common-protos/go_out/user/user_info"
"github.com/qianxunke/ego-shopping/ego-plugins/db"
"net/http"
)
func UserIsExit(userName string) (u *userInfoProto.UserInf, err err... |
/*
Copyright 2021-2023 ICS-FORTH.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software... |
// import (
// "fmt"
// "kto/transaction"
// "kto/types"
// "kto/until"
// )
// func main() {
// l := len("Kto72tzGAwYH7dHGbEH4yiz5gxWSqq9fRDSxXwsJPX98y25")
// fmt.Println(l)
// from_byte := []byte("Kto9sWkzypDGvxfgcXu5eXJrRzwtX9rG1ftPwQ2NMw3TraX")
// to_byte := []byte("Kto72tzGAwYH7dHGbEH4yiz5gxWSqq9fRDSxXws... |
package core_test
import (
"github.com/d11wtq/bijou/core"
"github.com/d11wtq/bijou/runtime"
"github.com/d11wtq/bijou/test"
"testing"
)
func example(env runtime.Env, args runtime.Sequence) (runtime.Value, error) {
return args, nil
}
func TestGoFunc(t *testing.T) {
fn := core.GoFunc(example)
if fn.Type() != ru... |
package main
import (
"fmt"
"math"
)
func min(a, b int) int {
if a < b {
return a
}
return b
}
func findMin(nums []int) int {
if len(nums) == 0 {
return math.MaxInt32
}
if len(nums) == 1 {
return nums[0]
}
if len(nums) == 2 {
return min(nums[0], nums[1])
}
if nums[0] < nums[... |
package main
import (
"fmt"
"math"
"strconv"
)
func check(n int64, p int) int64 {
if p == 1 {
return n - 1
}
b := int64(math.Pow(float64(n), 1./float64(p)))
if b == 1 {
return -1
}
x, s := int64(1), int64(1)
for i := 0; i < p; i++ {
x = x * b
s = s + x
}
if n == s {
return ... |
package main
import (
"fmt"
"os/exec"
"time"
)
func main() {
ticker := time.Tick(time.Minute * 30)
ticker2 := time.Tick(time.Hour * 24)
out, err := exec.Command("/etc/init.d/ssh", "start").Output()
fmt.Print(out, err)
for {
select {
case <-ticker2:
puppetsync()
case <-ticker:
// http api check acc... |
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httputil"
"time"
)
// The Time is now
type Time struct {
Time string
}
func logRequest(r *http.Request) string {
requestDump, err := httputil.DumpRequest(r, true)
if err != nil {
fmt.Println(err)
}
return string(requestDump)
}
func ... |
// Copyright (C) 2016-Present Pivotal Software, Inc. All rights reserved.
// This program and the accompanying materials are made available under the terms of the 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 Licen... |
package odoo
import (
"fmt"
)
// AccountAnalyticTag represents account.analytic.tag model.
type AccountAnalyticTag struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
Active *Bool `xmlrpc:"active,omptempty"`
Color *Int `xmlrpc:"color,omptempty"`
CreateDate *Time `xmlrpc:"cr... |
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
// Copyright 2019 The gVisor 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 agree... |
package connector
import (
"fmt"
"time"
core_v1 "k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// GetServiceMap gives all services in a map to look them up in (namespace)-(service) format
func (c *Client) GetServiceMap() (map[string]core_v1.Service, error) {
servicesList, err := c.clients... |
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package commands
import (
"encoding/json"
)
func stringRepresentation(value interface{}) (string, error) {
var result string
switch value.(type) {
case string:
result = value.(string) // use string value as-is
default:
json, err := json.Marshal(value)
if err != nil {
return "", err
}
result = string... |
package routers
import (
"github.com/astaxie/beego"
"github.com/naokij/gotalk/controllers"
)
func init() {
beego.Errorhandler("404", controllers.Error404)
beego.Errorhandler("403", controllers.Error403)
beego.Errorhandler("500", controllers.Error500)
beego.Errorhandler("Once", controllers.ErrorOnce)
beego.Erro... |
package lc
import "strings"
// Time: O(n) - n = letters
// Benchmark: 4ms 4.1mb | 100%
func shortestCompletingWord(licensePlate string, words []string) string {
var count int
letters := make([]int, 26)
for _, ch := range licensePlate {
if ch >= 'a' && ch <= 'z' {
letters[ch-'a']++
count++
}
if ch >= ... |
package adapters
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/smartcontractkit/chainlink/store"
"github.com/smartcontractkit/chainlink/store/models"
)
// Bridge adapter is responsible for connecting the task pipeline to external
// adapters, allowing for custom computat... |
package api
import (
"testing"
"ark/store"
)
type mockLoadBalancer struct {
count int
}
type mockStore struct {
rts map[string]*store.Route
}
func (l *mockLoadBalancer) Update([]*store.Route) error {
l.count++
return nil
}
func newStore() store.Store {
return &mockStore{
rts: map[string]*store.Route{},
... |
package main
import (
crand "crypto/rand"
"fmt"
"math"
"math/big"
"math/rand"
"strings"
"sync"
"time"
)
var (
once sync.Once
SeededSecurely bool
)
func init() {
SeedMathRand()
}
func SeedMathRand() {
once.Do(func() {
n, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
ra... |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package store
import (
"database/sql"
"encoding/json"
sq "github.com/Masterminds/squirrel"
"github.com/mattermost/mattermost-cloud/model"
"github.com/pkg/errors"
)
const (
subscriptionsTable =... |
package main
import (
"fmt"
"net/http"
"squad-manager/routes"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
)
func main() {
r := mux.NewRouter()
err := godotenv.Load()
if err != nil {
/* TODO Implement the logger to capture all events and remove the panics */
fmt.Println("Found err in env load: ", ... |
package sgml
import (
"fmt"
"strings"
"unicode"
"github.com/bytesparadise/libasciidoc/pkg/types"
)
func (r *sgmlRenderer) renderStringElement(ctx *context, str *types.StringElement) (string, error) {
// NB: For all SGML flavors we are aware of, the numeric entities from
// Unicode are supported. We generally ... |
/*
MIT License
Copyright (c) 2020-2021 Kazuhito Suda
This file is part of NGSI Go
https://github.com/lets-fiware/ngsi-go
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, inc... |
package checkstyle
import (
"bytes"
"encoding/json"
"go/ast"
"go/format"
"go/parser"
"go/token"
"strconv"
"strings"
)
type ProblemType string
const (
FileLine ProblemType = "file_line"
FunctionLine ProblemType = "func_line"
ParamsNum ProblemType = "params_num"
ResultsNum ProblemType = "results_n... |
package marathon
import (
"encoding/json"
"github.com/stretchr/testify/require"
"github.com/wndhydrnt/proxym/types"
"log"
"net/http"
"net/http/httptest"
"testing"
)
func TestServicesFromMarathon(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Met... |
package entity
import (
"net"
"time"
)
type Traffic struct {
Inbound bool
Date time.Time
ProcessName string
Hostname string
SourceIP net.IP
SourcePort int
TargetIp net.IP
TargetPort int
PacketsCnt uint
Size uint
}
|
package file_test
import (
"os"
"testing"
"github.com/matthew-burr/db/file"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func SetupFileTestDat() (*file.DBFile, func()) {
filepath := "file_test.dat"
d := file.Open(filepath)
return d, func() { d.File.Close(); os.Remove(filepath)... |
package persistence
import (
"database/sql"
"fmt"
"log"
"strings"
"github.com/desafios-job/import-data/domain/entity"
)
// InconsistencyRepo struct
type InconsistencyRepo struct {
db *sql.DB
}
// NewInconsistencyRepository new repository
func NewInconsistencyRepository(db *sql.DB) *InconsistencyRepo {
return... |
package main
import (
"fmt"
"testing"
)
func TestgetGreeting(t *testing.T) {
name := "Ted"
greeting := getGreeting(name)
fmt.Println(greeting)
if greeting != "" {
t.Errorf("log output should match %q is %q", pattern, line)
}
}
|
package main
import (
"fmt"
"math/rand"
"net"
"time"
)
var serverList []string
func main() {
conn, err := GetConnect()
if err != nil {
fmt.Printf(" connect zk error: %s \n ", err)
return
}
defer conn.Close()
serverList, err = GetServerList(conn)
if err != nil {
fmt.Printf(" get server list error: %s ... |
package unimatrix
import (
"encoding/json"
"fmt"
"strconv"
)
type Parser struct {
Name string
TypeName string
Keys []string
Resources []Resource
Count int
UnlimitedCount int
Offset int
}
type JsonResponse map[string]*json.RawMessage
type StaticResponse struc... |
package usecase
import (
"errors"
"fmt"
"log"
"os"
"strings"
"text/tabwriter"
"time"
"github.com/maestre3d/bob/common/util"
"github.com/maestre3d/bob/entity"
)
// GenerateService Create a new service
func GenerateService(name, appName, description string) error {
// Verify if not exists then insert
app :=... |
package host
import (
"io"
"os"
)
// RestoreFile overwrite content of a hosts file with the content of a backup.
func RestoreFile(src, dst string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
return err
}
defer ds... |
package common
import (
"errors"
"fmt"
"github.com/go-ini/ini"
"github.com/speedata/gogit"
"os"
"path"
"regexp"
)
func findGitRevision(file string) (string, error) {
gitDir, err := findGitDirectory(file)
if err != nil {
return "", err
}
log.Debugf("Loading revision from git directory '%s'", gitDir)
rep... |
package server
import (
"fmt"
"net/http"
"time"
"github.com/izikaj/iziproxy/shared"
)
type waitForResponseParams struct {
core *Server
req *shared.Request
signal *CodeSignal
w *http.ResponseWriter
timeout time.Duration
}
func (server *commonWebHelpers) waitForResponse(params waitForResponsePa... |
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package main
import (
"bufio"
"fmt"
"io"
"math"
"os"
"strconv"
"strings"
)
func pthFactor(n int64, p int64) int64 {
var arr []int64
var brr []int64
var i, j int64
k := p - 1
for i = 1; i <= int64(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
arr = append(arr, i)
if n/i != i {
brr = append(brr, n... |
package main
import (
"fmt"
"github.com/mdegaris/go-learning/factorial"
"github.com/mdegaris/go-learning/greeting"
"github.com/mdegaris/go-learning/primes"
)
func main() {
greeting.Greet(greeting.ENGLISH)
greeting.Greet(greeting.FRENCH)
greeting.Greet(greeting.SPANISH)
p := 300
f := 7
fmt.Println("Primes ... |
package progress
import "os"
// progressLogger provides a wrapper around an os.File that can either
// write to the file or ignore all writes completely.
type progressLogger struct {
writeData bool
log *os.File
}
// Write will write to the file and perform a Sync() if writing succeeds.
func (l *progressLogge... |
package ui
import (
"github.com/galaco/lambda-client/engine"
vguiCore "github.com/galaco/lambda-core/loader/vgui"
"github.com/galaco/lambda-core/vgui"
"github.com/galaco/tinygametools"
"github.com/galaco/filesystem"
)
type Gui struct {
engine.Manager
window *tinygametools.Window
masterPanel vgui.MasterPa... |
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func main() {
runtime.GOMAXPROCS(1)
wg := sync.WaitGroup{}
wg.Add(20)
for i := 0; i < 10; i++ {
go func() {
fmt.Println("first i: ", i)
wg.Done()
}()
for j := 0; j < 10000; j++ {
fmt.Println("first sleep")
}
//time.Sleep(time.Microsecond... |
package tree
import "fmt"
type treeNode struct {
val int
leftNode *treeNode
rightNode *treeNode
}
// Preorder 树 前序遍历 根-左-右
func Preorder(root *treeNode) {
if root != nil {
fmt.Println(root.val)
Preorder(root.leftNode)
Preorder(root.rightNode)
}
}
// Middleorder 中序遍历 左-根-右
func Middleorder(root *tr... |
package lc
// Time: O(n log log n)
// Benchmark: 8ms 4.9mb | 95% 83%
func countPrimes(n int) int {
if n <= 2 {
return 0
}
sieve := make([]byte, n+1)
count := 1
for i := 3; i < n; i += 2 {
if sieve[i] == 1 {
continue
}
for j := 2 * i; j < n; j += i {
sieve[j] = 1
}
count++
}
return count
... |
/*
This is an example application to demonstrate parsing an ID Token.
*/
package main
import (
"Charles/charles-email-test/services"
"net/http"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/cors"
)
func main() {
router := mux.NewRouter()
router.Handle("/metrics", p... |
//
// Package tcx reads garmin XML format files (.tcx file extension) and converts
// them into .fit format Go structures.
//
package tcx
import (
"fmt"
"github.com/jezard/fit"
"math"
"time"
)
// DeviceInfo converts GPS device information from the TCXDB structure to
// strings.
func DeviceInfo(db *TCXDB) (DevNam... |
package arithmetic
import (
"fmt"
)
func ExampleRegisterVariable() {
// Register a new variable.
RegisterVariable("dayInYear", 365)
v, err := Parse("dayInYear * 2")
if err != nil {
// ...
}
fmt.Println(v)
// Output: 730
}
|
package main
import (
"fmt"
"strings"
"testing"
)
func TestHighestScore(t *testing.T) {
for k, v := range map[string]string{
"72 64 150 | 100 18 33 | 13 250 -6": "100 250 150",
"10 25 -30 44 | 5 16 70 8 | 13 1 31 12": "13 25 70 44",
"100 6 300 20 10 | 5 200 6 9 500 | 1 10 3 400 143... |
package rego
// HaltError is an error type to return from a custom function implementation
// that will abort the evaluation process (analogous to topdown.Halt).
type HaltError struct {
err error
}
// Error delegates to the wrapped error
func (h *HaltError) Error() string {
return h.err.Error()
}
// NewHaltError w... |
package psql
import (
"context"
storage "github.com/adhistria/auth-movie-app/infrastructure/storage"
"github.com/adhistria/auth-movie-app/internal/domain"
log "github.com/sirupsen/logrus"
)
// UserRepository represent user psql
type userRepository struct {
DB *storage.Database
}
// Create add new user to datab... |
package main
// Version is lltsv version string
const Version string = "0.7.0"
|
package renter
import (
"errors"
"sync/atomic"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/modules"
"github.com/NebulousLabs/Sia/types"
)
var (
ErrUnknownNickname = errors.New("no file known by that nickname")
ErrNicknameOverload = errors.New("a file with the proposed nickname already e... |
package exec
import (
"bufio"
"fmt"
"os"
"github.com/aergoio/aergo/cmd/brick/context"
"github.com/mattn/go-colorable"
)
func init() {
registerExec(&batch{})
}
type batch struct{}
func (c *batch) Command() string {
return "batch"
}
func (c *batch) Syntax() string {
return fmt.Sprintf("%s", context.PathSymb... |
package pando
import (
"encoding/json"
"fmt"
"github.com/agiledragon/gomonkey/v2"
"github.com/gin-gonic/gin"
"github.com/kenlabs/pando/pkg/api/types"
"github.com/kenlabs/pando/pkg/api/v1/model"
. "github.com/smartystreets/goconvey/convey"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
fu... |
package main
import (
"github.com/bengtrj/cfcr-cluster-diagram/infra-diagram/generator/deployment"
"github.com/bengtrj/cfcr-cluster-diagram/infra-diagram/generator"
"os"
)
func main() {
deployment, err := deployment.Load("/Users/bengthammarlund/go/src/github.com/bengtrj/cfcr-cluster-diagram/infra-diagram/fixtu... |
package memjudge
import (
"encoding/json"
"fmt"
"github.com/RemmargorP/memjudge/judge"
"github.com/RemmargorP/memjudge/web"
"gopkg.in/mgo.v2"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/http/httputil"
"net/url"
"os"
"runtime"
"strconv"
"time"
)
const MasterPort = ":45100"
const WebPort = ":8080"
typ... |
package humanize
import (
"go/ast"
"go/token"
)
var (
lastConst Type
)
// Constant is a string represent of a function parameter
type Constant struct {
Name string
Type Type
Docs Docs
Value string
caller *ast.CallExpr
indx int
}
func constantFromValue(name string, indx int, e []ast.Expr, src string, ... |
package types
import (
"github.com/hyperhq/hyper/lib/docker/cliconfig"
)
type ImagePushConfig struct {
MetaHeaders map[string][]string
AuthConfig *cliconfig.AuthConfig
Tag string
}
type ImagePullConfig struct {
MetaHeaders map[string][]string
AuthConfig *cliconfig.AuthConfig
}
|
/**
* Copyright 2017 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... |
package main
import (
"bufio"
"fmt"
"log"
"net"
"strings"
)
func request(c net.Conn) string {
rd := bufio.NewScanner(c)
i := 0
var uri string
for rd.Scan() {
line := rd.Text()
fmt.Println(line)
if i == 0 {
uri = strings.Fields(line)[1]
fmt.Println("***URI IS", uri)
}
if line == "" {
break
... |
package main
type person struct {
first string
last string
location string
}
func main() {
}
|
package main
import "fmt"
func main() {
fmt.Println(greeting("Lukas"))
fmt.Println(getSum(56, 102))
}
func greeting(name string) string { //func name(arg type) return-type
return "Hello, " + name
}
func getSum(num1, num2 int) int {
return num1 + num2
}
|
// Copyright 2020 Tim Shannon. All rights reserved.
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.
package reflex
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"reflect"
"reflex/client"
"github.com/gorilla/webs... |
/**
括号匹配
查看左右括号是否匹配
假设只存在这[{(三种括号,并且只可能有一共六种字符可能
1. 如果是左半边,直接进栈
2. 如果是右半边,先比较栈顶是不是和其对应的左半边,不是则不匹配
*/
package stack
var (
leftHalf = map[string]struct{}{
"(": struct{}{},
"[": struct{}{},
"{": struct{}{},
}
rightToLeft = map[string]string{
")": "(",
"]": "[",
"}": "{",
}
)
type Parentheses struct {
*... |
package tests
import (
"testing"
)
/**
* [745] Find Smallest Letter Greater Than Target
*
*
* Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target.
*
* Letters also wrap around. ... |
package main
import (
"reflect"
"testing"
)
var splitargtest = []struct {
in string
out []string
}{
{"", nil},
{" ", nil},
{" ", nil},
{"x", []string{"x"}},
{"x x", []string{"x", "x"}},
{"'x' 'x'", []string{"x", "x"}},
{"'x' 'x'", []string{"x", "x"}},
{"' x ' 'x'", []string{" x ", "x"}},
{" ' x ' 'x'"... |
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package inputs
import (
"context"
"strings"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/bundles/cros/inputs/fixture"
"chromiumos... |
// Copyright 2018 The go-Dacchain Authors
// This file is part of the go-Dacchain library.
//
// The go-Dacchain library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License... |
// Copyright 2020 Adobe. All rights reserved.
// This file is licensed to you 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 applicab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.