text stringlengths 11 4.05M |
|---|
package main
import (
"encoding/json"
"net/http"
module "imuslab.com/arozos/mod/modules"
)
type settingModule struct {
Name string //Name of the setting module.
Desc string //Description of the setting module
IconPath string //Icon path for the setting module
Group string //Accept {... |
package main
import (
"math/rand"
"sync"
"time"
)
func read2(id int, ci chan int, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
println(id, ":", <-ci)
}
wg.Done() //one go routine done
}
func main() {
ci := make(chan int)
rand.Seed(time.Now().UnixNano())
go func() {
for {
ci <- rand.Intn(100)
}... |
package repository
// Repository collects the repositories for each model
type Repository struct {
User UserRepository
Project ProjectRepository
Release ReleaseRepository
Session SessionRepository
GitRepo GitRepoRepositor... |
package main
import (
"github.com/paulmach/go.geojson"
"time"
)
type Stop struct {
//gorm.Model
ID uint32 `gorm:"column:ctr_id"`
Name string
Lat float64
Lon float64
}
type Line struct {
ID string
ShortName string
LongName string
Stops []Stop `gorm:"many2many:line_stop;association_foreignke... |
package main
import (
"net/http"
"github.com/gorilla/rpc"
"github.com/gorilla/rpc/json"
"github.com/gin-gonic/gin"
"github.com/olahol/melody"
)
func main() {
pluginManager.Load()
m := melody.New()
s := rpc.NewServer()
s.RegisterCodec(json.NewCodec(), "application/json, text/javascript")
chat := newChat(... |
package cdp
import (
"context"
"crypto/tls"
"net"
"net/http"
"github.com/go-rod/rod/lib/utils"
)
// Dialer interface for WebSocket connection
type Dialer interface {
DialContext(ctx context.Context, network, address string) (net.Conn, error)
}
// TODO: replace it with tls.Dialer once golang v1.15 is widely us... |
package nettests
// Psiphon test implementation
type Psiphon struct {
}
// Run starts the test
func (h Psiphon) Run(ctl *Controller) error {
builder, err := ctl.Session.NewExperimentBuilder(
"psiphon",
)
if err != nil {
return err
}
return ctl.Run(builder, []string{""})
}
|
package main
type retangulo struct {
altura float64
largura float64
}
type circulo struct {
raio float64
}
func main() {
}
|
package gatherer
import (
"io/ioutil"
"net/http"
"regexp"
"../logger"
)
// CMSDetector detects CMS with whatcms.org api.
// AJAX API.
type CMSDetector struct {
target string
CMS string
}
// NewCMSDetector returns a new CMS detector.
func NewCMSDetector() *CMSDetector {
return &CMSDetector{}
}
// Set impl... |
package main
// O(n) time | O(n) space
func IsPalindrome(str string) bool {
return helper(str, 0)
}
func helper(str string, i int) bool {
j := len(str) - 1 - i
if i >= j {
return true
}
if str[i] != str[j] {
return false
}
return helper(str, i+1)
} |
package cmd
import (
"context"
"crypto/tls"
"errors"
"expvar"
"flag"
"fmt"
"hash/crc32"
"math/rand"
"net"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/linfn/camo/pkg/camo"
"github.com/linfn/camo/pkg/env"
"github.com/linfn/camo/pkg/machineid"
"github.com/linfn/camo/pkg/util"
"git... |
package template
type TemplateRepository interface {
}
|
package getchapterinfo
import (
"bufio"
"database/sql"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
)
//book信息
type Bookinfo struct {
Bookid int `db:"id"`
Bookname string `db:"booksName"`
Boookauthor string `db:"author"`
Bookcahtpernum int `db:"... |
/*
* Created on Mon Jan 21 2019 22:52:12
* Author: WuLC
* EMail: liangchaowu5@gmail.com
*/
// two pointers, O(n) time, O(n) space
func abs(num int) int {
if num <= 0 {
return -1 * num
} else {
return num
}
}
func sortedSquares(A []int) []int {
idx := len(A)
for i, num := range A {
if num >= 0 {
idx... |
package ms
import (
"github.com/catorpilor/leetcode/utils"
)
// MaxSquare returns a max all 1s square inside matrix
func MaxSquare(matrix [][]int) int {
if matrix == nil {
return 0
}
// brute force
// if we find a 1, we move diagonally
// and check this square if it is all 1s
// if it is true update the maxS... |
package errors
// 系统性错误
func SystemError(options ...interface{}) *Error {
return NewError(1001, "system error", options...)
}
// 参数错误错误
func ParamError(options ...interface{}) *Error {
return NewError(1002, "param error", options...)
}
// DB错误错误
func DBError(options ...interface{}) *Error {
return NewError(1003, ... |
package v1
import (
"github.com/openshift-knative/knative-openshift-ingress/pkg/apis"
routev1 "github.com/openshift/api/route/v1"
)
func init() {
apis.AddToSchemes = append(apis.AddToSchemes, routev1.SchemeBuilder.AddToScheme)
}
|
package main
import (
"fmt"
"os"
"github.com/marcozj/centrify-awstool/awstool"
log "github.com/marcozj/golang-sdk/logging"
)
func main() {
log.SetLevel(log.LevelDebug)
log.SetLogPath("centrifyawstool.log")
cli := awstool.NewClient()
err := cli.Run()
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
... |
package ngx
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
// NgxClientParams 请求nginx status相关参数
type NgxClientParams struct {
EndPoint *string
UserAgent *string
Timeout time.Duration
}
// NgxClient nginx 客户端信息
type NgxClient struct {
endPoint string
httpClient *http.Client
}
//... |
package myArray
func transfer(array []int) {
}
func testAssign() {
datas := []int{1, 2, 3, 4, 5}
transfer(datas)
}
func Test_Array() {
testAssign()
}
|
package main
// Leetcode 509. (easy)
func fib(n int) int {
if n < 2 {
return n
}
res := matrixPow([2][2]int{{1, 1}, {1, 0}}, n-1)
return res[0][0]
}
func matrixPow(a [2][2]int, n int) [2][2]int {
ret := [2][2]int{{1, 0}, {0, 1}}
for n > 0 {
if n&1 == 1 {
ret = matrixMultiply(ret, a)
}
a = matrixMulti... |
package common
import (
"context"
"os"
"testing"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/stretchr/testify/assert"
)
func TestCommonEnvironmentClient(t *testing.T) {
ResetCommonEnvironmentClient()
defer CleanupEnvironment()()
os.Setenv("DATABRICKS_TOKEN", ".")
os.Setenv("DATA... |
package Majority_Element
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestME(t *testing.T) {
ast := assert.New(t)
case1 := []int{1, 1, 1, 1, 1, 3, 4, 5}
ast.Equal(majorityElement(case1), 1)
case2 := []int{1, 2, 3, 4, 1, 1, 1, 1}
ast.Equal(majorityElement(case2), 1)
case3 := []int{3, 3, 4}... |
package handlers
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestParseListParams(t *testing.T) {
namespace := "bookinfo"
objects := ""
criteria := parseCriteria(namespace, objects)
assert.Equal(t, "bookinfo", criteria.Namespace)
assert.True(t, criteria.IncludeVirtualServices)
assert.True(t... |
package msg
import (
"github.com/name5566/leaf/network/protobuf"
)
var (
Processor = protobuf.NewProcessor()
)
func init() { // 这里我们注册了一个 protobuf 消息)
Processor.Register(&TocNotifyConnect{})
Processor.Register(&TosChat{})
Processor.Register(&TocChat{})
}
|
package svr
import (
"net/http"
"github.com/gin-gonic/gin"
)
func noRoute(c *gin.Context) {
c.AbortWithStatus(http.StatusNotFound)
}
|
package main
import (
"fmt"
)
func lowerBound(nums []int,target int) int {
l,r := 0,len(nums)
for ;l<r; {
m := (l+r)/2
//和upperbound唯一的区别
// < 意味着,l会右移到小于target,那么r就是第一个等于target的下标,如果没有等于就是大于
if nums[m] < target {
l = m + 1
} else {
r = m
... |
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"os"
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/client"
)
// the version string is injected during the build process
var version string
var (
dev bool // development mode?
keys map[string]string // public key -> sec... |
package cherryInterfaces
import "fmt"
type PacketDecoder interface {
Decode(data []byte) ([]*Packet, error)
}
type PacketEncoder interface {
Encode(typ byte, buf []byte) ([]byte, error)
}
// Packet represents a network packet.
type Packet struct {
Type byte
Length int
Data []byte
}
//New create a Packet i... |
package microGin
import (
"todoList/app/options"
"github.com/gin-gonic/gin"
)
type MicroGin struct {
Engine *gin.Engine
Listen string
}
func NewMicroGin()*MicroGin{
return &MicroGin{
Engine:gin.Default(),
Listen:options.Options.GinService.Listen,
}
}
func (m *MicroGin)Run(){
m.Engine.Run(m.Listen)
}
|
package user
import (
user "goto/logic/user"
"github.com/gin-gonic/gin"
)
// Hello 打个招呼
func Hello(c *gin.Context) {
var message = user.Hello()
c.JSON(200, gin.H{
"code": 0,
"message": message,
"data": "",
})
}
// List 用户列表
func List(c *gin.Context) {
var data = user.List()
c.JSON(200, gin.H{
"... |
package ut
import (
"../../datahub"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/stretchr/testify/assert"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func TestJoinGroup(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWr... |
/*
Copyright 2022 The Skaffold 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, sof... |
package trigger
import (
"context"
"time"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io... |
package Algorithms
import (
GD "GoGraph/DataStructure"
GG "GoGraph/Graph"
GV "GoGraph/Vertex"
)
func dijkstraOnDense(s *GV.Vertex, graph *GG.Graph) {
if len(graph.AdjMatr) == 0 {
graph.GetAdjMatrix()
}
var V []*GV.Vertex //A vertex set which has the shortest path from s.
var U []*GV.Vertex //V... |
package smartling
// FileStatus represents current file status in the Smartling system.
type File struct {
// FileURI is a unique path to file in Smartling system.
FileURI string
// FileType is a file type identifier.
FileType FileType
// LastUploaded refers to time when file was uploaded.
LastUploaded UTC
/... |
package credit_journal
import "cointhink/proto"
import "cointhink/model/account"
import "cointhink/db"
import "log"
var Columns = "id, account_id, schedule_id, status, stripe_tx, credit_adjustment, total_usd"
var Fields = ":id, :account_id, :schedule_id, :status, :stripe_tx, :credit_adjustment, :total_usd"
var Table ... |
package flexo
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"github.com/SECCDC/flexo/model"
)
func (s *Server) getCategories(c *gin.Context) {
cats, err := queryCategories(s.DB)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"message": "Encountered an error while pr... |
package parser
import (
"github.com/stephens2424/php/ast"
"github.com/stephens2424/php/token"
)
func (p *Parser) parseTopStmt() ast.Statement {
switch p.current.Typ {
case token.Namespace:
// TODO check that this comes before anything but a declare statement
p.expect(token.Identifier)
p.namespace = ast.NewN... |
package common
import "go.uber.org/dig"
type UpdateActionOut struct {
dig.Out
Action func(dt int64) `group:"update_actions"`
}
type UpdateActionsIn struct {
dig.In
Actions []func(dt int64) `group:"update_actions"`
}
type Pos struct {
X, Y float32
}
|
package delete
import (
"fmt"
"os"
"path/filepath"
"strings"
platformK8s "github.com/dolittle/platform-api/pkg/platform/k8s"
"github.com/spf13/cobra"
)
var customerCMD = &cobra.Command{
Use: "customer",
Short: "Shows commands to aid in deleting a customer from the cluster",
Long: `
go run main.go tools h... |
// 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 quickanswers
import (
"context"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/browser"
"chromiumos/tast/local/... |
package color
import (
"fmt"
"github.com/bchadwic/gh-graph/pkg/stats"
lg "github.com/charmbracelet/lipgloss"
)
const (
Catagories = 5
GroupFormRate = 2
DefaultBestDay = 100
)
type ColorPalette struct {
Colors []Color
Limits []int
}
type Color struct {
R uint8
G uint8
B uint8
}
func (cp *ColorPalet... |
package main
import (
"io"
"os"
"github.com/yuyamada/atcoder/lib"
)
func main() {
solve(os.Stdin, os.Stdout)
}
func solve(r io.Reader, w io.Writer) {
io := lib.NewIo(r, w)
defer io.Flush()
n := io.NextInt()
ans := solver(n)
io.Println(ans)
}
func solver(n int) int {
a := lib.Matrix([][]int{{2, 1, 0}, {2,... |
package rawdatalog_test
import (
"fmt"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/sirupsen/logrus"
logrusTest "github.com/sirupsen/logrus/hooks/test"
"github.com/dolittle/platform-api/pkg/dolittle/k8s"
"github.com/dolittle/platform-api/pkg/platform"
appsv1 "k8s.io/api/apps/v1"
corev1 ... |
/*
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 connector
import (
"common"
// "logger"
)
const PLAYERLEVEL_MAX = 200
// //return (*cfg)[0].Deco
// return reflect.ValueOf(&(*cfg)[0]).Elem().FieldByName(fmt.Sprintf("Deco%d", level)).Interface().(uint32)
// case rpc.BuildingId_Bomb:
func GetGlobalCfg(key string) uint32 {
return common.GetGlobalConf... |
package BuddySimulator
import (
"sort"
"fmt"
)
var nextPid int = 0
type Process struct {
pid int
memoryUsage uint
memoryBlock *Block
}
func NewProcess(memoryUsage uint) *Process {
process := &Process{nextPid, memoryUsage, nil}
nextPid++
return process
}
func (p Process)GetPid() int {
return p.pid
... |
// Copyright 2015-2016 Cocoon Labs Ltd.
//
// See LICENSE file for terms and conditions.
package libflac
import (
"io"
"os"
"testing"
"github.com/cocoonlife/testify/assert"
)
func TestDecode(t *testing.T) {
a := assert.New(t)
d, err := NewDecoder("testdata/nonexistent.flac")
a.Equal(d, (*Decoder)(nil), "dec... |
package handlers
import (
"net/http"
"github.com/abhinavdwivedi440/microservices/data"
)
// swagger:route GET /products products listProducts
// Returns a list of products
// responses:
// 200: productsResponse
// GetProducts returns the products from the data store
func (p *Product) GetProducts(w http.ResponseWr... |
// SPDX-License-Identifier: MIT
// apidoc 是一个 RESTful API 文档生成工具
//
// 大致的使用方法为:
//
// apidoc cmd [args]
//
// 其中的 cmd 为子命令,args 代码传递给该子命令的参数。
// 可以使用 help 查看每个子命令的具体说明:
//
// apidoc help [cmd]
package main
import (
"fmt"
"os"
"github.com/issue9/localeutil"
"golang.org/x/text/language"
"github.com/caixw/apidoc... |
package undocker
import (
"encoding/json"
"io"
"github.com/pkg/errors"
"github.com/pepabo/undocker/internal/untar"
)
type Source interface {
Config(repository, tag string) ([]byte, error)
Exists(repository, tag string) bool
LayerBlobs(repository, tag string) ([]io.Reader, error)
Image(repository, tag string... |
package log
import (
"fmt"
"io"
stdlib_log "log"
"os"
log_api "github.com/cyberark/secretless-broker/pkg/secretless/log"
)
var defaultOutputBuffer = os.Stdout
// Logger is the main logging object that can be used to log messages to stdout
// or any other io.Writer. Delegates to `log.Logger` for writing to the ... |
package html5_test
import (
. "github.com/bytesparadise/libasciidoc/testsupport"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("ordered lists", func() {
It("with implicit numbering style on a single line", func() {
source := `. item on a single line`
expected := `<div class="ol... |
// Copyright (c) 2011 Mateusz Czapliński (Go port)
// Copyright (c) 2011 Mahir Iqbal (as3 version)
// 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, including without li... |
package verify
import "testing"
var (
threeCharacterNames = []string{
"bob",
"mat",
"jim",
"sue",
}
validIntegers = []string{
"123",
"4",
"9993",
}
invalidIntegers = []string{
"12 3",
" 123",
" 1",
"1,200",
"fm",
"dskq",
" a",
}
)
func Test_Length(t *testing.T) {
for _, name := ran... |
package elf
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"os"
"strconv"
)
type formatterFunc func(a byte, b ...byte) string
type field struct {
offset byte
name string
fn formatterFunc
}
const (
bufSize = 64
)
type HeaderInfo struct {
Magic string `json:"magic"`
Class string `json:"c... |
package main
import (
"log"
"time"
)
func main() {
ticker := time.Tick(time.Second * 1)
for i := 0; i < 4; i++ {
log.Println(i, ":", <-ticker)
}
}
|
package smaato
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/buger/jsonparser"
"github.com/prebid/openrtb/v19/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-serv... |
package assert
import "testing"
func TestNotNilValue(t *testing.T) {
{
err := AssertThat(t, NotNilValue())
if err != nil {
t.Fatal("expect nil")
}
}
{
err := AssertThat(0, NotNilValue())
if err != nil {
t.Fatal("expect nil")
}
}
{
err := AssertThat("", NotNilValue())
if err != nil {
t.Fa... |
package config
import (
"fmt"
"github.com/spf13/viper"
"os"
)
type (
MongodbConfig struct{
Database string `mapstructure:"database"`
Host string `mapstructure:"host"`
}
SwaggerConfig struct{
Host string `mapstructure:"host"`
Version string `mapstructure:"version"`
BasePath string `mapstructur... |
package action
import (
"github.com/mylxsw/adanos-alert/configs"
"github.com/mylxsw/adanos-alert/internal/queue"
"github.com/mylxsw/adanos-alert/internal/repository"
"github.com/mylxsw/asteria/log"
"github.com/mylxsw/glacier/infra"
"github.com/pkg/errors"
)
type Provider struct{}
func (s Provider) Register(app... |
/*
Copyright 2014 Jiang Le
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
distri... |
package cmd
import (
"bytes"
"context"
"fmt"
"net"
"os"
"strconv"
"time"
"github.com/google/uuid"
"github.com/gridscale/gsclient-go/v3"
"github.com/gridscale/gscloud/render"
"github.com/sethvargo/go-password/password"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type serverCmdFlags struct... |
package log
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func newZapLogger() *zap.SugaredLogger {
var cfg *zap.Config
if _debugMode {
cfg = &zap.Config{
Level: zap.NewAtomicLevelAt(zap.DebugLevel),
Development: true,
Encoding: "console",
EncoderConfig: zapcore.EncoderConfig{
M... |
// ===================================== //
// author: gavingqf //
// == Please don'g change me by hand == //
//====================================== //
/*you have defined the following interface:
type IConfig interface {
// load interface
Load(path string) bool
// clear interface
Clear()
}... |
package value
import (
"fmt"
"go.starlark.net/starlark"
)
type Stringable struct {
Value string
IsSet bool
}
func (s *Stringable) Unpack(v starlark.Value) error {
str, ok := AsString(v)
if !ok {
return fmt.Errorf("Value should be convertible to string, but is type %s", v.Type())
}
s.Value = str
s.IsSet =... |
package kubectl
import (
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
"github.com/loft-sh/devspace/pkg/devspace/kubectl"
)
func Delete(ctx devspacecontext.Context, deploymentName string) error {
deploymentCache, ok := ctx.Config().RemoteCache().GetDeployment(deploymentName)
if !ok || deploym... |
package cron
import "time"
import "log"
import "encoding/json"
import "fmt"
import "strconv"
import "cointhink/config"
import "cointhink/proto"
import "cointhink/common"
import "cointhink/constants"
import "cointhink/httpclients"
import "cointhink/q"
import "cointhink/lxd"
import "cointhink/mailer"
import "cointhink/... |
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/sensu/sensu-go/types"
"github.com/spf13/cobra"
pushbullet "github.com/xconstruct/go-pushbullet"
)
var (
token, device string
stdin *os.File
allDevices bool
)
func main() {
rootCmd := configureRootCommand(... |
package entity
import "fmt"
type GraphDataElements []GraphDataElement
func (g GraphDataElements) MinSize() (min int) {
for _, v := range g {
if min == 0 {
min = v.SizeBytes
}
if v.SizeBytes < min {
min = v.SizeBytes
}
}
return
}
func (g GraphDataElements) MaxSize() (max int) {
for _, v := range g ... |
// 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, ... |
//115. Returning a func
// //回傳的類型 他是type
//bar() func() int
//橘色為回傳類型 func()int
//因 橘色 回傳類型限定 所以 得綠色方式回傳
//而因紅色 輸出 bar() 需要再多個 ()當容器
//dc 圖解 115
package main
import "fmt"
func main() {
x := bar()
fmt.Printf("%T\n", x)
fmt.Println(bar()())
}
func bar() func() int {
return func() int {
return 451
}
}
|
package main
import (
"io/ioutil"
"log"
"os"
"github.com/alecthomas/chroma/lexers"
"github.com/ktnyt/carrera"
carreraBuffer "github.com/ktnyt/carrera/buffer"
termbox "github.com/ktnyt/termbox-go"
)
func openFile(filename string) carrera.BufferService {
file, err := os.Open(filename)
if err != nil {
log.Fa... |
package main
import (
"fmt"
"os"
"runtime"
)
func operator() {
assert((true && true) == true, "Wrong logic")
assert((true && false) == false, "Wrong logic")
assert((false && true) == false, "Wrong logic")
assert((false && false) == false, "Wrong logic")
assert((true || true) == true, "Wrong logic")
assert((... |
package cmd
import (
"github.com/spf13/cobra"
)
var azureCmd = &cobra.Command{
Use: "azure",
Short: "Azure subcommands",
}
func init() {
createCmd.AddCommand(azureCmd)
}
|
package Binary_Tree_Right_Side_View
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRightSideView(t *testing.T) {
ast := assert.New(t)
ast.Equal([]int{1, 3, 4, 7}, rightSideView(&TreeNode{
Val: 1,
Left: &TreeNode{
Val: 2,
Right: &TreeNode{
Val: 5,
Left: &TreeNode{
Val: ... |
package bittrex
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/pkg/errors"
)
type restCall struct {
req *http.Request
res *restResponse
resBody []byte
httpClient *http.Client
httpTranspo... |
package routes
import (
"net/http"
"github.com/jesperkha/SuperSurveys/app/data"
)
func setEncodedCookie(res http.ResponseWriter, name string, key string, value interface{}) {
if encoded, err := CookieHandler.Encode(key, value); err == nil {
cookie := &http.Cookie{
Name: name,
Value: encoded,
Path: "/"... |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
package e2e
import (
"context"
framework "github.com/operator-framework/operator-sdk/pkg/test"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"... |
package wasi
import (
"os"
"sync/atomic"
)
const unknownDevice = (1 << 64) - 1
var fileCookie uint64
func fileStatUnknown(info os.FileInfo) FileStat {
modTime := info.ModTime()
return FileStat{
Dev: unknownDevice,
Inode: atomic.AddUint64(&fileCookie, 1),
Mode: info.Mode(),
LinkCount: ... |
package identity
import "context"
type contextKey string
func (k contextKey) String() string {
return "context key: " + string(k)
}
var (
userKey = contextKey("user")
)
// WithUser adds the user to the request context.
func WithUser(ctx context.Context, user string) context.Context {
return context.WithValue(ct... |
package socket
import (
"errors"
protoutil "github.com/gogo/protobuf/proto"
"net"
"xj_web_server/httpserver/wss/proto"
"xj_web_server/util"
"strings"
"sync"
"time"
)
const (
// 写超时时间
writeWait = 10 * time.Second
msgCont = 1024
)
type Connection struct {
tcpConn net.Conn
inChan chan []byte
outCha... |
package email
import (
"bytes"
"fmt"
"html/template"
"log"
"mta_app/config"
"net/smtp"
)
type emailUser struct {
Username string
Password string
EmailServer string
Port int
SendTo []string
}
func NewEmailUser(opts config.EmailUser) emailUser {
return emailUser{
Username: opts.Usern... |
package virtualmachine
import (
"fmt"
"testing"
"../ast"
"../compiler"
"../lexer"
"../object"
"../parser"
)
// virtualMachineTestCase :
type virtualMachineTestCase struct {
input string
expected interface{}
}
// parse :
func parse(input string) *ast.Program {
l := lexer.InitializeLexer(input)
p := par... |
package scan
import (
"io"
"github.com/bobappleyard/readline"
// "gitlab.com/Scheming/interpreter/config" //// config not yet implemented
)
type gnuReadline struct {
// config *config.T //// config not yet implemented
line string
next int
}
func NewConsoleReader( /* config *config.T */ ) io.ByteReader {
retu... |
package logging
import (
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"strconv"
"time"
)
func NewLogger() *zap.Logger {
year, month, day := time.Now().Date()
_ = os.Mkdir("logs", 0755)
filename := "/logs/" + strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day) + ".log"
_, ... |
package noolite
import (
"errors"
"reflect"
"testing"
)
type FakeUart struct {
awaitReq []byte
successRead bool
needFail bool
}
func (fu FakeUart) Read(d []byte) (count int, err error) {
if fu.successRead {
d[0] = 173
d[16] = 174
if !fu.needFail {
d[15] = 173
}
return 17, nil
}
return 0, ... |
package leetcode
func missingNumber(nums []int) int {
length := len(nums)
var lsum int
var nsum int
lsum = (length + 1) * length / 2
for i := 0; i < length; i++ {
nsum += nums[i]
}
return lsum - nsum
}
// Test site: bit operation
func missingNumber(nums []int) int {
length := len(nums)
var xor int
for i ... |
package main
func main() {
var x int
x = 1 + 2 +
}
|
package main
import "fmt"
type matrix struct {
row int
column int
mat [][]int
}
func (m matrix) create_mat (r int, c int) matrix{
temp:= matrix{}
temp.row = r
temp.column = c
temp.mat = make([][]int, r)
for k:= 0; k<r; k++ {
temp.mat[k] = make([]int, c)
}
... |
package main
func f(a, b, int) {
}
|
/**
动态扩容的数组
*/
package array
type DynamicArray struct {
elements []int
length int
capacity int
}
func NewDynamicArray(cnt int) *DynamicArray {
if cnt <= 0 {
panic("array capacity must be gt 0.")
}
return &DynamicArray{
elements: make([]int, cnt),
length: 0,
capacity: cnt,
}
}
func (da *DynamicArra... |
// Copyright (C) 2015-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 th... |
package controller
import (
"github.com/gin-gonic/gin"
"gopetstore_v2/src/domain"
"gopetstore_v2/src/global"
"gopetstore_v2/src/service"
"gopetstore_v2/src/util"
"log"
"net/http"
)
// file name
const (
signInFormFile = "signInForm.html"
registerFormFile = "registerForm.html"
editAccountFormFile = "e... |
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var prev *TreeNode
func _flatten(root *TreeNode) {
if root == nil {
return
}
_flatten(root.Right)
_flatten(root.Left)
root.Right, root.Left, prev = prev, nil, root
}
func flatten(root *TreeNode) {
prev = nil
_flatten(root)
}
... |
// 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 hub
import (
"testing"
"github.com/pkg/errors"
"h12.io/sej"
)
type stackTracer interface {
StackTrace() errors.StackTrace
}
func TestMain(m *testing.M) {
sej.Test{}.Main(m)
}
|
package main
import (
"flag"
"fmt"
"log"
"bytes"
"time"
"github.com/live-dash/live-dash/templates"
"github.com/live-dash/live-dash/sse"
"github.com/valyala/fasthttp"
)
type MyHandler struct {
routes map[string]fasthttp.RequestHandler
}
var (
addr = flag.String("addr", ":80", "TCP address to listen to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.