text stringlengths 11 4.05M |
|---|
package dogachess
type Position struct {
board Bitboard
subboard [14]Bitboard
color bool
}
var position Position
func FreshBoard() Position {
position.subboard[0] = 0 // White occupied
position.subboard[1] = 0 // Black occupied
position.subboard[2] = 0x00FF00000000 // WHite occupied
position.subboard[... |
package main
import "fmt"
func main() {
name := "Wilbrone Okoth"
name := os.Args[1]
fmt.Println(os.Args[0])
fmt.Println(os.Args[1])
str := fmt.Sprint(
`
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
Hello World!
</title>
</head>
<body>
<h1>
... |
package Jwt
type IdentityClaims struct {
Audience string `json:"aud,omitempty" structs:"aud"`
ExpiresAt int64 `json:"exp,omitempty" structs:"exp"`
Id string `json:"jti,omitempty" structs:"jti"`
IssuedAt int64 `json:"iat,omitempty" structs:"iat"`
Issuer string `json:"iss,omitempty" ... |
// Copyright 2014 The Sporting Exchange Limited. All rights reserved.
// Use of this source code is governed by a free license that can be
// found in the LICENSE file.
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris
package collect
import (
"os/exec"
"syscall"
)
// statusReschedule is the ex... |
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use ... |
package main
import (
"github.com/miguelmota/cointop/cointop"
)
func main() {
cointop.Run()
}
|
package main
import "sort"
func threeSumClosest(nums []int, target int) int {
// 题目限制了只有唯一答案,所以也说明了len(nums)>=3
if len(nums) < 3 {
return 0
}
sort.Ints(nums)
minDistance := 100000000000
ans := -1
for i := 0; i < len(nums); i++ {
l, r := i+1, len(nums)-1
for l < r {
sum := nums[l] + nums[r] + nums[i]... |
/**
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package cmd
import (
"context"
"encoding/json"
"io/ioutil"
"math/big"
"os"
"strings"
"github.com/aergoio/aergo/cmd/aergocli/util"
"github.com/aergoio/aergo/types"
"github.com/mr-tron/base58/base58"
"github.com/spf13/cobra"
)
var revert bool
var... |
package main
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"math/rand"
"net/http"
)
type Weather struct {
Status WeatherCondition `json:"status"`
}
type WeatherCondition struct {
Water int `json:"Water"`
Wind int `json:"Wind"`
}
func index(w http.ResponseWriter, r *http.Request) {
//... |
package main
import (
"time"
validator "gopkg.in/go-playground/validator.v9"
)
// Validate date in the form (YYYY-MM-DD).
// All dates in publiccode.yml must follow the format "YYYY-MM-DD",
// which is one of the ISO8601 allowed encoding.
// This is the only allowed encoding though, so not the full ISO8601
// is a... |
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
)
func defaultScratchfile() string {
return os.ExpandEnv("$GOPATH/src/github.com/fletcher91/docker-go/Dockerfile.scratch")
}
func transformScratchDockerfile(outFile string) {
if defaultScratchfile() == *scratchfile {
dockerfile, err := ioutil.Re... |
package main
import "fmt"
func main() {
year := 2016
if year%4 == 0 {
fmt.Println("Look before you leap.")
}
}
|
package script
type Bool struct {
Type
}
//AnyBool is anything that can retrieve a script.Bool.
type AnyBool interface {
BoolFromCtx(AnyCtx) Bool
}
//BoolFromCtx implements AnyBool.
func (b Bool) BoolFromCtx(AnyCtx) Bool {
return b
}
func (q Ctx) Bool(literal bool) Bool {
return Bool{q.Literal(literal)}
}
func... |
package main
import (
"fmt"
"net/http"
)
func helloWorld(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Fprintf(w, "%v \n", r.Form)
fmt.Fprintf(w, "url: %s \n", r.URL)
fmt.Fprintf(w, "scheme: %s \n", r.URL.Scheme)
fmt.Fprintf(w, "hello world ... \n")
}
func main() {
http.HandleFunc("/", helloWor... |
package ytrwrap
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func TestClientGet(t *testing.T) {
ff := NewFetcher(nil)
_, code, err := ff.Get("http://localhost:1234")
assert.NotNil(t, err, "err")
assert.Equal(t, http.StatusInternalServerError, code, "code")
}
|
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package romannumerals
import "errors"
import "bytes"
import "strings"
const testVersion = 3
// The Romans wrote numbers using letters - I, V, X, L, C, D, M.
// I - 1 : 1-3
// V - 5 : 4-8
// X - 10 : 9-39
// L - 50 : 40-89
// C - 100: 90-399
// D - 500: 400-899
// M - 1000: 900-3999
// this style looks much shorter ... |
package constant
const (
URLCode = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect"
URLToken = "https://api.weixin.qq.com/sns/oauth2/access_token"
URLRefresh = "https://api.weixin.qq.com/sns/oauth2/refresh_token"
URLUserInfo... |
package session
import (
"fmt"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"github.com/trussworks/sesh/pkg/dbstore"
"github.com/trussworks/sesh/pkg/domain"
"github.com/trussworks/sesh/pkg/mock"
)
func dbURLFromEnv() string {
host := os.Getenv("DATABASE_H... |
package physics
import "math"
var (
Gravity Vector = Vector(-5)
)
type Direction int
const (
PositiveDirection Direction = 1
NegativeDirection = -1
)
type Vector float64
func (f Vector) Direction() Direction {
if f > 0 {
return PositiveDirection
}
return NegativeDirection
}
func (f Vector) Magn... |
// Runs instantly, using Dijkstra and priority queue
package main
import "fmt"
import "strings"
import "strconv"
import "io/ioutil"
import "github.com/roessland/gopkg/digraph"
var N int
var mat [][]float64
func ReadMatrix(filename string) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
panic(err.Error())... |
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
func CheckError(err error) {
if err != nil {
log.Fatal(err)
}
}
var data []string
var dataSize float64
func LoadData(basePath string, filePattern string) error {
dir, _ := o... |
package v1alpha1
import (
"github.com/operator-framework/operator-sdk/pkg/status"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ContainerSnapshotSpec defines the desired state of ContainerSnapshot
type ContainerSnapshotSpec struct {
// Important: Run "operator-sdk generate k8s" to reg... |
package main
import (
"fmt"
)
type person struct {
first_name string
last_name string
fav_icecream []string
}
func main() {
p1 := person{
first_name: "Alireza",
last_name: "Alavi",
fav_icecream: []string{
"Dark Choclate",
"Vanilla Ice",
},
}
p2 := person{
first_name: "Marian",
last_na... |
package controller
import (
"encoding/json"
"github.com/bearname/videohost/internal/common/caching"
commonDto "github.com/bearname/videohost/internal/common/dto"
"github.com/bearname/videohost/internal/common/infrarstructure/transport/controller"
"github.com/bearname/videohost/internal/common/util"
"github.com/b... |
package account
import(
"github.com/tealeg/xlsx"
acc "entity/accountentity"
"util"
//"fmt"
"strings"
)
type AccountColumnParser struct{
//each sheet define some tables, sheet-table-columns
//use to create the database table, the key is table/common name
CategoryColumnMap map[string]map[st... |
package common
type TopicType string
//Topic type
const (
EventPublish TopicType = "publish"
EventConfirmReq TopicType = "confirmReq"
EventConfirmAck TopicType = "confirmAck"
EventSyncBlock TopicType = "syncBlock"
EventConfirmedBlock TopicType = "confirmedBlock"
EventBroadcast... |
package main
import "fmt"
func main2() {
n, err := fmt.Printf("hello world\n")
fmt.Printf("%d\n", n)
fmt.Println(err)
}
|
package smhi
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"
)
var baseURLPath = "/api-test"
func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown func()) {
mux = http.NewServeMux()
apiHandler := http.NewServeMux()
apiHandler.Handle(baseURLPath+... |
package main
type CopyBuffer struct {
CutMode bool
Cards []*Card
CardsToSerialized map[*Card]string
}
func NewCopyBuffer() *CopyBuffer {
buffer := &CopyBuffer{}
buffer.Clear()
return buffer
}
func (buffer *CopyBuffer) Clear() {
buffer.Cards = []*Card{}
buffer.CardsToSerialized = map[*Ca... |
// Copyright 2023 PingCAP, 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 wr... |
package implwin
import (
"fmt"
"testing"
"draw"
"win"
)
func TestGetPenStyleWin(t *testing.T) {
testdata := []struct {
style draw.PenStyle
styleWin uint32
}{
{draw.PenStyle{}, win.PS_COSMETIC | win.PS_SOLID | win.PS_ENDCAP_ROUND | win.PS_JOIN_ROUND},
{draw.PenStyle{draw.PEN_TYPE_GEOMETRIC, draw.PEN_... |
package config
import (
"os"
"fmt"
"io/ioutil"
"encoding/json"
"portal/util"
)
// App basic config
type appConfig struct {
TokenSecrect string
TokenMaxAge int
AesKey string
}
// DB connect config
type dbConfig struct {
Username string
Password string
Host string
Port int
Database string
... |
package rotate_test
import (
"fmt"
"io/ioutil"
"os"
"github.com/bingoohuang/golog/pkg/rotate"
)
func ExampleNew() {
logDir, err := ioutil.TempDir("", "rotate_test")
if err != nil {
fmt.Println("could not create log directory ", err)
return
}
logPath := fmt.Sprintf("%s/test.log", logDir)
for i := 0; i ... |
package config
import (
"encoding/json"
"github.com/hunterhug/fafacms/core/util/mail"
"github.com/hunterhug/fafacms/core/util/oss"
"github.com/hunterhug/fafacms/core/util/rdb"
"github.com/hunterhug/fafacms/core/util/session"
"github.com/alexedwards/scs"
)
var (
FafaConfig *Config
FafaRdb *rdb.MyDb
... |
package common
import (
"testing"
)
func TestDedup(t *testing.T) {
inChannel := make(chan LogMessage, 10)
noDupChannel := Dedup(inChannel)
inChannel <- LogMessage{
ID: "1",
}
inChannel <- LogMessage{
ID: "2",
}
inChannel <- LogMessage{
ID: "3",
}
if msg := <-noDupChannel; msg.ID != "1" {
t.Fatal("Di... |
package sim
import (
"math"
"time"
)
type Job struct {
*Simulacrum
employed int
unemployed int
monthly float64
}
func NewJob(sim *Simulation, baseAnnualSalary float64) *Job {
return &Job{
Simulacrum: NewSimulacrum(sim),
employed: 0,
unemployed: 0,
monthly: baseAnnualSalary / 12.0,
}
}
func (j *Job) ... |
package main
import (
"fmt"
"io"
"os"
)
/*
create a program Read a contents from text file and prints on terminal
Note : File should be read on Command Line Args
*/
func main() {
f, err := os.Open(os.Args[1]) //--------->>> open a file from terminal EX: go run InterfaceAssignment2.go filename
// os.Args[0] ... |
package sparkpost
import (
"errors"
sp "github.com/SparkPost/gosparkpost"
"github.com/mkj-gram/go_email_service/internal/emailprovider"
"log"
"os"
"strings"
)
type SparkPostProvider struct{}
var client *sp.Client
func (s SparkPostProvider) Init() error {
cfg := &sp.Config{
BaseUrl: "https://api.sparkpos... |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package cmd
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vespa-engine/vespa/client/go/vespa"
)
func TestConfig(t *testing.T)... |
package sqlite
import (
"database/sql"
"github.com/jakewitcher/pos-server/graph/model"
"github.com/jakewitcher/pos-server/internal/users"
"golang.org/x/crypto/bcrypt"
"log"
"strconv"
)
type UserProvider struct {
db *sql.DB
}
func (p *UserProvider) CreateUser(newUser model.NewUserInput) (*model.User, error) {
... |
package models
// Crontab defines structure for crontab
type Crontab struct {
Records []Record
}
// Record defines single record at the crontab
type Record struct {
Schedule string
Command string
} |
package memory
import (
"sync"
)
// Store реализует интерфейс хранилища данных
type Store struct {
statements map[int][]string
counter int
mu sync.Mutex
}
// NewMemoryStore конструктор Store
func NewMemoryStore() (s *Store) {
return &Store{
statements: make(map[int][]string),
}
}
// SaveStatement... |
package main
import (
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
"fmt"
"log"
"time"
)
var (
device string = "en0"
snaplen int32 = 65535
promisc bool = false
err error
timeout time.Duration = -1 * time.Second
handle *pcap.Handle
)
func main() {
handle, err = pcap.OpenLive(d... |
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
func handler(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, "Hello World, %s!", request.URL.Path[1:])
}
// to run from the command line type go run main.go
// Open a browser and navigate to localhost:5555
func main() {
f... |
package 贪心
func groupThePeople(groupSizes []int) [][]int {
uids := make(map[int][]int)
result := make([][]int, 0)
for i := 0; i < len(groupSizes); i++ {
uid := i
uids[groupSizes[i]] = append(uids[groupSizes[i]], uid)
if len(uids[groupSizes[i]]) == groupSizes[i] {
result = append(result, uids[groupSizes[i]]... |
package issueProcessor
import (
"fmt"
"time"
"github.com/google/go-github/github"
"github.com/pouchcontainer/pouchrobot/utils"
)
func (ip *IssueProcessor) ActToIssueExpired(issue *github.Issue) error {
ip.ActToCloseExpire(issue)
return nil
}
func (ip *IssueProcessor) ActToCloseExpire(issue *git... |
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
const (
docsDirEntry = "website/docs"
)
func main() {
pwd, err := os.Getwd()
if err != nil {
fmt.Println("error while getting pwd")
panic(err)
}
rootDir := filepath.Join(pwd, "..", "..")
err = validateDocsDirStructure(rootDir)
if err != nil... |
package task
import (
log "code.google.com/p/log4go"
"github.com/d-d-j/ddj_master/common"
"github.com/d-d-j/ddj_master/dto"
"github.com/d-d-j/ddj_master/node"
"fmt"
)
type TaskWorker struct {
reqChan chan dto.RestRequest
getNodeChan chan node.GetNodeRequest
done chan Worker
pending int
index ... |
package bbir
import (
"os"
"testing"
)
func Test_BulkCommandExecutor(t *testing.T) {
injector := NewInjectorForCommandBuilderTest(t)
converter := injector.Get(new(CommandConverter)).(*CommandConverter)
filePath := fixturesPath + "example.csv"
file, err := os.Open(filePath)
if err != nil {
t.Errorf("Could not... |
package imagekit
import (
"context"
"errors"
"time"
)
//
// RESPONSES
//
type GetFileDetailsResponse struct {
// FileID is the unique ID of the uploaded file.
FileID string `json:"fileId"`
// Type of item. It can be either file or imageFolder.
Type string `json:"type"`
// Name of the file or imageFolder.
Na... |
package testcase
import (
"net/http"
"time"
)
type Options struct {
name string `validate:"required"`
timeout time.Duration `validate:"min=100ms,max=30s"`
maxAttempts int `validate:"min=1,max=10"`
httpClient *http.Client `validate:"gt=0"`
}
func getDefaults() Options {
return Opt... |
package main
import (
"fmt"
"github.com/achakravarty/30daysofgo/day8"
)
func main() {
var size int
fmt.Scanf("%d\n", &size)
phoneBook := day8.PhoneBook{}.NewPhoneBook()
for i := 0; i < size; i++ {
var name string
var number int
fmt.Scanf("%s %d", &name, &number)
phoneBook.Add(name, number)
}
var quer... |
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package main
import (
"container/list"
"strconv"
"strings"
)
type Codec struct {
}
func Constructor() Codec {
return Codec{}
}
// Serializes a tree to a single string.
func (c *Codec) serialize(root *TreeNode) string {
if root == nil {
return "[]"
}
q := list.New()
q.PushFront(root)
result := []string{c... |
package chain
import (
"fmt"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/wire"
)
// BitcoindEvents is the interface that must be satisfied by any type that
// serves bitcoind block and transactions events.
type BitcoindEvents interface {
// TxNoti... |
package hive_test
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/geoffgarside/homekit-hive/pkg/api/v6/hive"
)
func TestHomeConnect(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
... |
package util_test
import (
"github.com/maprost/application/generator/internal/util"
"github.com/maprost/assertion"
"testing"
)
func TestWebsiteIcons(t *testing.T) {
assert := assertion.New(t)
assert.Equal(util.WebsiteIcon("https://www.linkedin.com/myname"), util.LinkedinIconPath)
assert.Equal(util.WebsiteIcon(... |
// This program demonstrates attaching an eBPF program to a control group.
// The eBPF program will be attached as an egress filter,
// receiving an `__sk_buff` pointer for each outgoing packet.
// It prints the count of total packets every second.
package main
import (
"bufio"
"errors"
"log"
"os"
"strings"
"tim... |
package lineartable
import (
"bytes"
"errors"
"fmt"
)
// NewCircleLinkedList 返回链表
func NewCircleLinkedList() *CircleLinkedList {
h := &CircleListNode{}
h.Next = h
return &CircleLinkedList{h, 0}
}
// CircleListNode 节点
type CircleListNode struct {
Next *CircleListNode
Data interface{}
}
// CircleLinkedList 链表... |
package rest
import (
"fmt"
"time"
"github.com/jinmukeji/jiujiantang-services/pkg/rest"
analysispb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/analysis/v1"
generalpb "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2"
ptypesv2 "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2"
"github.co... |
package main
import (
"fmt"
"io/ioutil"
"runtime"
"time"
)
func openFile() {
//_, err := ioutil.ReadFile("/Users/ckhero/php-5.6.40.tar.gz") // just pass the file name
_, err := ioutil.ReadFile("/Users/ckhero/sophisticate/sophiticate/IPZ-933-C.mp4") // just pass the file name
if err != nil {
fmt.Print(err)
... |
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softw... |
// Copyright © 2017 Aeneas Rekkas <aeneas+oss@aeneas.io>
//
// 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 appl... |
package model
type UnableToRenameFileError struct {
Err string
}
func (e UnableToRenameFileError) Error() string {
return e.Err
} |
package provider
import "github.com/nats-io/nats.go"
type Provider interface {
Connect(url string, queueName string, subject string, providerName string, reply string, jetStream bool)
Provide() []byte
OnReply(msg *nats.Msg)
}
|
package main
import "fmt"
import "sort"
//import "reflect"
//abbbbccdde
//aeccddbbbb
type ss struct {
freq int
ch uint8
}
func frequency_sort(ip string) {
if len(ip) == 0 {
return
}
var m1 map[uint8]int = make(map[uint8]int, 10)
for i:=0; i<len(ip); i++ {
m1[ip[i]]++
}
... |
package service
import (
"context"
"fmt"
"strconv"
"time"
"boiler/pkg/entity"
"boiler/pkg/errors"
"boiler/pkg/store"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
"golang.org/x/crypto/bcrypt"
)
// AddUser add a new user
func (s *Service) AddUser(ctx context.Context, user *entity.User) ... |
package initiate
import (
"os"
"proximity/config"
"github.com/ralstan-vaz/go-errors"
)
// Version ...
var Version string
// Env Gets the enviroment variable from TIER
// By default the env will be development
func Env() (string, error) {
env := os.Getenv("TIER")
if env == "" {
err := os.Setenv("TIER", config... |
package main
import (
"fmt"
"github.com/sinksmell/files-cmp/client/utils"
"github.com/sinksmell/files-cmp/models"
)
const (
HOST string = "http://localhost:8080/v1/check"
HASH_URL string = "/hash"
FILE_URL string = "/file"
)
var (
groups []string //分组文件列表
diffFiles []string // 需要对比的小文件集合
)
func init(... |
package service
import (
entity "github.com/Surafeljava/Court-Case-Management-System/Entity"
notificationuse "github.com/Surafeljava/Court-Case-Management-System/notificationUse"
)
//NotificationServiceImpl struct
type NotificationServiceImpl struct {
notfRepo notificationuse.NotificationRepository
}
//NewNotifi... |
package logging
import (
"context"
"github.com/sirupsen/logrus"
)
// PrintfLogger is a logger that implements a common Printf logger.
type PrintfLogger struct {
level logrus.Level
logrus *logrus.Logger
}
// Printf is the implementation of the interface.
func (l *PrintfLogger) Printf(format string, args ...any)... |
/*
* @lc app=leetcode.cn id=173 lang=golang
*
* [173] 二叉搜索树迭代器
*/
package main
// @lc code=start
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// type TreeNode struct {
// Val int
// Left *TreeNode
// Right *TreeNode
// }... |
// common functions used across multiple files
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"github.com/bwmarrin/discordgo"
)
func getFileFullPath(filename string) (string, error) {
if !getDebugMode() {
homePath := os.Getenv("HOME")
if homePath == "" {
return "", errors.New("U... |
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00700101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.007.001.01 Document"`
Message *TransferInConfirmation `xml:"sese.007.001.01"`
}
func (d *Document00700101) AddMe... |
package fsm
//-----------------------------------------------------------------------------
// Activate activates the state and it's consecutive states until the next state
// is nil or encounters an error
func Activate(s State) (funcErr error) {
next := s
for next != nil && funcErr == nil {
next, funcErr = next.... |
// Copyright 2022 PingCAP, 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 wr... |
package lang
import (
"encoding/json"
"errors"
"log"
"math"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"tetra/lib/dbg"
"tetra/lib/levenshtein"
"tetra/lib/store"
)
var (
dict = make(map[string]string)
// store words which already printed debug message
debug = make(map[string]bool)
rxlc = regex... |
package main
import (
"github.com/guilhermeonrails/api-go-gin/database"
"github.com/guilhermeonrails/api-go-gin/routes"
)
func main() {
database.ConectaComBancoDeDados()
routes.HandleRequest()
}
|
package main
import "fmt"
func main() {
var a,b int
fmt.Scanln(&a)
fmt.Scanln(&b)
fmt.Println("X =",a+b)
} |
package rectangle
type Rectangle struct {
Len float64
Wid float64
}
func (r Rectangle)Area() float64 {
return r.Len*r.Wid
}
|
// Package main is the main package for Goswift.
package main
import (
"github.com/ChristopherRabotin/gin-contrib-headerauth"
"github.com/gin-gonic/gin"
"github.com/op/go-logging"
"sync"
)
// testGoswift must be true when testing to avoid starting the server.
var testGoswift = false
// testS3Locations will store... |
package main
import (
"fmt"
"io/ioutil"
)
func main() {
// 读取文件
byteStr, err := ioutil.ReadFile("./main/test.txt")
if err != nil {
fmt.Println("读取文件出错")
return
}
// 写入指定的文件
ioutil.WriteFile("./main/test2.txt", byteStr, 777)
}
|
//go:build linux || windows
// +build linux windows
/*
Copyright © 2021 SUSE LLC
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 ... |
package main
import (
"fmt"
linuxproc "github.com/c9s/goprocinfo/linux"
"github.com/google/go-cmp/cmp"
"testing"
)
func TestGetCpuCoresIdleTime(t *testing.T) {
mockReadStat := func(s string) (*linuxproc.Stat, error) {
return &linuxproc.Stat{
CPUStats: []linuxproc.CPUStat{
{Idle: 90},
{Idle: 100},
... |
package pathutil
import (
"fmt"
"testing"
)
func use() {
fmt.Println("")
}
func getSolFiles(solPath string) (solFiles []string, err error) {
err = filepath.Walk(solPath, func(solFile string, solFileInfo os.FileInfo, err error) error {
if solFileInfo == nil {
return err
}
if solFileInfo.IsDir() {
retu... |
package main
// --------------------- StockSpanner ---------------------
// 执行用时:192 ms, 在所有 Go 提交中击败了 98.48% 的用户
// 内存消耗:8.7 MB, 在所有 Go 提交中击败了 100.00% 的用户
//
// 时间复杂度: O(n)
// 思路: 维护一个单调递减栈。
type StockSpanner struct {
data []int
indexStack *MyStack
}
func Constructor() StockSpanner {
return StockSpanner{
... |
// Exercise 1.1:
// Modify the echo statement to also print os.Args[0], the name of the command
// that invoked it.
// Prints the command that invoked it.
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(os.Args[0])
}
|
package main
import "time"
type endpoint struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Status int `json:"status,omitempty"`
ResponseTime time.Duration `json:"responsetime,omitempty"`
}... |
package v1
import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// HelloType is a top-level type
type HelloType struct {
metav1.TypeMeta `json:",inline"`
// +optional
metav1.ObjectMeta `json:"metadata,omitempty"`
// +optional
S... |
package mutex
import (
"sync"
"sync/atomic"
"gvisor.dev/gvisor/pkg/tmutex"
)
type TMutex struct {
tmutex.Mutex
initialized uint32
}
func NewTMutex() *TMutex {
m := &TMutex{
Mutex: tmutex.Mutex{},
initialized: 0x1,
}
m.Mutex.Init()
return m
}
func (m *TMutex) Lock() {
if atomic.CompareAndSwapUi... |
package main
import (
"fmt"
"net/http"
"blockchain"
"crypto/rand"
"log"
"os"
)
func UUID() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return ""
}
return fmt.Sprintf("%X-%X-%X-%X-%X", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}
func main() {
address := os.Getenv("CHAIN_ADDRESS"... |
package hive
import (
"errors"
"testing"
)
func TestError_Error(t *testing.T) {
type fields struct {
Code string
Message string
Op string
Err error
}
tests := []struct {
name string
fields fields
want string
}{
{"Err", fields{Err: errors.New("example")}, "example"},
{"OpMessage... |
package main
import (
"fmt"
"testing"
"google.golang.org/grpc"
)
func Test_main(t *testing.T) {
_, err := grpc.Dial("127.0.0.1:2680", grpc.WithInsecure())
if err != nil {
fmt.Println(err)
return
}
}
|
// Copyright 2017 PingCAP, 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 i... |
package ds
/**
*
*
Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.
Notice that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
Example 1:
... |
package main
import (
"fmt"
)
type Items interface{}
func Map(items []Items, mapFun func(Items) Items) []Items {
for i, item := range items {
items[i] = mapFun(item)
}
return items
}
func add2(iface Items) Items {
switch v := iface.(type) {
case int:
return v * 2
case string:
return v + v
}
return if... |
package handler
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/chonla/oddsvr-api/jwt"
jwtgo "github.com/dgrijalva/jwt-go"
"github.com/globalsign/mgo/bson"
"github.com/labstack/echo"
)
func (h *Handler) Vr(c echo.Context) error {
id := c.Param("id")
if h.vr.Exists(id) {
vr, e := h.vr.FromLink(id)
... |
package proc
import (
"os"
"path/filepath"
"regexp"
"strconv"
)
type Process struct {
PID int
CmdLine string
}
func Processes() ([]*Process, error) {
return findProc(func(process *Process) bool {
return true
})
}
func ProcessesByPattern(pattern string) ([]*Process, error) {
var expression = regexp.Mu... |
// Copyright 2012 The Freetype-Go Authors. All rights reserved.
// Use of this source code is governed by your choice of either the
// FreeType License or the GNU General Public License version 2 (or
// any later version), both of which can be found in the LICENSE file.
package truetype
// This file implements a True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.