text stringlengths 11 4.05M |
|---|
package serve
import (
"io/ioutil"
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday"
)
func generateHtml(path string) (html []byte, err error) {
fileBytes, err := ioutil.ReadFile(path)
if err != nil {
return
}
unsafe := blackfriday.MarkdownCommon(fileBytes)
html = bluemonday.UGCPolicy(... |
// Copyright (c) OpenFaaS Author(s) 2018. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// API source - https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange
// Idea from Matthew Holt (@mholt6)
package function
import (
"crypto/... |
package plan
type Merge struct {
nodeBase
}
func (self *Merge) Children() []Node {
return self.nodeBase.Children
}
func (self *Merge) Accept(v Visitor, f *bool) {
v.OnMerge(self, f)
visitChildrenIfNeed(self, v, f)
}
type Project struct {
nodeBase
Columns []Node
}
func (self *Project) Children() []Node {
ret... |
package emoji
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/sairoutine/RenmeriMaker/server/constant"
"github.com/sairoutine/RenmeriMaker/server/model"
"github.com/sairoutine/RenmeriMaker/server/util"
"net/http"
)
func Add(c *gin.Context) {
db := c.MustGet("DB").(*gorm.DB)
novelId :=... |
package game
import (
"errors"
"github.com/golang/glog"
"github.com/noxue/utils/argsUtil"
"github.com/noxue/utils/fsm"
"qipai/dao"
"qipai/game/card"
"qipai/model"
"qipai/utils"
"time"
)
func StateSetScore(action fsm.ActionType, args ...interface{}) (nextState fsm.StateType) {
if action != SetScoreAction {
... |
package epaper
import (
"fmt"
"image"
"time"
"periph.io/x/periph/conn/gpio"
"periph.io/x/periph/conn/gpio/gpioreg"
"periph.io/x/periph/conn/physic"
"periph.io/x/periph/conn/spi"
"periph.io/x/periph/conn/spi/spireg"
"periph.io/x/periph/host"
)
// Epd is basic struc for Waveshare eps2in13bc
type Epd struct {
... |
package main
import "fmt"
func main() {
// รับค่า
fmt.Print("Input Your Number : ")
// ตัวแปร ชื่อ input รับค่าแบบทศนิยม
var input float64
// แสดงผลเป็นทศนิยม
fmt.Scanf("%f", &input)
output := input * 2
fmt.Println(output)
}
|
package main
import (
"database/sql"
"errors"
"fmt"
"log"
"net/http"
"os"
"sort"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/srinathgs/mysqlstore"
"golang.org/x/crypto/bcrypt"
_ "github.com/g... |
package JsonStructure
//******************************************************************************
/*
struct for User Request
*/
type QueryReqS struct {
Mdn string `json:"mdn"`
Dateofdeparture string `json:"dateofdeparture"`
Dateofarrival string `json:"dateofarrival"`
Source string `json:"source"`
Desti... |
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
)
const spotifyBaseUrl = "https://api.spotify.com"
const spotifyAuthUrl = "https://accounts.spotify.com/api/token"
const spotifyClientId = "867357abf03643fab0ee2cad0b8903f9"
func getSpotifyAuth(w http.ResponseWriter, r *http.Request) {
req, err := ht... |
package main
import (
"github.com/lavpthak/easysurvey/app/routes"
"github.com/lavpthak/easysurvey/app/routes/survey"
"github.com/labstack/echo"
)
func main() {
e := echo.New()
e.GET("/", routes.Index)
e.GET("/survey/all", survey.GetAll)
e.Logger.Fatal(e.Start(":8081"))
}
|
package util
// Pagination page
type Pagination struct {
PerPage int `json:"per_page"`
Page int `json:"page"`
TotalCount int `json:"total_count"`
PageCount int `json:"page_count"`
}
func InitPagination(totalCount, pageSize, page int) Pagination {
pageCount := totalCount / pageSize
if totalCount%pageSi... |
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os"
"runtime"
"strconv"
"strings"
"time"
)
// Object represents the row of the CSV as an object to use for writing and parsing data
type Object struct {
Discriminator string
Key string
Text string
}
// used to replace special chara... |
package server
import (
"FPproject/Backend/log"
"FPproject/Backend/models"
"net/http"
"github.com/gin-gonic/gin"
)
func (h *Handler) InsertFood(c *gin.Context) {
var body models.Food
err := c.BindJSON(&body)
if err != nil {
log.Info.Println(err)
c.JSON(http.StatusBadRequest, gin.H{
"status": "bad reque... |
package backend
import (
"encoding/json"
"errors"
"io/fs"
"os"
"strconv"
"strings"
"time"
)
const NO_SESSION_NUMBER = -1
// Represents a single note-taking session.
type Session struct {
Notes []Note // the collection of all notes created by the user
Date time.Time // the date and time t... |
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/troydai/blocks/echo/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
func main() {
conn, err := grpc.Dial("localhost:5436", grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("fail to dial tcp: %v", err)... |
package merkle
const (
// MaxBlockSize reasonable max byte size for blocks that are checksummed for
// a Node
MaxBlockSize = 1024 * 16
)
// DetermineBlockSize returns a reasonable block size to use, based on the
// provided size
func DetermineBlockSize(blockSize int) int {
var b = blockSize
for b > MaxBlockSize ... |
package rpc_user
import (
"github.com/bqxtt/book_online/rpc/model/userpb"
"google.golang.org/grpc"
"log"
)
var UserServiceClient userpb.UserServiceClient
const (
address = "localhost:50001"
//address = "101.200.155.166:30001"
)
func Init() {
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock(... |
package main
import "github.com/aelindeman/namedns/cmd"
func main() {
cmd.Execute()
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//389. Find the Difference
//Given two strings s and t which consist of only lowercase letters.
//String t is generated by random shuffling string s an... |
package routing
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"net"
"os/exec"
"regexp"
log "github.com/Sirupsen/logrus"
)
func InitBGPMonitoring(masterIface string) {
ethIface = masterIface
err := cleanExistingRoutes(ethIface)
if err != nil {
log.Infof("Error cleaning old routes: %s", err)
}... |
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type RangeFunction struct {
Lateral bool
Ordinality bool
IsRowsfrom bool
Functions *ast.List
Alias *Alias
Coldeflist *ast.List
}
func (n *RangeFunction) Pos() int {
return 0
}
|
package design
// "go generate ./..." to regenerate bindata!
//go:generate go run ./data-compiler png design generationX4 icon72 icon96 ripple circle192
// DesignScale is the current scale for the Design.
var DesignScale float64
// Setup sets the sizes, fonts and borders according to the given scale.
func Setup(scal... |
package cmd
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"github.com/spf13/cobra"
)
var SubArrayMaxSumCmd = &cobra.Command{
Use: "subArrayMaxSum",
Short: "Calculate maximum sub array sum",
Run: SubArrayMaxSum,
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func SubArrayMaxSum(cmd *co... |
package register
import (
"bufio"
"regexp"
"strconv"
"strings"
)
const (
pattern = `([a-z]+) (inc|dec) (-?[0-9]+) if ([a-z]+) ([<>=!]+) (-?[0-9]+)`
)
type condition func(map[string]int, string, int) bool
func gt(registry map[string]int, reg string, val int) bool {
return registry[reg] > val
}
func lt(registr... |
package transport
import (
"bytes"
"encoding/binary"
)
const (
FIN = 1 // 00 0001
SYN = 2 // 00 0010
RST = 4 // 00 0100
PSH = 8 // 00 1000
ACK = 16 // 01 0000
URG = 32 // 10 0000
)
type TCPHeader struct {
Source int //uint16
Destination int //uint16
SeqNum int //uint32
AckNum int //uin... |
package tests
import (
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/gomodule/redigo/redis"
"github.com/tidwall/gjson"
)
func subTestKeys(g *testGroup) {
g.regSubTest("BOUNDS", keys_BOUNDS_test)
g.regSubTest("DEL", keys_DEL_test)
g.regSubTest("DROP", keys_DROP_test)
g.regSubTest("RENAME", keys_R... |
package actions
import (
"github.com/barrydev/api-3h-shop/src/model"
)
func InsertProductItemByProductId(productId int64, body *model.BodyProductItem) (*model.ProductItem, error) {
body.ProductId = &productId
return InsertProductItem(body)
}
|
package easypost
// ShipmentOptions represents the various options that can be applied to a
// shipment at creation.
type ShipmentOptions struct {
AdditionalHandling bool `json:"additional_handling,omitempty"`
AddressValidationLevel string `json:"address_validation_level,omitempty"`
Alcohol ... |
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"os"
"runtime"
"strconv"
"strings"
"unicode"
"unicode/utf8"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"github.com/opencontainers/runtime-tools/generate/seccomp"
"github.com/urfave... |
package logic
import (
"encoding/json"
"reflect"
"testing"
"time"
)
func Test_UnmarshalJSON(t *testing.T) {
type args struct {
jsonString string
}
type output struct {
load inputLoad
hasError bool
}
tests := []struct {
name string
args args
want output
}{
{
name: "MarshallingOk",
arg... |
package main
import "fmt"
/* pointer (*) จะทำให้ฟังก์ชัน zero เปลี่ยนค่าเริ่มต้นของตัวแปรได้
เครื่องหมาย * จะตามด้วยประเภทของตัวแปรที่ถูกจัดเก็บ
*/
func zero(xPrt *int) {
// *xPrt เป็นการบอกว่า xPrt ชี้ไปที่ int เก็บค่า 0 ไว้ที่หน่วยความจำที่ xPrt อ้างถึงอยู่
*xPrt = 0
}
func main() {
x := 5
// ส่งตำแหน่งของ x เข... |
package explorerutils
import (
"bytes"
"fmt"
"log"
"os"
yaml "gopkg.in/yaml.v2"
)
type ExplorerServices struct {
Version string `yaml:"version"`
Volumes map[string]interface{} `yaml:"volumes"`
Networks map[string]Networks `yaml:"networks"`
Services map[string]ExplorerService... |
package main
import (
"adventofcode-solutions/2018/readinput"
"fmt"
)
// Part1 should calculate the multiplication of amount of string that has 2 repetitions and 3 repetitions
func Part1(input []string) int {
var numberOfTwices = 0
var numberOfTripples = 0
for _, line := range input {
occurrences := make(map[... |
package main
import (
"testing"
)
func TestReverseWords(t *testing.T) {
}
|
package http_handlers
import (
"fmt"
"github.com/go-martini/martini"
"net/http"
"project/models"
"runtime/debug"
)
const (
AUTH_REQUIRED = "auth_required"
CACHE_REQUIRED = "cache_required"
DOCUMENT_REQUIRED = "document_required"
IGNORE_PAYLOAD = "igno... |
//////////////////////////////////////////////////////////////////////////////////////////////
//
// Usage: go run AQMstat.go
//
// Summary: This program was written for use to statistically compare modeled and
// measured values of ambient air pollutants.
// Data time range: Jan-01-2005 through Dec-31-2005
// IS... |
package mysql
import (
"database/sql"
_ "github.com/go-sql-driver/mysql" // dbDriver
)
// DBConn dataSourceName : "user:pwd@host:port/databasename"
func DBConn(dataSourceName string) (db *sql.DB) {
dbDriver := "mysql" // Database driver
// Realize the connection with mysql driver
db, err := sql.Open(dbDriver,... |
package main
import (
"context"
"github.com/ktsstudio/selectel-exporter/pkg/config"
"github.com/ktsstudio/selectel-exporter/pkg/exporter"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
exporterConfig, err := config.Parse()
if err != nil ... |
package model
import (
"sync"
"net"
)
type Device struct{
Uuid string
Imei string
Conn net.Conn
}
type UserCache struct{
sync.RWMutex
cache map[string] *Device
}
func (cache *UserCache) Init(){
cache.cache = make(map[string] *Device)
}
func (cache *UserCache) Add(uuid string, device *Device){
cache.Lock()... |
package internal
import (
"github.com/hashicorp/go-plugin"
)
func NewHandshakeConfig(pluginType string) plugin.HandshakeConfig {
return plugin.HandshakeConfig{
ProtocolVersion: 1,
MagicCookieKey: "gatekeeper|plugin-type",
MagicCookieValue: pluginType,
}
}
|
package template
import (
"bytes"
"fmt"
"path/filepath"
"text/template"
"github.com/criteo/graphite-remote-adapter/ui"
)
func getTemplate(name string) (string, error) {
baseTmpl, err := ui.Asset("templates/_base.html")
if err != nil {
return "", fmt.Errorf("error reading base template: %s", err)
}
pageTmp... |
package main
import (
"errors"
"log"
)
type WithdrawCommand interface {
Execute() error
Undo() error
Redo() error
}
type CommandManager struct {
UndoCommand []WithdrawCommand
RedoCommand []WithdrawCommand
}
func NewCommandManager() CommandManager{
return CommandManager{
UndoCommand:make([]WithdrawCommand,... |
package util
import (
"math"
"path"
"runtime"
"sync"
"time"
"github.com/OopsMouse/arbitgo/models"
"github.com/jpillora/backoff"
log "github.com/sirupsen/logrus"
)
func Index(vs []string, t string) int {
for i, v := range vs {
if v == t {
return i
}
}
return -1
}
func Include(vs []string, t string)... |
package persistence
import (
"fmt"
"os"
"strings"
)
var (
filename string
)
func RequestFilename() string {
fmt.Printf("Please, insert the path for the file to load:\n")
var msg string
fmt.Scanf("%s\n", &msg)
return msg
}
func ObtainSelectionList(filename string) []string {
var content string = ""... |
package zhlog
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/connext-cs/pub/paasdb"
"github.com/go-xorm/xorm"
)
// SLog 日志表
type SLog struct {
LogId int `json:"log_id"` //日志ID
LogResId int `json:"log_res_id"` //资源ID
LogResName string `json:"log_res_name"... |
// Copyright (c) 2017 Intel Corporation
//
// 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 ag... |
package ant
import (
"bufio"
"fmt"
"io"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
func (e *Env) newAnt(pos int) *Ant {
ant := new(Ant)
ant.env = e
ant.visited = make([][]int, len(e.weight))
for i := 0; i < len(e.weight); i++ {
ant.visited[i] = make([]int, len(e.weight))
for j := 0; j < le... |
package mock
import (
"context"
"github.com/google/uuid"
"github.com/odpf/optimus/job"
"github.com/odpf/optimus/core/tree"
"github.com/odpf/optimus/core/progress"
"github.com/odpf/optimus/models"
"github.com/odpf/optimus/store"
"github.com/odpf/optimus/store/local"
"github.com/stretchr/testify/mock"
)
//... |
package test
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
"testing"
// account "github.com/cloudfly/ecenter/pkg/account"
"github.com/cloudfly/ecenter/pkg/store"
"github.com/stretchr/testify/require"
)
var (
addr = "127.0.0.1:3306"
user = "root"
password = "123456"
t... |
package main
func main() {
}
func smallestEvenMultiple(n int) int {
if n%2 == 0 {
return n
}
return n * 2
}
|
package record
import (
"sync"
"sync/atomic"
"context"
"gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse"
"gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse/fs"
)
// Writes gathers data from FUSE Write calls.
type Writes struct {
buf Buffer
}
var _ = fs.HandleWriter(&Writes{})
func (w *W... |
package main
import "fmt"
// init 函数可以用来初始化,在 main 函数之前调用,任何一个源文件都可以包含 init 函数
func init() {
fmt.Println("init1...")
}
func init() {
fmt.Println("init2...")
}
func main() {
fmt.Println("main...")
}
/**
对于导包,变量定义,init 函数,main 函数,执行流程:
包文件变量定义-->包文件 init 函数---> main 文件变量定义---> main 文件 init 函数---> main 文件 main 函数... |
// +build integration
package keepalived
import (
"context"
"testing"
"time"
corev2 "github.com/sensu/sensu-go/api/core/v2"
"github.com/sensu/sensu-go/backend/etcd"
"github.com/sensu/sensu-go/backend/liveness"
"github.com/sensu/sensu-go/backend/messaging"
"github.com/sensu/sensu-go/backend/seeds"
"github.co... |
package data
import (
"github.com/souhub/wecircles/pkg/logging"
)
type Chat struct {
ID int
Body string
UserID int
UserIdStr string
UserImagePath string
CircleID int
CircleOwnerIDStr string
CreatedAt string
}
// Get all of the chats
func GetChats(... |
package server
import (
"net"
)
type Client struct{
Id string `json:"id"`
Connection net.Conn `json:"-"`
ChunkServers []ChunkServer `json:"-"`
}
|
package model
import (
"strconv"
"strings"
)
func NumDecPlaces(v float64) int64 {
s := strconv.FormatFloat(v, 'f', -1, 64)
i := strings.IndexByte(s, '.')
if i > -1 {
return int64(len(s) - i - 1)
}
return 0
}
|
/*
Copyright (C) 2018 Synopsys, Inc.
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
"... |
package controller
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"model"
"net/http"
"strconv"
)
/* handler function for GET method */
var SelectUsers = func(w http.ResponseWriter, r *http.Request) {
users := []model.User{}
err := GetDB().Table("users").Find(&users).Error
if err != nil {
msg := ma... |
// Copyright 2018 Andrew Bates
//
// 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 wri... |
package main
import "fmt"
type Problem21B struct {
Log bool;
}
func (this *Problem21B) Solve() {
Log.Info("Problem 21B solver beginning!");
this.Log = false;
system := &PasswordSwapSystem{};
// Note - the naive search approach is maybe not the intended way to solve this problem, but its fast enough < 10s to b... |
/*
Copyright 2015 Crunchy Data Solutions, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
/*
go get -u github.com/tidwall/gjson
go get -u github.com/go-sql-driver/mysql
*/
package main
import (
"os"
"fmt"
"./package/http"
)
func main() {
fmt.Print("【HTTP开放接口】服务器")
arg_num := len(os.Args)
if false {
fmt.Printf("\nthe num of input is %d", arg_num)
}
http.ListenAndServ... |
package transdsl
type Specification interface {
Ok(transInfo *TransInfo) bool
}
type Not struct {
Spec Specification
}
func (this *Not) Ok(transInfo *TransInfo) bool {
return !this.Spec.Ok(transInfo)
}
type AllOf struct {
Specs []Specification
}
func (this *AllOf) Ok(transInfo *TransInfo) bool {
for _, spec :... |
package main
import "fmt"
func main() {
student_1 := "Goku"
student_2 := "Gohan"
student_3 := "Vegeta"
student_4 := "Piccolo"
student_5 := "Krillin"
student_6 := "Yamcha"
student_7 := "Bluma"
student_8 := "Videl"
student_9 := "Oolang"
student_10 := "Puar"
fmt.Println(student_1, student_2, student_3, stude... |
package main
import (
"crypto/hmac"
"crypto/sha512"
"database/sql"
"encoding/base64"
"flag"
"fmt"
"log"
"net"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/adhocteam/soapbox"
"github.com/adhocteam/soapbox/buildinfo"
pb "github.com/adhocteam/soapbox/proto"
"github.com/adhocteam/soapbox/soapbox... |
package main
import (
"github.com/ActiveState/log"
"github.com/ActiveState/logyard-apps/applog_endpoint"
"github.com/ActiveState/logyard-apps/applog_endpoint/config"
"github.com/ActiveState/logyard-apps/applog_endpoint/drain"
)
func main() {
config.LoadConfig()
drain.RemoveOrphanedDrains()
applog_endpoint.Rou... |
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
// const INF int = 1000000
var sc = bufio.NewScanner(os.Stdin)
func nextInt() int {
sc.Scan()
i, e := strconv.Atoi(sc.Text())
if e != nil {
panic(e)
}
return i
}
func main() {
sc.Split(bufio.ScanWords)
n := nextInt()
k := nextInt()
list :=... |
package db
import (
"database/sql"
"io/ioutil"
"log"
)
func Migrate() {
con, err := sql.Open("mysql", "root:@/php_datebase")
defer con.Close()
if err != nil {
panic(err)
}
b, err := ioutil.ReadFile("./db/migration.sql")
if err != nil {
log.Fatal(err)
}
//for _, q := range strings.Split(string(b),";"... |
package main
import "net/http"
func (a *apiServer) routes() {
// C
// s.router.POST("/payments")
// R
a.router.HandleFunc("/payments", a.GET(a.handleGetSinglePayment()))
// s.router.GET("/payments", nil)
// U
// s.router.PUT("/payments", nil)
// D
// s.router.DELETE("/payments", nil)
//.HandleFunc("/api... |
package sp
import (
"bytes"
"errors"
"fmt"
"regexp"
"regexp/syntax"
"strconv"
"strings"
"time"
)
// DataType represents the primitive data types available in InfluxQL.
type DataType int
const (
// Unknown primitive data type.
Unknown DataType = 0
// Float means the data type is a float
Float = 1
// Inte... |
/*
Copyright (c) 2015 Antonin Amand <antonin.amand@gmail.com>, All rights reserved.
See LICENSE file or http://www.opensource.org/licenses/BSD-3-Clause.
*/
// Package server provides utilities to run celery workers.
package server
import (
"os"
"os/signal"
"time"
"github.com/efimbakulin/celery"
"github.com/efim... |
package main
import "fmt"
func main() {
// เรียกใช้ฟังก์ชัน
// x คือ ข้อความที่เก็บไว้ในพารามิเตอร์(str)
showString("x")
// 10,20 คือ ข้อมูลที่เก็บไว้ในพารามิเตอร์ (a,b)
addition(10, 20)
empty()
// ตัวแปร result เก็บค่าจาก function addition2(5, 5)
// 5+5 = 10 การบวกมาจากใน function
// 10 * 10 = 100
result... |
package store
import (
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/zwj186/alog/log"
)
type _FileConfig struct {
Size int64
Path string
RetainDay int
GCInterval time.Duration
ChildTmpl *template.Template
NameTmpl *template.Template
TimeTmpl *template.Templat... |
package query
import (
"fmt"
"time"
"github.com/EverythingMe/meduza/errors"
)
// Query is just the commmon interface for all queries.
// They must validate themselves
type Query interface {
Validate() error
}
type Ordering struct {
By string `bson:"by"`
Ascending bool `bson:"asc"`
}
var NoOrder = Or... |
package processlink
import (
"learn_go/dataStruct/linkstruct"
"learn_go/datastruct/stacks"
)
var (
head = linkstruct.New(0)
)
// CreateSingleLink 创建一个新链表
func CreateSingleLink() *linkstruct.LinkNode {
head := linkstruct.New(0)
head.Append(1)
head.Append(2)
head.Append(4)
head.Append(5)
head.Append(6)
retur... |
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println("Make file generator for Golang (xgo)")
reader := bufio.NewReader(os.Stdin)
fmt.Print("\nWorking golang directory: ")
wdir, _ := reader.ReadString('\n')
wdir = normalize(wdir)
fmt.Print("Build output directory: ")
bdir, _ := rea... |
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
var wg sync.WaitGroup
ch := make(chan int, 100)
chSend := make(chan int)
chConsume := make(chan int)
sc := make(chan os.Signal, 1)
signal.Notify(sc,
os.Kill,
os.Interrupt,
syscall.SIGHUP,
syscall.SIGINT,
sysca... |
package client
var (
KEY_MATERIAL = "material"
KEY_UNIT = "unit"
KEY_QUANTIFIERS = "quantifiers"
KEY_QUESTION = "question"
KEY_VERB = "verb"
KEY_NUMERIC = "numeric"
KEY_ROMAN = "roman"
KEY_CREDIT = "credit"
KEY_MARK = "mark"
regexPatternSourceWord = map[string]strin... |
package golayout
import (
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
func CreateFileIncludeDir(fp string) (*os.File, error) {
dir := filepath.Dir(fp)
isExist, err := Exists(dir)
if err != nil {
return nil, err
}
if !isExist {
log.Infof("Create sub directory %s", dir)
if err := os.MkdirAll... |
package main
import (
"flag"
"strings"
"github.com/rpcx-ecosystem/agent"
)
var (
addr = flag.String("addr", ":9981", "listen address")
registry = flag.String("reg", "", "注册中心类型,支持direct,multi,zookeeper,etcdv3,consul等类型")
opts = flag.String("opts", "", "所需参数,不同的注册中心需要不同的参数,参数以空格分隔")
)
func main() {
f... |
package console
import (
"fmt"
"io"
)
// A SimpleConsole represents a Logger implementation for simple shell sessions
type SimpleConsole struct {
out io.Writer
}
// NewSimpleConsole returns a new SimpleConsole with the given writer
func NewSimpleConsole(w io.Writer) *SimpleConsole {
return &SimpleConsole{
out:... |
package impl
import (
"bitbucket.org/waas_pro/api/models/entity"
"bitbucket.org/waas_pro/api/views"
"bitbucket.org/waas_pro/common/constants"
"bitbucket.org/waas_pro/errorhandling"
"github.com/jinzhu/gorm"
"time"
)
var (
walletLogTag = "wallets_impl.go" + "(" + packageTag + ")"
)
func ValidateWallet(db *gorm.D... |
package hunter
import (
"sync/atomic"
"time"
"github.com/lucky-loki/bounty"
)
type goWorker struct {
taskQueue chan bounty.Job
jobCount int64
size int
status int64
active time.Time // last active time
}
// NewGoWorker return a go routine worker
func NewGoWorker(size int) Worker {
if size <= 0 {... |
package redis
import (
"fmt"
"github.com/garyburd/redigo/redis"
"strconv"
"time"
)
type Redis struct {
RedisIp string
RedisPort int
ExpireTime int
RedisPool *redis.Pool
}
func GetRedis(RedisIp string, RedisPort int, ExpireTime int) *Redis {
var redis Redis
redis.RedisIp = RedisIp
redis.RedisPort = RedisPo... |
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"ms/sun/shared/helper"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// Action represents a row from 'sun.action'.
//... |
package arriba
import (
"testing"
)
func TestGetFunctions(*testing.T) {
GetFunctions(html1)
}
const html1 = (`
<!DOCTYPE html>
<html>
<head >
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Home</title>
</head>
<body>
<div data-lift="surround?with=default;at=content">... |
package site
import (
"time"
"github.com/valyala/fasthttp"
)
// Site handler
type Site struct {
timeout time.Duration
}
// GetDatа function for get data from url
func (s *Site) GetDatа(url string) (data []byte, err error) {
_, data, err = fasthttp.GetTimeout(nil, url, s.timeout)
return
}
// NewSite constructo... |
package main
import (
"net/http"
"net/url"
"os"
)
func main() {
if len(os.Args) != 2 {
panic("Bad Arguments")
}
url, err := url.Parse(os.Args[1])
if err != nil {
panic(err)
}
url.Scheme = "https"
http.ListenAndServe("0.0.0.0:8080", http.RedirectHandler(url.String(), 301))
}
|
package main
import (
"LanguageBotService/grpcUtil"
"LanguageBotService/wordgen"
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"log"
"net"
"os"
)
func Init(){
PORT := os.Getenv("PORT")
TcpAddress := os.Getenv("TCP_ADDRESS")
lis, err := net.Listen("tcp", TcpAddress + PORT)
if err != nil{
lo... |
package main
import (
"flag"
"fmt"
"net/http"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
func main() {
// server port
ServerPort := flag.String("server-port", ":8084", "server port")
//database connection
DBHost := flag.String("db-host", "localhost", "db host")
DBPort := flag.Int("db-port", 5432, "... |
package controllers
import (
"context"
// "log"
// tspb "github.com/golang/protobuf/ptypes/timestamp"
pb "github.com/growlog/rpc/protos"
)
func (s *ThingServer) SetSensor(ctx context.Context, in *pb.SetSensorRequest) (*pb.SetSensorResponse, error) {
return &pb.SetSensorResponse{
Message: "Sensor was created"... |
package obs
import "errors"
// TracerConfig stores tracer configuration.
type TracerConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
ZipkinURL string `json:"zipkin-url" yaml:"zipkin-url"`
}
// SetDefault sets sane default for tracer's config.
func (c *TracerConfig) SetDefault() {
c.Enabled = fa... |
package avail
import (
"context"
"sync/atomic"
"time"
"github.com/XiaoMi/pegasus-go-client/pegasus"
log "github.com/sirupsen/logrus"
)
// Detector periodically checks the service availability of the Pegasus cluster.
type Detector interface {
// Start detection until the ctx cancelled. This method will block t... |
package models
import (
"time"
)
type UserFavoriteItem struct {
UserID uint64 `json:"user_id" gorm:"column:user_id;primary_key" sql:"not null;type:bigint(20);index:idx_fav_user_id_item_id"`
ItemID uint64 `json:"item_id" gorm:"column:item_id;primary_key" sql:"not null;type:bigint(20);index:idx_fav... |
/*
Goal:
The goal of this challenge is to take a simple 6 row by 6 column XML file (without the standard XML header) and parse it out so that the program can return the value of a cell given it's coordinates.
The entry with the shortest overall length by language and overall will be declared the winner.
Additional ... |
package trea
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01300101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:trea.013.001.01 Document"`
Message *WithdrawalNotificationV01 `xml:"WdrwlNtfctnV01"`
}
func (d *Document01300101) ... |
package client
import (
"context"
"fmt"
"github.com/wish/ctl/pkg/client/types"
batchv1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"time"
)
// RunCronJob creates a new job with timestamp from the specified cron job template
func (c *Client) RunCronJob(contexts []string, namespace, cronjo... |
package paths
import (
"testing"
"github.com/criteo/graphite-remote-adapter/client/graphite/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/require"
yaml "gopkg.in/yaml.v2"
)
var (
metric = model.Metric{
model.MetricNameLabel: "test:metric",
"testlabel": "test:value",
... |
package main
import "fmt"
func main() {
fmt.Println("Aprendiendo Go Lang de nuevo!")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.