text stringlengths 11 4.05M |
|---|
// Copyright (C) 2019 Google 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 lmq
// Queue manages topics
type Queue interface {
Option() *Options
OpenTopic(topic, groupID string, flag int) Topic
PutMessages(topic Topic, msgs []*Message)
ReadMessages(topic Topic, groupID string, msgs chan<- *[]byte)
Stat(topic Topic) *TopicStat
CloseTopic(topic Topic)
Close()
}
type queue struct... |
package steps_test
import (
"os"
"testing"
"github.com/joshuacrass/online-upgrade/steps"
"github.com/joshuacrass/online-upgrade/testutil"
"github.com/joshuacrass/online-upgrade/util"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
versionHash = os.Getenv("MEMSQL_VERSION_5_7... |
package utils
import "time"
type Comparator func(a,b interface{}) int
//两个字符串比较大小的方式是比较其中字符转为数字的差的累加
func StringComparator(a,b interface{}) int{
s1:=a.(string)
s2:=b.(string)
min:=len(s2)
if len(s1)<len(s2){
min=len(s1)
}
diff:=0
for i:=0;i<min;i++{
diff+=int(s1[i])-int(s2[i])
}
if diff==0{
diff=len(s... |
package model
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"rain/library/format"
"rain/library/go-str"
"rain/library/helper"
resp "rain/library/response"
"time"
)
type Bookmark struct{
BaseModel
Name string `gorm:"comment: '名称'" json:"name"`
Url string `gorm:"comment: '书签url'" json:"url... |
// Package workerpool provides a basic pool of goroutine workers
// that can execute an arbitrary simple function of the type func(). The
// pool can be used to perform tasks that may block for an indeterminate
// amount of time such as writing data to a network connection, sending on
// a channel which is only servic... |
package server
import "fmt"
type Word struct {
Ori []rune
Ops []*WordOpAtom
}
type WordOp int
const (
PrefixRs WordOp = iota
SuffixRs
HeadTrimRs
TailTrimRs
MidRmRs
MidInsertRs
)
type WordOpAtom struct {
op WordOp
position int
opNum int
runes []rune
}
// analyzation
func (word *Word) Analiz... |
// Copyright 2014-2017 The Zurichess 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 engine
import (
. "bitbucket.org/zurichess/board"
)
func groupByCount(feature featureType, n int32, accum *Accum) {
start := getFeatureS... |
package server
import (
"fmt"
"os"
"syscall"
)
func Interrupt() error {
if proc, err := os.FindProcess(os.Getpid()); err != nil {
return fmt.Errorf("get current process: %w", err)
} else if err = proc.Signal(syscall.SIGINT); err != nil {
return fmt.Errorf("send SIGINT to current process: %w", err)
} else {
... |
package typedkey
import (
"bytes"
"encoding/binary"
"errors"
"sync"
"github.com/iotaledger/hive.go/kvstore"
)
type GenericType[T any] struct {
store kvstore.KVStore
key []byte
value T
mutex sync.RWMutex
}
func NewGenericType[T any](store kvstore.KVStore, keyBytes ...byte) (newGenericType *GenericType[T])... |
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
)
func manifestToolPushFromSpec(yamlSpec string) error {
yamlFile, err := ioutil.TempFile("", "bashbrew-manifest-tool-yaml-")
if err != nil {
return err
}
defer os.Remove(yamlFile.Name())
if _, err := yamlFile.Write([]byte(yamlSpec)); err != nil {
r... |
package models
type Health struct {
Service string `json:"service"`
Environment string `json:"environment"`
Status int `json:"status"`
}
|
package advSysUtil
//longzhang.li add 2018.11.14
import (
"encoding/json"
"fmt"
"os"
)
func GetAppEnv(key string) (string, error) {
var dat map[string]interface{}
jsonStr := os.Getenv("VCAP_APPLICATION")
fmt.Printf("----------\r\nget application_env_json is:%s\r\n", jsonStr)
err := json.Unmarshal([]byte(jsonSt... |
/*
Copyright 2021 The KodeRover 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, s... |
package routes
import (
"database/sql"
"github.com/gofiber/fiber/v2"
"github.com/louissaadgo/ecom-backend/database"
"github.com/louissaadgo/ecom-backend/middlewares"
)
func user(c *fiber.Ctx) error {
cookie := c.Cookies("JWT")
if cookie == "" {
return fiber.NewError(400, "User Not Authenticated")
}
id, ... |
// Copyright 2020 The VectorSQL Authors.
//
// Code is licensed under Apache License, Version 2.0.
package datatypes
import (
"base/binary"
"base/errors"
"datavalues"
"io"
)
type IDataType interface {
Name() string
Serialize(*binary.Writer, datavalues.IDataValue) error
SerializeText(io.Writer, datavalues.IDat... |
package filters
import "fmt"
//
// A base ffmpeg filter (Volume and Speed already included)
// anything can be given to this and will be formatted to
// ffmpeg as `name=k1=v1:k2=v2`
type Filter struct {
Name string `json:"filter_name"`
Values map[string]string `json:"filter_values"`
}
func (f *Filter... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package arc
import (
"context"
"sort"
"time"
"chromiumos/tast/common/perf"
"chromiumos/tast/local/memory"
"chromiumos/tast/local/resourced"
"chromiumos/tast/testing"... |
package controllers
import (
"database/sql"
"github.com/astaxie/beego"
"homework/models/datamodels"
"strconv"
)
type SeckillController struct {
beego.Controller
MySqlConn *sql.DB
}
func (this *SeckillController) Kill() {
productstring := this.GetString("productid")
uidstring := this.Ctx.GetCookie("uid")
pr... |
package main
func main() {
}
//接雨水
/***
* 思路 1、i点的可存水量为 左右最矮高度 减去当前高度
* min(max(height[:i+1]...), max(height[i:])) - height[i]
* 2、关键点在找到左右最大高度
*/
func bigger(a, b int) int {
if a > b {
return a
}
return b
}
func smaller(a, b int) int {
if a < b {
return a
}
return b
}
func trap(height []int) int ... |
package dao
import (
"fmt"
"github.com/yuwe1/pgim/internal/model"
"github.com/yuwe1/pgim/pkg/client/dbpool"
"github.com/yuwe1/pgim/pkg/logger"
)
type messageDao struct {
}
var MessageDao = new(messageDao)
// 插入一条消息
func (*messageDao) Add(tableName string, message model.Message) error {
session, err, p, c := d... |
package plugins
import (
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/runtime"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/api/core/v1"
"transwarp/isomateset-client/pkg/apis/apiextensions.transwarp.io/v1alpha1"
)
func Test_ConvertStsToIsomateSet(... |
package controllers
import (
"errors"
"net/http"
"strconv"
"github.com/go-react/community/logs"
"github.com/astaxie/beego"
)
// BaseController 提供基础的控制器处理
type BaseController struct {
beego.Controller
}
// ResData 数据响应输出
func (bc *BaseController) ResData(v interface{}) {
bc.Ctx.Input.SetData("data", v)
}
//... |
package cldr
import (
"encoding/xml"
"fmt"
"reflect"
"strings"
"testing"
)
func TestPluralsDecode(t *testing.T) {
const xmlData = `<?xml version="1.0" encoding="UTF-8" ?>
<root>
<plurals type="cardinal">
<pluralRules locales="bm bo dz id">
<pluralRule count="other"> @integer 0~15, 100, 1000, 10000, 10... |
package main
import (
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"time"
)
type Myclaims struct {
UserId int
Username string
jwt.StandardClaims
}
func main() {
mySigningKey := []byte("hzwy23")
// Create the Claims
claims := Myclaims{
1,
"wjf",
jwt.StandardClaims{
IssuedAt: int64(time.Now().Unix()),
... |
package main
import (
"reflect"
"net/rpc"
"fmt"
"net"
"encoding/json"
"sync"
"time"
"github.com/pkg/errors"
"math/rand"
"log"
)
//定义传输数据格式
type User struct {
Name string
Age int
}
//定义rpc调用接口,通过tag定义接口中函数对应的远程服务名
type HelleServiceInterface struct {
Hello func(int, *int) string `service:"HelleServ... |
package auth
import (
"context"
"net/http"
)
type contextKey int
const (
contextKeySubject contextKey = iota
)
type Subject struct {
Name string
Groups []string
}
func GetSubject(r *http.Request) *Subject {
rawSub := r.Context().Value(contextKeySubject)
if rawSub == nil {
return nil
}
sub, ok := rawS... |
package payment
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/xml"
"fmt"
"github.com/pkg/errors"
"io/ioutil"
"net/http"
"sort"
"strings"
"time"
)
const (
appId = ""
mch_id = ""
apiKey = ""
ip = ""
notify_url = ""
out_trade_no = ""
)
// 测试样例
func TestPayment() {
// 创建实例并初始化
o := &RequestUn... |
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestValidCidrToMask(t *testing.T) {
assert := assert.New(t)
assert.Equal("128.0.0.0", cidrToMask("1"))
assert.Equal("255.255.0.0", cidrToMask("16"))
assert.Equal("255.255.248.0", cidrToMask("21"))
assert.Equal("255.255.255.255", cidr... |
package log
import (
"fmt"
"github.com/golang/glog"
)
const (
debug glog.Level = glog.Level(4)
trace glog.Level = glog.Level(5)
)
func Info(args ...interface{}) {
glog.InfoDepth(1, args...)
}
func Infof(format string, args ...interface{}) {
glog.InfoDepth(1, fmt.Sprintf(format, args...))
}
func Warning(args... |
// Copyright 2017 The Go 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 cfg holds configuration shared by multiple parts
// of the go command.
package cfg
import (
"os"
"path/filepath"
"runtime"
"github.com/gernest/... |
package test
import (
"github.com/orbs-network/orbs-network-javascript-plugin/test"
. "github.com/orbs-network/orbs-network-javascript-plugin/worker"
"github.com/stretchr/testify/require"
"testing"
)
func TestNewV8Worker_Address(t *testing.T) {
sdkHandler := test.AFakeSdkFor([]byte("signer"), []byte("caller"))
... |
// Deadlock, page 10
package main
import (
"fmt"
"sync"
"time"
)
type value struct {
value int
lock sync.Mutex
}
func main() {
var wg sync.WaitGroup
printSum := func(a, b *value) {
defer wg.Done()
a.lock.Lock()
defer a.lock.Unlock()
time.Sleep(2 * time.Second)
b.lock.Lock()
defer b.lock.Unlock()... |
package snaketask
import (
"math/rand"
"github.com/JoelOtter/termloop"
)
type Food struct {
*termloop.Entity
coord coordinate
}
func newFood() *Food {
f := new(Food)
f.Entity = termloop.NewEntity(1, 1, 1, 1)
f.shiftToNewPosition()
return f
}
func (f *Food) Draw(screen *termloop.Screen) {
if f == nil {
... |
package runtime
// Function calls are emitted as deferred procedures
type TailCall interface {
// Resolve the tail call to its value
Return() (Value, error)
}
|
package db
import (
"database/sql"
"fmt"
)
// SQLWordRepo finds words if they exist
type SQLWordRepo struct {
ConnString string
}
// Search finds a word if it exists
func (wr SQLWordRepo) Search(prefix string, limit int) ([]string, error) {
sql, err := sql.Open("mysql", wr.ConnString)
if err != nil {
return ... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"log"
"math"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/getsentry/sentry-sdk-benchmark/internal/plot"
"github.com/getsentry/sentry-sdk-benchmark/internal/std/browser"
vegeta "github.com/tsenart/vegeta/v12/lib"
)
var sdk... |
package ast
import (
"reflect"
"testing"
"github.com/lavaorg/telex/internal/glob/syntax/lexer"
)
type stubLexer struct {
tokens []lexer.Token
pos int
}
func (s *stubLexer) Next() (ret lexer.Token) {
if s.pos == len(s.tokens) {
return lexer.Token{Type:lexer.EOF, Raw:""}
}
ret = s.tokens[s.pos]
s.pos++
... |
package provider
import (
"github.com/GehirnInc/GOpenID"
"net/url"
)
type Response interface {
NeedsRedirect() bool
IsPermanently() bool
GetRedirectTo() string
GetBody() []byte
GetContentType() string
}
type OpenIDResponse struct {
request Request
message gopenid.Message
needsRedirect bool
isP... |
/*
* @lc app=leetcode.cn id=2225 lang=golang
*
* [2225] 找出输掉零场或一场比赛的玩家
*/
package leetcode
import "sort"
// @lc code=start
func findWinners(matches [][]int) [][]int {
answer := make([][]int, 2)
winMap := make(map[int]int)
loserMap := make(map[int]int)
for _, v := range matches {
winMap[v[0]]+... |
package db
import (
"database/sql"
"reflect"
"regexp"
"strings"
"time"
_ "github.com/lib/pq"
"github.com/dgonyeo/brandreth2.0/config"
)
var setupTables = `
BEGIN;
drop table if exists entries;
drop table if exists people;
create table people (
user_id TEXT NOT NULL,
name TEXT NOT... |
package role
import (
"fmt"
"sync"
"github.com/corioders/gokit/errors"
)
var roleManagers = &sync.Map{}
type RoleManager struct {
name string
roles *sync.Map
permissions *sync.Map
}
var (
ErrRoleManagerNonUnique = errors.New("Role manager name must be unique")
ErrRoleNameNonUnique = errors.... |
// 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 verificator
import (
"regexp"
)
// Event verificator.
type Event struct {
r *regexp.Regexp
}
// NewEvent ...
func NewEvent(
layout string,
) (v *Event, err error) {
r, err := regexp.Compile(layout)
if err != nil {
return
}
v = &Event{
r: r,
}
return
}
func (e *Event) Type(t string) bool {
retu... |
// date: 2019-03-13
package server
import (
"fmt"
"github.com/Jarvens/Exchange-Agent/api"
"github.com/Jarvens/Exchange-Agent/config"
"github.com/Jarvens/Exchange-Agent/util/log"
"github.com/gin-gonic/gin"
)
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Con... |
package data
import (
"context"
"fmt"
"html/template"
"net/http"
"github.com/movsb/taoblog/config"
"github.com/movsb/taoblog/modules/auth"
"github.com/movsb/taoblog/protocols"
"github.com/movsb/taoblog/service"
)
// SearchData ...
type SearchData struct {
Posts []*SearchPost
}
type SearchPost struct {
p *... |
/*
Copyright 2020 KubeSphere Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... |
package main
import "fmt"
import "math"
type Rectangle struct{
x1, y1, x2, y2 float64
}
func distance(x1, y1, x2, y2 float64) float64 {
a:=x2-x1
b:=y2-y1
return math.Sqrt(a*a + b*b)
}
func (r *Rectangle) area() float64{
l:= distance(r.x1, r.y1, r.x1, r.y2)
w:= distance(r.x1, r.y1, r.x2, r.y1)
return l*... |
package main
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"runtime"
// "io/ioutil"
"log"
"os"
"time"
"example.com/signal"
"github.com/pion/webrtc/v3"
"github.com/pion/webrtc/v3/pkg/media"
"github.com/pion/webrtc/v3/pkg/media/h264reader"
)
func main() {
// Create a new RTCPeerConnection
peerConnecti... |
/*
Copyright 2021 The KodeRover 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, s... |
package lc
// Time: O(n^2)
// Benchmark: 0ms 2mb | 100%
func combinationSum3(k int, n int) [][]int {
var rc func(nums []int, start int, target int, valid *[][]int)
rc = func(nums []int, start int, target int, valid *[][]int) {
if len(nums) == k {
if target == 0 {
*valid = append(*valid, append([]int{}, num... |
package apiParser
import "net/http"
type ParserClient struct {
client *http.Client
}
func CreateParserClient(httpClient *http.Client) *ParserClient {
return &ParserClient{client: httpClient}
}
|
package main
import (
"flag"
"os"
"path"
)
type option struct {
Port string
Remote string
Dir string
Fetch string
Connect string
}
func (self *option) parse() {
flag.StringVar(&self.Port, "port", "1984", "listening on http://localhost:<port>")
flag.StringVar(&self.Remote, "remote", "http://127.0.... |
package main
import (
"fmt"
"unsafe"
)
type myStruct struct {
field int
}
type point struct {
x, y int
}
func main() {
var v int32 = 100
var pointer *int32 = &v
fmt.Println("ポインタの値: ", pointer)
fmt.Println("関節演算子の結果: ", *pointer)
v = 200
fmt.Println("変数vの更新: ", *pointer)
*pointer = 300
fmt.Println("ポ... |
package algorithm
import "strings"
func RomanToInt(s string) int {
result := 0
single := map[string]int{"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
mix := map[string]int{"IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900}
for k, v := range mix {
if strings.Contains(s, k) {
res... |
package thought
import (
"fmt"
"testing"
"time"
)
func newFactor(id string) *factor {
return &factor{
id: id,
status: FactorPendingStatus,
startTime: time.Now(),
}
}
func TestFactor_String(t *testing.T) {
f := factor{
id: "1",
refs: []*factor{
{id: "0", startTime: time.Now()},
},
sta... |
package main
import (
"context"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"os"
"time"
"github.com/adelplace/snippetbox/pkg/models/persistence"
"github.com/mongodb/mongo-go-driver/mongo"
"github.com/mongodb/mongo-go-driver/mongo/readpref"
)
type application struct {
errorLog *log.Logger
infoLog... |
package main
import (
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"os"
"strings"
"text/template"
)
// код писать тут
type HandlerInfo struct {
URL string
Auth bool
Method string
}
type Handler struct {
HandlerMethod string
HandlerInfo
ParamIn string
ResultOut string
R... |
package ipaccess
import (
"fmt"
"net"
"sort"
)
type Policy struct {
defaultAllow bool
rules []Rule
}
type Rule struct {
ipNet *net.IPNet
ports []int
allow bool
}
func NewPolicy(defaultAllow bool, rules []Rule) (*Policy, error) {
for _, rule := range rules {
if err := rule.Validate(); err != nil {
... |
package gcp
import (
"context"
"fmt"
"net/url"
admin "cloud.google.com/go/iam/admin/apiv1"
adminpb "google.golang.org/genproto/googleapis/iam/admin/v1"
crm "google.golang.org/api/cloudresourcemanager/v1"
gke "google.golang.org/api/container/v1"
)
type Agent struct {
Ctx context.Context
ProjectID stri... |
package api
import "github.com/edznux/wonderxss/storage"
var store storage.Storage
func Init() {
store = storage.GetDB()
}
|
/*
* @File: models.message.go
* @Description: Defines Message information will be returned to the clients
* @Author: Nguyen Truong Duong (seedotech@gmail.com)
*/
package interfaces
// Message defines the response message
type Response struct {
Data Message `json:"data"`
}
type Message struct {
Message string `j... |
package main
import (
"fmt"
"time"
)
func main() {
// if condition
num := 1
if num == 1 {
fmt.Println("One")
} else if num == 2{
fmt.Println("Two")
} else {
fmt.Println("None")
}
// switch case
num2 := 2
switch num2 {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
default:
fmt... |
package migrations
import (
"context"
"errors"
"testing"
"github.com/golang/mock/gomock"
_ "github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type runnerObjs struct {
runner *Runner
source *MockSource
target *MockTarget
ctrl *gomock.Controller
}
f... |
// Copyright 2018 Saferwall. All rights reserved.
// Use of this source code is governed by Apache v2 license
// license that can be found in the LICENSE file.
package constants
// Version indicates the current version of the application.
const (
Version = "0.5.0"
)
|
// +build !windows
package workspace
import (
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
)
func TestLocateSymlinks(t *testing.T) {
_, cwd, _, _ := runtime.Caller(0)
root := filepath.Join(cwd, "..", "..", "fixtures", "locate-exercise")
wsSymbolic, err := New(filepath.Join(root, ... |
// Copyright (C) 2017 Google 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 coordinator
import (
"github.com/streadway/amqp"
"github.com/eugenebad/ticker/qutils"
"time"
"bytes"
"github.com/eugenebad/ticker/dto"
"encoding/gob"
)
const maxRate = 5 * time.Second
type DatabaseConsumer struct{
er EventRaiser
conn *amqp.Connection
ch *amqp.Channel
queue *amqp.Queue
sources []stri... |
package fetcher
import (
"bufio"
"fmt"
"golang.org/x/net/html/charset"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
"io/ioutil"
"log"
"net/http"
"time"
"zhenai-crawler/crawler/common/reporter"
)
const UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... |
package main
import (
"fmt"
)
func minWindow(s string, t string) string {
ls := len(s)
lt := len(t)
i := 0
j := 0
k := -1
for i < ls {
if k < 0 && s[i]==t[j] {
k = i
}
if s[i]==t[j] {
// fmt.Println(i,j)
if j == lt-1 {
... |
// Package jirams is Jira adapter microservice
package jirams
|
package exports
type Employee struct {
Managed map[string]*Employee `json:"manages"`
}
// HierarchyInfo - generated API structure
type HierarchyInfo struct {
CEO *Employee `json:"CEO"`
}
|
package resource
import (
"github.com/pressly/chi"
"net/http"
"golang.org/x/oauth2"
"github.com/google/go-github/github"
"log"
"github.com/dgrijalva/jwt-go"
"github.com/alioygur/gores"
"env"
)
type AuthResource struct {
env *env.Env
}
func NewAuthResource(env *env.Env) *AuthResource {
return &AuthResource... |
package adasync
import (
"testing"
)
func TestHashFromBytes(t *testing.T) {
hash := HashFromBytes([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})
if hash.String() != "AQIDBAUGBwgJCgsMDQ4PEA==" {
t.Error("Incorrect hash string")
}
}
func TestEqual(t *testing.T) {
tests := []struct {
a, b *Ha... |
package main
import (
"encoding/json"
"net/http"
)
//WebResponse is response object
type WebResponse struct {
Message string `json:message`
}
func writeErrorMsg(w http.ResponseWriter, msg string) {
w.WriteHeader(404)
writeJSONResponse(w, WebResponse{msg})
}
func writeJSONResponse(w http.ResponseWriter, obj int... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package policy
import (
"context"
"encoding/json"
"time"
"github.com/golang/protobuf/ptypes/empty"
"chromiumos/tast/common/policy"
"chromiumos/tast/ctxutil"
"chromi... |
package main
import (
"github.com/csmith/aoc-2020/common"
)
// This file contains four different implementations of the same algorithm with different backing data structures:
// A map, a map initialised with a large capacity, a fixed-size array of ints, and a fixed-size array of int32s.
//
// Benchmark results:
//
/... |
package tests
import (
"testing"
)
/**
* [20] Valid Parentheses
*
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
*
* An input string is valid if:
*
*
* Open brackets must be closed by the same type of brackets.
* Open brackets must ... |
package lumps
import (
"bytes"
"encoding/binary"
primitives "github.com/galaco/bsp/primitives/cubemap"
"log"
"unsafe"
)
/**
Lump 42: Cubemaps
*/
type Cubemap struct {
LumpGeneric
data []primitives.CubemapSample
}
func (lump *Cubemap) FromBytes(raw []byte, length int32) {
lump.LumpInfo.SetLength(length)
if l... |
package git
import (
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestRepoBasic(t *testing.T) {
const path = "test.git"
repo, err := InitBareRepository(path)
if err != nil {
t.Fatalf("Creating repo failed with err: %v", err)
}
if !strings.HasSuffix(repo.Path, path) {
t.Fatalf("Expected to see ... |
package local
import (
"fmt"
"github.com/jdcloud-serverless/sca/common/template"
"testing"
)
func TestExecute(t *testing.T) {
envs := make(map[string]string)
envs["key1"] = "value1"
properties := template.FunctionProperties{
Name: "test-function",
Handler: "index.handler",
Timeout: 100,
... |
package main
import (
"fmt"
)
func main() {
var myArray [10]int = [10]int{1, 2, 34, 5, 6, 7, 7}
var mySlice []int = myArray[:5]
mySlice2 := make([]int, 4, 5)
fmt.Println("asdf")
for i := 0; i < len(mySlice); i++ {
fmt.Println(mySlice[i])
}
for _, v := range mySlice {
fmt.Println(v)
}
mySlice2 = append(... |
package main
import (
"container/heap"
"github.com/kr/pretty"
)
type State struct {
s string
cnt int
}
type StateHeap []*State
func (h StateHeap) Len() int {
return len(h)
}
func (h StateHeap) Less(i, j int) bool {
if h[i].cnt == h[j].cnt {
return h[i].s < h[j].s
}
return h[i].cnt... |
package main
// Leetcode 305. (hard)
func numIslands2(m int, n int, positions [][]int) (res []int) {
root := make([]int, m*n)
for i := range root {
root[i] = i
}
direction := [4][2]int{[2]int{0, 1}, [2]int{1, 0}, [2]int{0, -1}, [2]int{-1, 0}}
delta := [2]int{n, 1}
cnt := 0
visited := make([]bool, m*n)
for _... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
checks := []string{}
testUrls := []string{
"http://localhost:8080/api/auctions",
"http://localhost:8080/api/auction",
"http://localhost:8080/api/user",
"http://localhost:8080/api/user/login",
}
runTestR(testUrls, &checks)
fmt.Printf(... |
package leetcode_0070_爬楼梯
/*
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
*/
/*
如果一个问题的最优解包含了其中子问题的最优解,那么称其具有最优子结构的性质。
什么意思?青蛙在面对 n 个台阶时的解决方案数是 f... |
package main
import "fmt"
func main() {
x := 15
y := 10
if x < y {
fmt.Printf("%d is less than %d\n", x, y)
} else {
fmt.Printf("%d is less than %d\n", y, x)
}
for i := 0; i < 100; i++ {
if i%3 < 1 && i%5 < 1 {
fmt.Println("fizzbuzz")
} else if i%3 < 1 {
fmt.Println("fizz")
} else if i%5 < 1 {... |
package rankservice
import (
"errors"
"fmt"
"log"
"math"
"puck-server/db-server/user"
"sort"
"time"
)
const (
RANKEMPTY = "rank empty"
RANKSINGLEENTRY = "rank single entry"
)
// GetRankZeroBasedDesc returns Rank for given score.
// descArr is the previous score array which should be sorted in
// desce... |
package cherryMessage
import (
"fmt"
"strings"
)
// message协议的主要作用是封装消息头,包括route和消息类型两部分,
// 不同的消息类型有着不同的消息头,在消息头里面可能要打入message id(即requestId)和route信息。
// 由于可能会有route压缩,而且对于服务端push的消息,message id为空,对于客户端请求的响应,route为空
// 消息头分为三部分,flag,message id,route。
//如下所示:
// flag(1byte) + message id(0~5byte) + route(0~256bytes)
... |
package models
import "github.com/astaxie/beego/orm"
type FaqCategory struct {
Id uint32
}
func (m *FaqCategory) TableName() string {
return "faq_categories"
}
func (m *FaqCategory) Query() orm.QuerySeter{
return orm.NewOrm().QueryTable(m)
}
func (m *FaqCategory) Insert() error{
if _,err:=orm.NewOrm().Insert(m... |
package main
import (
"time"
"machine"
)
func main() {
pingConfig := machine.PinConfig{Mode: machine.PinOutput}
buttonIn := machine.Pin(2)
buttonIn.Configure(machine.PinConfig{Mode: machine.PinInput})
greenLED := machine.Pin(12)
greenLED.Configure(pingConfig)
yellowLED := machine.Pin(11)
yellowLED.Config... |
// 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 routes
import (
"github.com/gofiber/fiber/v2"
swagger "github.com/arsmn/fiber-swagger/v2" // fiber-swagger middleware
)
// SwaggerRoute func for describe group of API Docs routes.
func SwaggerRoute(app *fiber.App) {
// Create routes group.
route := app.Group("/swagger")
// Routes for GET method:
route... |
package day3
import (
"bufio"
"fmt"
"os"
)
func checkError(err error) {
if err != nil {
panic(err)
}
}
func main() {
treeMap := readinput()
var down = []int{1, 1, 1, 1, 2}
var right = []int{1, 3, 5, 7, 1}
var numberOfTrees []int
for index := 0; index < len(down); index++ {
var trees = 0
var limit = 0... |
package grab
import (
"fmt"
"net/http"
"net/url"
"testing"
)
func TestURLFilenames(t *testing.T) {
t.Run("Valid", func(t *testing.T) {
expect := "filename"
testCases := []string{
"http://test.com/filename",
"http://test.com/path/filename",
"http://test.com/deep/path/filename",
"http://test.com/fi... |
package crawler
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/life-assistant-go/base"
"github.com/life-assistant-go/utils"
)
// CrawlWorth crawl worth by fund code
func CrawlWorth(c *gin.Context) {
if code := c.Query("code"); code != "" {
if err := ForWorth(code); err != nil {
c.JSON(
http... |
/* ######################################################################
# Author: (__AUTHOR__)
# Created Time: __CREATE_DATETIME__
# File Name: loops.go
# Description:
####################################################################### */
package loops
import (
"os"
"time"
)
type Entry struct {
Spec time.Du... |
package main
import "log"
func main() {
var x []int
// what is zero value of slice when defined using var?
log.Println(x)
// what about length and capacity?
log.Printf("len: %v, cap: %v", len(x), cap(x))
// how about getting a value using an index?
// log.Println(x[0]) // panics
// And when defined like this... |
package main;
import (
"fmt"
)
type VersionCommand struct {
}
func (cmd *VersionCommand) Name() string {
return "version"
}
func (cmd *VersionCommand) Execute() (error) {
fmt.Println("bpm version 1.0.15")
return nil
}
|
package main
import (
"fmt"
"github.com/kormat/adventofcode/util"
"os"
"strings"
)
func main() {
lines, ok := util.ReadFileArg(os.Args[1:])
if !ok {
os.Exit(1)
}
var total_lit, total_mem, total_reenc int
for _, line := range lines {
total_lit += len(line)
total_mem += countEscaped(line)
total_reenc +... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.