text stringlengths 11 4.05M |
|---|
/*
Given an image, either as input (possibly in RGB triplets) or with the filename as input (you may assume the image has a specific filename, possibly without an extension), output an image representing a single color channel of the image.
You will also take another input, representing which channel to output.
The i... |
// +build !no_ldflags
package oiio
// #cgo LDFLAGS: -L/usr/local/lib -lOpenImageIO -lboost_thread -lboost_system
import "C"
|
package list
type Element struct {
next *Element
prev *Element
list *List
Value interface{}
}
func (e *Element) Next() *Element {
if p := e.next; e.list != nil && p != &e.list.root {
return p
}
return nil
}
func (e *Element) Prev() *Element {
if p := e.prev; e.list != nil && p != &e.list.root {
return ... |
// slices package provides template for genny.
//
// It generates generic algorithms for slices:
//
// genny -in=$GOPATH/src/github.com/shibukawa/slices/template/slices.go -out=mystructslices.go gen "ValueType=MyStruct"
//
// This commands generates the following functions:
//
// MyStructSort(slices []MyStruct, lt... |
package mqtt
import (
"context"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/backends/mqtt/types"
"github.com/batchcorp/plumber/promet... |
package main
import (
"bufio"
"bytes"
"os/exec"
"regexp"
"strings"
)
var deviceRE = regexp.MustCompile(`^(.*):$`)
var locationRE = regexp.MustCompile(`^Location ID: (.*)$`)
//TODO: Call library directly
func enumerateDevices() ([]device, error) {
if err := checkExe("system_profiler"); err != nil {
return nil... |
package main
import (
"github.com/gorilla/mux"
"fmt"
"log"
"net/http"
)
func boardHandler(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
board := params["board"]
if boards[board] != true {
log.Println("Invalid board requested: /" + board + "/")
http.NotFound(w, r)
return
}
b, err := ... |
package connectors
import (
"fmt"
"net/http"
"io"
"io/ioutil"
"errors"
"encoding/json"
log "github.com/sirupsen/logrus"
)
var (
// define base URL for yelp API
baseApiURL = "https://api.yelp.com/v3/businesses"
// define custom errors
ErrInvalidAPIResponse = errors.New("R... |
package main
import (
"context"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/xumc/mini-queue/queue"
"os"
"os/signal"
"strconv"
"syscall"
"time"
)
func init() {
log.SetFormatter(&log.TextFormatter{})
log.SetOutput(os.Stdout)
log.SetLevel(log.DebugLevel)
}
func main() {
run()
}
func run() {
ctx, c... |
package auth
import (
"io/ioutil"
"net/url"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/square/p2/pkg/logging"
"github.com/square/p2/pkg/uri"
"github.com/square/p2/pkg/util"
)
type testFile string
var (
testArtifact testFile = "hello-server_3881c78ed47ae8be4a4080178f2d46cc174a5a95.tar.gz"
tes... |
package leetcode
import (
"reflect"
"testing"
)
func TestSumEvenAfterQueries(t *testing.T) {
A1, q1, ans1 := []int{1, 2, 3, 4},
[][]int{
[]int{1, 0},
[]int{-3, 1},
[]int{-4, 0},
[]int{2, 3},
}, []int{8, 6, 2, 4}
if !reflect.DeepEqual(sumEvenAfterQueries(A1, q1), ans1) {
t.Fatal()
}
}
|
package main
import (
"fmt"
"github.com/zcong1993/telnetor/rpclib"
"github.com/zcong1993/telnetor/utils"
"gopkg.in/alecthomas/kingpin.v2"
"log"
"net/rpc"
"os"
)
var (
// Version is cli version
Version = "v0.1.0"
serverAddr = utils.GetEnvOrDefault("SERVER_ADDR", "localhost:10101")
)
var (
app = ... |
package thorf
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
)
// TokenType is the enum of possible types of Tokens.
type TokenType int
const (
// Word is the name of an operation.
Word TokenType = iota
// Num is a number.
Num
// Def indicates the beginning of the definition for a new user-defined functio... |
package orders
import (
"../client"
"../ticket"
)
type Orders struct {
orders map[client.Client][] ticket.Ticket
}
|
package jwt
import (
"blog/config"
"github.com/dgrijalva/jwt-go"
jwtmiddleware "github.com/iris-contrib/middleware/jwt"
"github.com/kataras/iris/v12/context"
"github.com/mlogclub/simple"
"time"
)
var tokenClaimsData *tokenClaims
type tokenClaims struct {
UserId uint
UserName string
Rule string
}
func... |
// example1.go
package main
import "math/rand"
func f1(s []int) {
_ = s[0] // 第5行: 需要边界检查
_ = s[1] // 第6行: 需要边界检查
_ = s[2] // 第7行: 需要边界检查
}
func f2(s []int) {
_ = s[2] // 第11行: 需要边界检查
_ = s[1] // 第12行: 边界检查消除了!
_ = s[0] // 第13行: 边界检查消除了!
}
func f3(s []int, index int) {
_ = s[index] // 第17行: 需要边界检查
_ = s[ind... |
package awscommons
import (
goerrors "errors"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager/types"
"github.com/gruntwork-io/go-commons/errors"
)
// GetSecretsManagerMetadata returns the metadata of the Secrets Manag... |
// Package store defines the storage interface Store and contains any
// implementations of that interface. These are the storage-related
// methods to support the "business logic" in the service package.
// The storage methods do things such as fetching or storing a
// memoized value, as well as counting the number o... |
package module
import (
"fmt"
"buddin.us/eolian/dsp"
lookup "buddin.us/eolian/wavetable"
"github.com/mitchellh/mapstructure"
)
func init() {
Register("Wavetable", func(c Config) (Patcher, error) {
var config struct{ Table string }
if err := mapstructure.Decode(c, &config); err != nil {
return nil, err
... |
package grpc
import (
"github.com/HNB-ECO/HNB-Blockchain/HNB/access/grpc/proto"
"github.com/HNB-ECO/HNB-Blockchain/HNB/config"
"github.com/HNB-ECO/HNB-Blockchain/HNB/logging"
"crypto/tls"
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"net"
)
var GRPCLog loggin... |
package main
import (
"fmt"
"os"
"github.com/giantswarm/conair/networkd"
"github.com/giantswarm/conair/nspawn"
)
var cmdDestroy = &Command{
Name: "destroy",
Description: "Destroy conair environment",
Summary: "Remove bridge, iptables and unit file",
Run: runDestroy,
}
func runDestroy(args... |
package main
import (
"fmt"
"math"
)
func Prima(N int) string {
for i := 2; i <= int(math.Ceil(float64(N)/2)); i++ {
if N%i == 0 {
return "Bukan Bilangan Prima"
}
}
return "Bilangan Prima"
}
func main() {
var num int
fmt.Println("CHECK PRIME")
for {
fmt.Print("Input: ")
_, _ = fmt.Scanln(&num)
... |
package main
import (
"fmt"
)
type myType int
func (t myType) println() {
fmt.Println(t)
}
func main() {
var z myType = 123
z.println()
}
|
package acronym
import (
"strings"
)
// Abbreviate should receive a string and return a valid acronym.
func Abbreviate(s string) string {
s = strings.ToUpper(strings.TrimSpace(s))
replacer := strings.NewReplacer(",", "", ".", "", ";", "")
s = replacer.Replace(s)
words := strings.Fields(s)
var acr string
for _,... |
package query
import (
"github.com/juju/errgo"
// "github.com/mezis/klask/index"
)
// A selection filter (returns only values in the list)
type query_filter_in_t struct {
query_filter_membership_t
}
func (self *query_filter_in_t) Run(records string, ctx Context) (string, error) {
// err := self.field.Filter("in"... |
package worker
import (
"bytes"
"log"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWorkerReader(t *testing.T) {
w := New(nil)
f, err := os.Open("test_data/file.csv")
if err != nil {
panic(err)
}
defer func() { _ = f.Close() }()
// capture error log
logBuffer := &bytes.Buffer{}
log.Se... |
package analysis
// TokenFreq 表示 term 出现的次数
type TokenFreq struct {
Term []byte
frequency int
}
func (tf *TokenFreq) Frequency() int {
return tf.frequency
}
// TokenFrequencies 表示文档中所有 term 的 TokenFreq 信息
type TokenFrequencies map[string]*TokenFreq
func TokenFrequency(tokens TokenStream) TokenFrequencies {
... |
package main
import "fmt"
func main() {
//Perbedaan slice dan array
//Array adalah kumpulan nilai atau elemen, sedang slice adalah referensi tiap elemen tersebut.
//Slice dibentuk dari array yang sudah didefinisikan
/*Perbedaan Array dan Slice*/
// var fruitsA = []string{"apple", "grape"} // slice
// var ... |
package sdkc
/*
#include "lib/greengrasssdk.h"
*/
import "C"
import (
"encoding/json"
"fmt"
"unsafe"
)
// QueueFullPolicyOption specifies what to do when queue is full.
type QueueFullPolicyOption int
const (
// QueueFullPolicyOptionBestEffort sets publishing at best effort.
QueueFullPolicyOptionBestEffort = 0
... |
package models
//Slide type contains carousel slide info
type Slide struct {
Model
Title string `form:"title" binding:"required"`
Content string `form:"content"`
NavigationURL string `form:"navigation_url"`
FileURL string `form:"file_url"`
Ord int `form:"ord"`
}
|
package fujitsu01
import (
"errors"
"github.com/dash-app/remote-go/aircon"
"github.com/dash-app/remote-go/hex"
)
func (r *fujitsu01) Generate(e *aircon.Entry) ([]*hex.HexCode, error) {
code := [][]int{
{0x14, 0x63, 0x00, 0x10, 0x10, 0xFE, 0x0B, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00},... |
package pie_test
import (
"github.com/elliotchance/pie/v2"
"github.com/stretchr/testify/assert"
"testing"
)
func TestStrings(t *testing.T) {
assert.Equal(t, []string{}, pie.Strings([]float64{}))
assert.Equal(t,
[]string{"92.384", "823.324", "453"},
pie.Strings([]float64{92.384, 823.324, 453}))
}
|
package database
import "fmt"
var connection string
func init() {
connection = "MySQL"
fmt.Println("init di panggil")
}
func GetDatabase() string {
return connection
}
|
package mq
import (
"context"
"github.com/streadway/amqp"
"grm-service/mq/message"
)
// 消息对象参数
type Options struct {
Channel *amqp.Channel
Exchange []message.ExchangeOption
Queue []message.QueueOption
Publish []message.PublishOption
Consume []message.ConsumeOption
// Other options
Context context.C... |
package tdbdir
import (
"database/sql/driver"
"fmt"
"strconv"
"strings"
"bitbucket.org/matchmove/go-database/query"
testdb "github.com/erikstmartin/go-testdb"
)
// Entry represents the testdb test entry
type Entry struct {
Columns []string
CSVResult string
Test func(string, []driver.Value) (error, b... |
package bitbucket
import (
"encoding/json"
"errors"
"fmt"
"net/url"
)
// Bitbucket POSTs to the service URL you specify. The service
// receives an POST whenever user pushes to the repository.
const BrokerTypePost = "POST"
const BrokerTypePullRequestPost = "Pull Request POST"
type Broker struct {
// A Bitbucke... |
// Copyright © 2020 Attestant Limited.
// 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 ... |
// Package cryptoki implements cryptographic token interface as defined
// in PKCS #11.
package cryptoki
|
package admin
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"docktor/server/types"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
const assetsJSON = `{"cadvisor-compose.yml":".*","watchtower-compose.yml":".*"}`
func TestGetAssets(t *testing.T) {
// Setup
e ... |
package stages
import (
"context"
"fmt"
mortarpb "github.com/SoftwareDefinedBuildings/mortar/proto"
"github.com/pborman/uuid"
"github.com/pkg/errors"
"gopkg.in/btrdb.v4"
"math"
"regexp"
"strconv"
"sync"
"time"
)
type TimeseriesQueryStage struct {
upstream Stage
ctx context.Context
output chan *Re... |
package controllers
import (
"github.com/fatjiong/goblog/model"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
/**
分类列表
*/
func CategoryGet(c *gin.Context) {
cid, _ := strconv.Atoi(c.Param("cid"))
//获取文章列表
articleList, _ := model.GetArticleListByCategoryId(10, uint(cid))
//分类列表
categoryList, _ := model.G... |
package main
import (
"fmt"
"time"
)
/*
Channel (canal) - é a forma de comunicação entre goroutines
é um tipo
*/
func doisTresQuatroVezes(base int, c chan int) {
time.Sleep(time.Second)
c <- 2 * base
time.Sleep(time.Second)
c <- 3 * base
time.Sleep(3 * time.Second)
c <- 4 * base
}
func main() {
ch := ... |
package internal
import (
"strconv"
"sync"
b "github.com/stellar/go/build"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/keypair"
"github.com/stellar/go/support/errors"
)
// Bot represents the friendbot subsystem.
type Bot struct {
Horizon *horizon.Client
Secret string
Netw... |
package libs
import (
"log"
"github.com/streadway/amqp"
"github.com/Mateus-pilo/go-whats-opt/hlp"
)
var connection *session
type session struct {
*amqp.Connection
*amqp.Channel
}
func (s session) Close() error {
if s.Connection == nil {
return nil
}
return s.Connection.Close()
}
func ConnectionMqp() (s... |
package targets
import (
"encoding/base64"
"fmt"
"os"
"sort"
"strconv"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
tuf "github.com/theupdateframework/notary/tuf/data"
"gopkg.in/yaml.v2"
"github.com/foundriesio/fioctl/client"
"github.com/foundriesio/fioctl/sub... |
package controllers_test
import (
"authentication/router"
"net/http"
"net/http/httptest"
"testing"
"github.com/jinzhu/gorm"
. "github.com/smartystreets/goconvey/convey"
)
func TestStatusRoute(t *testing.T) {
Convey("When the server is running", t, func() {
db, err := gorm.Open("sqlite3", "./test.db")
if e... |
package types
import (
"bytes"
"fmt"
)
type FeedValues []FeedValue
// String implements fmt.Stringer
func (fv FeedValues) String() string {
if len(fv) == 0 {
return "[]"
}
var str string
for _, f := range fv {
str += f.String() + "\n"
}
return str
}
// String implements fmt.Stringer
func (f FeedContext... |
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03600205 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.036.002.05 Document"`
Message *SecuritiesFinancingModificationInstruction002V05 `xml:"S... |
package server
import (
"encoding/json"
"errors"
"time"
log "../log"
"../proto"
)
/// Reboot/Notification/config_read etc
//RPC Command
func ExecSendCommand(msg string) (string, error) {
var dat map[string]interface{}
if err := json.Unmarshal([]byte(msg), &dat); err == nil {
log.Debug("RPC Command:[%s]", m... |
package logic
import (
"context"
"encoding/json"
"time"
"tpay_backend/adminapi/internal/common"
"tpay_backend/model"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type SaveSiteConfigLogic struct {
logx.Logger
ctx context.Context
s... |
package main
import "testing"
func TestClientDummy(t *testing.T) {} |
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
// DB stores the information
type DB struct {
session *mgo.Session
collection *mgo.Collection
}
type bininfo struct {
ID bson.Ob... |
package datamodel
import (
template2 "html/template"
"github.com/GoAdminGroup/go-admin/context"
"github.com/GoAdminGroup/go-admin/modules/db"
"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
"github.com/GoAdminGroup/go-admin/template"
"github.com/GoAdminGroup/go-admin/template/types"
"github.com/... |
// 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 api
import (
"fmt"
"github.com/go-chi/chi"
"net/http"
"log"
"encoding/json"
"My-project/models"
)
func (api *API) initUsersRoutes(r chi.Router) {
r.Get("/", api.getUsersByName)
r.Get("/createusers", api.insert)
r.Get("/removeusers", api.remove)
r.Get("/updateusers", api.update)
}
func (api *API) g... |
package main
// Request a request
type Request struct {
Data string `json:"data"`
Input string `json:"input"`
}
// Response a response
type Response struct {
Output string `json:"output"`
TTL string `json:"ttl"`
}
|
package client_test
import (
"math/rand"
"os"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tochka/tcached/client"
)
var (
c *client.Client
)
func TestMain(m *testing.M) {
c = client.NewClient("127.0.0.1:30003")
rand.Seed(time.Now().Uni... |
package datastore
import (
"log"
"time"
"github.com/williamzion/chatter/logger"
)
// A Thread represents a forum thread (a conversation among forum users).
type Thread struct {
ID int
UUID string
Topic string
UserID int
CreatedAt time.Time
}
// A Post represents a post (a message added by... |
package errorcode
import (
"fmt"
"log"
"runtime/debug"
"strings"
"BearApp/common/helper"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/gqlerrors"
)
var mappingAPIError = map[string]APIError{
/**
* 共用相關
*/
"get_db_conn": {"4009001", "取DB連線失敗"},
"gorm_pool_is_timeout": {"4009... |
/*
Package nappy implements a small REST HTTP server, including a pluggable resource database.
*/
package nappy
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
const pathPrefix = "/api/"
const lenPathPrefix = len(pathPrefix)
// Nappy server.
//
// Sample server usage:
//
// db := nappy.N... |
package kubernetes
import (
"time"
)
// PodEvent represents Pod termination event
type PodEvent struct {
Namespace string
PodName string
StartedAt time.Time
FinishedAt time.Time
ExitCode int
Reason string
Message string
}
// NotifyFunc represents callback function for Pod event
type NotifyFunc ... |
package library
import (
"bufio"
// "fmt"
"io"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
filepath string //your ini file path directory+file
conflist map[string]map[string]string //configuration information slice
}
var Configer = &Config{}
func (this *Config) Init(filepat... |
// Copyright (c) 2012 The Gocov Authors.
//
// 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 limitation the
// rights to use, copy, modify, merge, pub... |
/*
Package javascript implements JavaScript object macros for RiveScript.
This is powered by the Otto JavaScript engine[1], which is a JavaScript engine
written in pure Go. It is not the V8 engine used by Node, so expect possible
compatibility issues to arise.
Usage is simple. In your Golang code:
import (
rivesc... |
package tracks
import (
"encoding/json"
"errors"
"github.com/tainacleal/go-musixmatch"
)
// Client sets the Backend that implements BackendService and the API Key
type Client struct {
Backend musixmatch.BackendService
Key string
}
func getClient() Client {
return Client{Backend: musixmatch.GetBackend(), K... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"time"
)
type myCookieJar struct {
cookies []*http.Cookie
cookieUrl string
expireAt time.Time
}
func (m *myCookieJar) SetCookies() {
}
const (
ACCESS_KEY = "C2QcWBwdgB5XIPge... |
package mongodb
import (
"errors"
"pb/c2s"
"pb/s2c"
"server"
"server/libs/log"
"server/libs/rpc"
"server/share"
"sync/atomic"
"time"
"github.com/golang/protobuf/proto"
"gopkg.in/mgo.v2/bson"
)
type Account struct {
numprocess int32
queue []chan *rpc.RpcCall
quit bool
pools int
}
func ... |
package LetterRepository
import (
"MainApplication/internal/Letter/LetterModel"
"errors"
)
var DbError = errors.New("Data Base error!")
var ReceiverNotFound = errors.New("Receiver not found!")
var SaveLetterError = errors.New("Save letter error!")
var ReceivedLetterError = errors.New("Could not get received letter... |
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"reflect"
"strings"
"conor.co.za/vservices/golib/logger"
"github.com/gorilla/mux"
"github.com/gorilla/pat"
"github.com/jansemmelink/api"
"github.com/jansemmelink/auth3/auth"
"github.com/jansemmelink/sweeper"
)
var (
port = flag.Int("por... |
package service
import "bbs/internal/biz"
type UserRegister struct {
useCase biz.UserRegisterCase
}
func NewUserRegister(useCase biz.UserRegisterCase) *UserRegister {
return &UserRegister{
useCase,
}
}
func (ur *UserRegister) Register(register UserRegister) error {
bizUr := biz.UserRegister{}
_, err := ur.u... |
package calculations
import "testing"
func TestCoordinatesDistance(t *testing.T) {
type args struct {
lat1 float64
lon1 float64
lat2 float64
lon2 float64
}
tests := []struct {
name string
args args
want float64
wantErr bool
}{
{
name: "boston to harford",
args: args{lat1: 42.3601,... |
package main
import (
"flag"
"log"
"github.com/andywow/golang-lessons/lesson10/copyfile"
)
var (
fromFileName = flag.String("from", "", "source file")
toFileName = flag.String("to", "", "destionation file")
fromFileOffset = flag.Int("offset", 0, "source file offset")
fromFileBytes = flag.Int("limit", 0... |
package problem0343
import "testing"
func TestIntegerBreak(t *testing.T) {
t.Log(integerBreak(2))
t.Log(integerBreak(10))
}
|
package server
import (
"chlorine/apierror"
"log"
"net/http"
)
// MyPlaylistsHandler is a handler for user's personal playlists in Spotify
type MyPlaylistsHandler struct {
ExternalMusicHandler
}
func (h MyPlaylistsHandler) Get(w http.ResponseWriter, r *http.Request) {
session := h.InitSession(r)
jsonWriter := ... |
package leetcode
import "testing"
func TestKthLargestElementInAStream(t *testing.T) {
kth := Constructor(3, []int{4, 5, 8, 2})
if kth.Add(3) != 4 {
t.Fatal()
}
if kth.Add(5) != 5 {
t.Fatal()
}
if kth.Add(10) != 5 {
t.Fatal()
}
if kth.Add(9) != 8 {
t.Fatal()
}
if kth.Add(4) != 8 {
t.Fatal()
}
}
|
package xlog
type Severity int
const (
SevNone Severity = -1
SevEmergency Severity = iota
SevAlert
SevCritical
SevError
SevWarn
SevNotice
SevInfo
SevDebug
SevTrace
)
var severityString = map[Severity]string{
SevEmergency: "EMERGENCY", // EM EMR EMER
SevAlert: "ALERT", // AL ALR ALER
SevCrit... |
package main
import "fmt"
func passByValue(num int) {
num++
}
func passByReference(num *int) {
*num++
}
func main(){
i := 0
fmt.Println(i)
passByValue(i)
fmt.Println(i)
passByReference(&i)
fmt.Println(i, &i)
}
|
// Contains the model of the application data
package users
import (
"crypto/rand"
"errors"
"github.com/duo-labs/webauthn/protocol"
"github.com/duo-labs/webauthn/webauthn"
"github.com/go-pg/pg/v9/orm"
"golang.org/x/crypto/argon2"
"strconv"
"strings"
)
type User struct {
Id int64 `pg:",pk,unique"`
Email ... |
package repository
import (
"github.com/gofrs/uuid"
"gorm.io/gorm"
)
// initialize uuid generator which will be used as primary key generator
var _ = uuid.Must(uuid.NewV7())
type Db struct {
db *gorm.DB
}
func NewDb(db *gorm.DB) *Db {
return &Db{db: db}
}
|
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
ver1 := "5"
ver2 := "1"
if !strings.Contains(ver1, ".") && !strings.Contains(ver2, ".") {
num1, _ := strconv.Atoi(ver1)
num2, _ := strconv.Atoi(ver2)
if num1 > num2 {
fmt.Println("true")
return
}
}
ver1Arr := strings.Split(ver1, ... |
package fantasyfootball
import (
"fmt"
"sort"
)
type FantasyPlayer struct {
name string
// team
dsts []*FootballPlayer
ks []*FootballPlayer
qbs []*FootballPlayer
rbs []*FootballPlayer
tes []*FootballPlayer
wrs []*FootballPlayer
// needed for calculations
defaultRb *FootballPlayer
defaultWr *Foo... |
// time: O(n^2), space: O(1)
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
for i, c := range strs[0] {
for j := 1; j < len(strs); j++ {
if i >= len(strs[j]) || rune(strs[j][i]) != c {
return strs[0][0:i]
}
}
... |
package main
func main() {
x := 2.4
}
|
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package contracts
import (
"fmt"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/coretypes/coreutil"
"github.com/iotaledger/wasp/packages/hashing"
"sync"
)
const VMType = "examplevm"
var (
allExamples ... |
package ui
// TODO: Can start putting them here and break them off and move them to
// pacakges from here
var Symbols = map[string]map[string]string{
"status": map[string]string{
"info": "ℹ ",
"success": "✔ ",
"warning": "⚠ ",
"error": "✖ ",
},
"emoticons": map[string]string{
"sad": "☹",
"happy":... |
// Copyright 2018 Lars Hoogestraat
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"bytes"
"html/template"
"strings"
"github.com/microcosm-cc/bluemonday"
bf "github.com/russross/blackfriday/v2"
)
// ext Defines the extensions that ... |
// Package rhcos contains assets for RHCOS.
package rhcos
import (
"context"
"fmt"
"time"
"github.com/coreos/stream-metadata-go/arch"
"github.com/openshift/installer/pkg/asset"
"github.com/openshift/installer/pkg/asset/installconfig"
"github.com/openshift/installer/pkg/rhcos"
"github.com/openshift/installer/... |
package main
import "fmt"
func main() {
for x := 0; x < 10; x++ {
if x == 5 {
continue
}
fmt.Println(x, "meio do loop")
if x == 7 {
break
}
}
}
|
package bbir
import (
"context"
"sync"
"github.com/golang/sync/errgroup"
"github.com/vvatanabe/go-backlog/backlog/v2"
)
type IssueRepository interface {
FindIssueByKey(ctx context.Context, issueKey string) (*v2.Issue, error)
AddIssue(ctx context.Context, projectID ProjectID, summary string, issueTypeID IssueT... |
package main
import (
"bytes"
"os"
"strings"
"testing"
)
func TestPrintenv(t *testing.T) {
var buf bytes.Buffer
want := os.Environ()
printenv(&buf)
found := strings.Split(buf.String(), "\n")
for i, v := range want {
if v != found[i] {
t.Fatalf("want %s, got %s", v, found[i])
}
}
}
|
package data
import "fmt"
// Maxy is a type
type Maxy struct {
Planet string
Size int64
}
// CalcDistance measures distance from Earth
func (m *Maxy) CalcDistance() {
fmt.Println("It's too far")
}
|
package main
// Rule описывает правила для продукционной модели
type Rule struct {
Fact string
Goal string
}
// Парсинг файла с правилами
type fileRule struct {
Fact []string `json:"fact"`
Goal string `json:"goal"`
}
|
package pg
import (
"fmt"
"time"
"data-manager/types"
"grm-service/common"
. "grm-service/dbcentral/pg"
"grm-service/log"
. "grm-service/time"
"grm-service/util"
)
type MetaDB struct {
MetaCentralDB
}
// 获取数据类型
func (db MetaDB) GetDataType(data string) (string, error) {
sql := fmt.Sprintf(`select data_typ... |
package controllers
import (
"github.com/gin-gonic/gin"
)
func (this *TransactionController) Create(c *gin.Context) {
}
|
package main
import "sort"
/**
47. 全排列 II
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
```
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
```
*/
/**
看着就像回溯算法,就是没写出来
*/
func PermuteUnique(nums []int) (ans [][]int) {
sort.Ints(nums)
nl := len(nums)
var temp []int
visit := make([]bool, nl)
var dfs func(idx int)
dfs =... |
package list_algorithm
import (
"testing"
"github.com/influxdata/influxdb/pkg/testing/assert"
)
var nonLoopArray=[]int{1,2,3,4,5,6,7}
var loopArray=[]int{1,2,3,4,5,1,6,7}
func TestLinkedList_ValidIfLoop_False(t *testing.T) {
linkedList:=&LinkedList{}
for _,value:=range nonLoopArray{
linkedList.Push(value)
}
... |
package main
import (
"fmt"
"math"
)
func myAtoi(str string) int {
flag := 1 //代表正数
j := 0
for j < len(str) {
if str[j] == ' ' {
j++ //是空格就跳过
} else {
break
}
}
if str[j:] == "" { //去掉开头空格后字符串为空
return 0
}
if str[j] == '-' {
flag = -1 //负数
j++
} else if str[j] == '+' {
j++
}
num := 0
... |
// Package fetchall (go-fetchall.go) :
// This is a Golang library for running HTTP requests with the asynchronous process.
package fetchall
import (
"net/http"
"runtime"
"sort"
"sync"
)
const (
workerNumber = 5 // Default workers
)
// Params : Parameters for fetchAll.
type Params struct {
Cou... |
package utils
import "strings"
func TrimASCIIArt(s string) string {
lines := []string{}
for _, line := range strings.Split(s, "\n") {
line = strings.TrimSpace(line)
if 0 < len(line) {
lines = append(lines, line)
}
}
return strings.Join(lines, "\n")
}
|
package main
import (
"flag"
"fmt"
"math/rand"
"time"
)
var (
seed = flag.Int("seed", 0, "seed for random generator. unix(now) be default")
start = flag.Int("start", 1,"first rand operand")
end = flag.Int("end", 6,"second rand operand")
n = flag.Int("n", 1,"cnt")
norepeat = flag.Bool("norepeat", false,"must ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.