text
stringlengths
11
4.05M
package main import ( "fmt" "math" "math/rand" ) var count int = 0 func addition(a [][]float64, b [][]float64) [][]float64 { m := float(len(a[0])) // s := int(math.Pow(m, 2)) c := make([][]float64, int(math.Pow(m, 2))) for i := range c { c[i] = make([]float64, int(math.Pow(m, 2))) } for i := 0; i ...
package main import ( "bufio" "fmt" "log" "net" "os" ) var PORT = "8080" func main() { conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%s", PORT)) if err != nil{ log.Println("Connect error: ", err.Error()) } for { in := bufio.NewReader(os.Stdin) fmt.Printf("Write your text:\n") msg,_ := in.ReadS...
/* Copyright 2022 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...
package pkg // job指每个用户下载的任务作为一个job或者自己的上传任务作为job. // 用于以Pkg为单位的上传或者下载状态的跟踪和记录 import ( "./../transfer/task" "./models" "cydex" "cydex/transfer" "fmt" clog "github.com/cihub/seelog" "sync" "time" ) const ( // JD数据同步进数据库的间隔 // DEFAULT_CACHE_SYNC_TIMEOUT = 30 * time.Second DEFAULT_CACHE_SYNC_TIMEOUT = 0 //...
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the ele that it will be usef...
// Unit tests for file implementation of item repository. // // @author TSS package file import ( "testing" "github.com/mashmb/1pass/1pass-core/core/domain" ) func setupFileItemRepo() *fileItemRepo { vault := domain.NewVault("../../../assets/onepassword_data") repo := NewFileItemRepo() items := make([]*domain....
/****************************************************************************** Handler library based on Gorilla Just add routes with their respective handlers This file contains all the database related functions. ******************************************************************************/ package handlers imp...
package main import ( "fmt" ) func main() { var ptr *int var i int = 123 ptr = &i fmt.Println("Address of i:", &i) fmt.Println("Value of ptr (address of i)", ptr) fmt.Println("Value of i:", i) fmt.Println("Value of i via pointer:", *ptr) *ptr = 999 fmt.Println("Value of i via pointer", i) }
package controller import ( "math" ) type gridParams struct { xmin,ymin,xmax,ymax float64 xN, yN int } func NewGridParams(xmin,ymin,xmax,ymax float64, xN, yN int) *gridParams { return &gridParams{xmin: xmin,ymin: ymin,xmax: xmax,ymax: ymax, xN: xN, yN: yN} } func (params *gridParams) dx() float64 { return (par...
package bitfinex_websocket import ( "fmt" "github.com/gorilla/websocket" "os" "time" ) type Bitfinex interface { //ping Ping() // connect WsConnect() // subscribe Subscribe() // read message ReadMessage() // tick BFTickWebsocket() // depth BFDepthWebsocket() // trade BFTradeWebsocket() // kline BF...
/* Copyright IBM Corporation 2020 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 di...
// Support the Gherkin language, as found in Ruby's Cucumber and Python's Lettuce projects. package gherkin import "io" import matchers "github.com/tychofreeman/go-matchers" // Static Runner object to make creating tests easier var DefaultRunner = CreateRunner() // Use this function to let the user know that this //...
package powervs_test import ( "fmt" "os" "testing" "github.com/IBM-Cloud/power-go-client/power/models" "github.com/IBM/vpc-go-sdk/vpcv1" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/p...
package ip import ( "net" ) func IP() string { ips := []string(nil) is, err := net.Interfaces() if err != nil || len(is) == 0 { return "" } for _, i := range is { if len(i.HardwareAddr) == 0 { continue } as, err := i.Addrs() if err != nil { continue } for _, a := range as { ip, ok := a....
package server import ( "github.com/kelseyhightower/envconfig" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/vgarvardt/rklotz/pkg/server/plugin" "github.com/vgarvardt/rklotz/pkg/server/renderer" "github.com/vgarvardt/rklotz/pkg/server/web" ) // Config represents server configuration type Config struc...
package _142_Linked_List_Cycle_2 /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func detectCycle(head *ListNode) *ListNode { return detectCycleWithPointer(head) } func detectCycleWithPointer(head *ListNode) *ListNode { var ( hhead = &ListNode{ ...
// 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 i...
package info import ( "fmt" grpc "github.com/antonioalfa22/egida/proto" googlegrpc "google.golang.org/grpc" "log" ) func CreateServicesClient(host string) grpc.ServicesClient { addr := fmt.Sprintf("%s:%s", host, "8128") conn, err := googlegrpc.Dial(addr, googlegrpc.WithInsecure()) if err != nil { log.Fatalf(...
package main import "fmt" type person struct { fName string lName string favfood []string } func main() { p1 := person{ fName: "Sirop", lName: "Lesperance", favfood: []string{"Katofel", "currywurst", "ketchup"}, } // print out the p1 fmt.Println(p1) // print out the values in favfood fmt.Pri...
package main import ( "context" "errors" "fmt" "github.com/amisevsk/workspace-bootstrap/library" "log" "os" "strings" "time" devworkspace "github.com/devfile/api/pkg/apis/workspaces/v1alpha2" k8sclient "sigs.k8s.io/controller-runtime/pkg/client" ) const ( repoDevfileEnvVar = "DEVFILE" defaultDevfileEn...
package main import ( "fmt" "strconv" ) var numero int var texto string var status bool func main() { // Go las inicializa automaticamente en 0 var num1, num2 int num3, num4 := 2, "Texto" num5, num6 := 56, 33 fmt.Println("Hello World") numer := 3 fmt.Println(num1) fmt.Println(num2) fmt.Println(num3) fmt....
/* RZFeeser | Alta3 Research HTTP GET with io.Copy() */ package main import ( "io" "log" "net/http" "os" ) func main() { resp, err := http.Get("http://webcode.me") if err != nil { log.Fatal(err) } defer resp.Body.Close() /* The io.Copy() function copies fr...
package repository import ( . "2019_2_IBAT/pkg/pkg/models" "fmt" "github.com/google/uuid" "github.com/pkg/errors" ) func (m *DBUserStorage) CreateSeeker(seekerInput Seeker) bool { // salt := make([]byte, 8) // rand.Read(salt) // seekerInput.Password = string(passwords.HashPass(salt, seekerInput.Password)) ...
package main import ( "fmt" "net/http" "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.Use(cors.New( cors.Config{ AllowOrigins: []string{"http://localhost:8888"}, AllowMethods: []string{"POST"}, AllowHeaders: []string{"Orig...
package dependencyinjection import ( "log" "net/http" ) func MyGreeterHandler(w http.ResponseWriter, r *http.Request) { OtherGreet(w, "world") } func main() { log.Fatal(http.ListenAndServe(":5000", http.HandlerFunc(MyGreeterHandler))) }
package main import ( "fmt" "gopkg.in/vinxi/replay.v0" "gopkg.in/vinxi/vinxi.v0" "net/http" ) func main() { vs := vinxi.NewServer(vinxi.ServerOptions{Host: "localhost", Port: 3100}) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Printf("Replay server reached: %s => %s\n", r.Re...
package wallet import ( "crypto/ecdsa" "log" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" "golang.org/x/crypto/sha3" ) func GeneratePrivateKey() *ecdsa.PrivateKey { privateKey, err := crypto.GenerateKey() if err != nil { log.Fatal("error generating private key", ...
package _137_Single_Number_2 const Times = 3 func singleNumber(nums []int) int { //return singleNumberWithCalcu(nums) return singleNumberWithBit(nums) } // 位运算解法 func singleNumberWithBit(nums []int) int { a, b := 0, 0 for _, num := range nums { a = (a ^ num) & ^b b = (^a ^ num) ^ b } return a } // 算术求和解法,...
/* Copyright 2019 The Kubernetes 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, ...
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 package wasmlib import "encoding/binary" const ( // all TYPE_* values should exactly match the counterpart OBJTYPE_* values on the host! TYPE_ARRAY int32 = 0x20 TYPE_ADDRESS int32 = 1 TYPE_AGENT_ID int32 = 2 TYPE_BYTES int32 = ...
package main import( "conn" ) func main(){ conn.NewTcpServer("0.0.0.0", 55555) }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/12/28 8:51 上午 # @File : lt_38_外观数列.go # @Description : # @Attention : */ package hot100 import ( "strconv" "strings" ) /* n=5的时候: 1 11 21 1211 111221 一步一步来 给一个数,这个数是1 描述上一步的数,这个数是 1 即一个1,故写作11 描述上一步的数,这个数是11即两个1,故写作21 描述上一步的数,这个数是21即一个2一个1,故写作12-11 描述上一步的数...
package controllers import ( "github.com/insisthzr/echo-test/cookbook/twitter/models" "github.com/insisthzr/echo-test/cookbook/twitter/utils" "github.com/dgrijalva/jwt-go" "github.com/labstack/echo" "gopkg.in/mgo.v2/bson" ) func Signup(c echo.Context) error { user := new(models.User) err := c.Bind(user) if e...
package mars import ( "math/rand" "sort" ) type ( opcode int8 addressMode int8 instructionModifier int8 ) const ( insnDAT opcode = iota insnMOV insnADD insnSUB insnJMP insnJMZ insnDJN insnCMP insnSPL ) const ( addrIMMEDIATE addressMode = iota addrRELATIVE addrINDIRECT addrDECR...
package problems func checkIfExist(arr []int) bool { var set = make(map[int]bool) for _, n := range arr { if set[n*2] { return true } if n%2 == 0 && set[n/2] { return true } set[n] = true } return false }
package handler import ( "backend-github-trending/log" "backend-github-trending/model" req "backend-github-trending/model/req" "backend-github-trending/repository" "github.com/dgrijalva/jwt-go" "github.com/google/uuid" "github.com/labstack/echo/v4" "net/http" "strings" ) type RepoHandler struct { GithubRepo...
package main import "fmt" type BasicColor struct { R float32 G float32 B float32 } type Color struct { Basic BasicColor Alpha float32 } func main() { var c Color c.Basic.R = 1 c.Basic.G = 1 c.Basic.B = 0 c.Alpha = 1 fmt.Printf("%+v", c) }
package release import ( "encoding/json" "fmt" "html/template" "github.com/bosh-io/web/ui/nav" bprel "github.com/cppforlife/bosh-provisioner/release" semiver "github.com/cppforlife/go-semi-semantic/version" "github.com/microcosm-cc/bluemonday" "github.com/russross/blackfriday" bhrelsrepo "github.com/bosh-io...
package main import ( "flag" "fmt" "os" log "github.com/Sirupsen/logrus" "github.com/gin-gonic/gin" ) var argDebug = flag.Bool("debug", false, "run in debug mode") var argLogJSON = flag.Bool("logjson", false, "output log in JSON format") // Info is the info logger var Info *log.Logger // Error is the error lo...
package main func main() { } func makeSmallestPalindrome(s string) string { bs := []byte(s) for left, right := 0, len(s)-1; left < right; left, right = left+1, right-1 { if bs[left] != bs[right] { if bs[left] < bs[right] { bs[right] = bs[left] } else { bs[left] = bs[right] } } } return strin...
package adutils import ( "fmt" "log" "os" "strconv" "time" ) // exists returns whether the given file or directory exists or not func Exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } //delete ...
package main import ( "encoding/json" "fmt" "log" "net/http" ) func main() { resp, err := http.Get("http://httpbin.org/html") if err != nil { log.Fatal(err) } defer resp.Body.Close() result := make(map[string]interface{}) dec := json.NewDecoder(resp.Body) if err := dec.Decode(&result); err != nil { lo...
package trie import ( "testing" "github.com/gioui/uax/internal/tracing" ) func TestEnterSimple(t *testing.T) { tracing.SetTestingLog(t) // trie, _ := NewTinyHashTrie(139, 46) p1 := trie.AllocPositionForWord([]byte{13, 20}) t.Logf("p=%d", p1) p2 := trie.AllocPositionForWord([]byte{13, 21}) t.Logf("p=%d", p2)...
package main import ( "encoding/json" "github.com/valyala/fasthttp" ) // GetItems will return our items object func GetItems(ctx *fasthttp.RequestCtx) { enc := json.NewEncoder(ctx) items := ReadItems() enc.Encode(&items) ctx.SetStatusCode(fasthttp.StatusOK) } // AddItems modifies our array func AddItems(ctx *...
package tbhandler import ( "fmt" "io/ioutil" "os" "regexp" "strings" "github.com/narrowizard/tinysql" ) var isNeedImport bool // CreateModelAll 生成一个数据库的所有表结构 // dbName: 数据库名 func CreateModelAll(dbName string) { dbName = strings.Trim(dbName, " ") var tbVal = getAllTable(dbName) var val = strings.Split(tbV...
package main wss import ( "fmt" "keepassapi/handler" "keepassapi/helper" "net/http" "os" "github.com/gorilla/mux" ) func main() { var port string if len(os.Args) >= 3 { port = os.Args[1] helper.Keepassdbpath = os.Args[2] } else { port = os.Getenv("KEEPASS_PORT") helper.Keepassdbpath = os.Getenv("KEEP...
package controllers import ( "golang.org/x/crypto/bcrypt" "github.com/revel/revel" "goblog/app/models" ) type User struct { App } func (c User) CheckUser() revel.Result { switch c.MethodName { case "Login", "CreateSession": return nil } if c.CurrentUser == nil { c.Flash.Error("Please log in first") re...
/* * * pk.go * schemas * * Created by lintao on 2020/5/18 3:39 下午 * Copyright © 2020-2020 LINTAO. All rights reserved. * */ package schemas import ( "bytes" "encoding/gob" "github.com/5xxxx/pie/utils" ) type PK []interface{} func NewPK(pks ...interface{}) *PK { p := PK(pks) return &p } func (p *PK) I...
// 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...
// +build !release,!nodebug package errutil import ( "fmt" "testing" ) func TestBug(t *testing.T) { format := "horrendous error %d %d" data := []interface{}{5, 7} err := recovered(func() { Bug(format, data...) }) if err == nil { t.Fatal("expected Bug() to happen, but it hasn't") } if want, got := fmt.Spr...
package tkapi //淘抢购api import ( "bytes" "encoding/json" "errors" "github.com/mrxiaojie/taobaoke" ) type JuTqg struct { ReqParam JuTqgParam } //请求参数 type JuTqgParam struct { AdZoneId int Fields string StartTime string EndTime string PageNo int PageSize int } //初始化api func (t *JuTqg) Init() { t.ReqParam...
package main import "fmt" func main() { return fmt.Println("hello") } //return //return 使用在方法或者函数中,表示跳出所在方法或函数,用在main函数中表示,结束运行
package main import "fmt" //结构体内部属性的初始化======= type Stu struct { Name string Age int } //实现String() func (s *Stu) String() string { str := fmt.Sprintf("Stu{Name=%v,Age=%v}", s.Name, s.Age) return str } func main() { var stu1 = Stu{"tom", 18} stu2 := Stu{"mark", 28} var stu3 = Stu{Name: "any", Age: 38} stu4...
package main import( "manager" "manager/stmanager" "manager/accmanager" "fmt" "time" "flag" ) func Call(m manager.Manager) { m.Process() } func main() { var m manager.Manager start := time.Now() t := flag.String("t", "list", "stock manager type") flag.Parse() fmt.Pri...
package primitives_test import ( "github.com/plandem/xlsx/internal/ml/primitives" "github.com/stretchr/testify/require" "testing" ) func TestCelRef(t *testing.T) { require.Equal(t, primitives.CellRef(""), primitives.CellRefFromIndexes(-1, -1)) require.Equal(t, primitives.CellRef(""), primitives.CellRefFromIndexe...
// Copyright (c) 2015 Andrea Masi. All rights reserved. // Use of this source code is governed by a MIT license // that can be found in the LICENSE.txt file. // Package middle exposes functions useful // building http services. package middle import ( "log" "math/rand" "net/http" "sync" "time" ) const ( authCo...
package accountstable import ( "bytes" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "database/sql" "encoding/hex" "os" "reflect" "testing" "github.com/SIGBlockchain/project_aurum/internal/accountinfo" "github.com/SIGBlockchain/project_aurum/internal/constants" "github.com/SIGBlockchain/project_aurum/int...
/* Links * http://afecymog.github.com/1.html * http://afecymog.github.com/2.html * http://afecymog.github.com/3.html * http://afecymog.github.com/4.html * http://afecymog.github.com/5.html * http://afecymog.github.com/6.html * http://afecymog.github.com/7.html * http://afecymog.github.com/8.html * http://afecymog.githu...
package main import ( "github.com/spf13/cobra" "os" "github.com/alejandroEsc/maas-cli/pkg/cli" "github.com/spf13/viper" "github.com/alejandroEsc/golang-maas-client/pkg/api" "github.com/alejandroEsc/golang-maas-client/pkg/api/v2" "encoding/json" "fmt" "net/url" ) func versionCmd() *cobra.Command { vo := ...
package main import ( "fmt" "strconv" ) // define person struct type Person struct { // firstName string // lastName string // age int // gender string firstName, lastName, gender string age int } // greeting method (value reciever) func (p Person) greet() string { return "...
package main import ( "github.com/walln/flurry2/flurry" ) func main() { server := flurry.Initialize() server.ListenAndServe() }
package couchdb import ( ) func (c *CouchDb)DatabaseCreate(name string) error { c.CountCalls++ buf,err:=c.call("PUT",name,nil,nil) if err!=nil { return err } _,err=parseGenericReturn(buf) return err } func (c *CouchDb)DatabaseDelete(name string) error { c.CountCalls++ buf,err:=c.call("DELETE",name,n...
package main import ( "launchpad.net/xmlpath" "log" "sync" "strings" //"fmt" //"text/template" ) func front_process(list_urls []string, c_front_urls chan string, c_doc_urls chan string) { var wg sync.WaitGroup c_front_page := make(chan []byte, 1000) for _, url := range list_urls { c_front_urls <- url wg....
package main import "fmt" func main() { for i := 1; i <= 9; i++ { for start := 1; start <= i; start++ { if start == i { fmt.Printf("%d*%d=%d\n", start, i, start*i) } else { fmt.Printf("%d*%d=%d ", start, i, start*i) } } } }
package model import "github.com/SDkie/metric_collector/db" //go:generate easytags metric_pg.go json //go:generate easytags metric_pg.go sql type MetricPg struct { Id int64 `sql:"id" gorm:"primary_key" json:"id"` MetricStruct } func InitPg() { db.InitPg() db.GetPg().CreateTable(&MetricPg{}) } func (m *MetricPg...
/* Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. For example, the following two linked lists begin to intersect at node c1: The test cases are generated such that there are no cycles any...
package kinetic import ( "runtime" "sync/atomic" "testing" "time" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/firehose" . "github.com/smartystreets/goconvey/convey" ) func TestFireHose(t *testing.T) { producer, _ := new(Firehose).InitC("your-stream", "", "", "accesskey", "secre...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //792. Number of Matching Subsequences //Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. //Exam...
/* 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 may not use this fi...
package base import ( "context" "github.com/thoohv5/template/internal/ent" "github.com/thoohv5/template/pkg/log" ) type Base struct { options } func New(opts ...Option) *Base { options := options{} for _, o := range opts { o.apply(&options) } return &Base{ options: options, } } type options struct { ...
package layers import ( "encoding/base64" "fmt" "io/ioutil" "os" "path/filepath" "strings" "grm-service/common" "grm-service/geoserver" "grm-service/log" . "grm-service/util" "data-manager/types" "github.com/emicklei/go-restful" //"grm-service/log" ) func (s DataLayerSvc) getLayers(req *restful.Reques...
// +build dev package bundle import "net/http" var SqlMap = func() http.FileSystem { return http.Dir("test/sqlmap") }()
package main import "fmt" func sayHi(name string) string { return "hello, " + name + "!" } func init() { fmt.Println("function init will be executed first.") } func main() { fmt.Println(sayHi("vivia")) const PI = 3.14 fmt.Printf("PI=%v\n", PI) fmt.Printf("%d\n", 100) fmt.Printf("%d\n", 0...
package core import ( "encoding/json" "er" "fwb" "hlf" "sgs" ) type playerImp struct { app fwb.FwApp id int name string lg hlf.Logger } func (me *playerImp) ID() int { return me.id } func (me *playerImp) Name() string { return me.name } func (me *playerImp) SendCommand(command sgs.Command) *er.Err ...
package domain import ( "log" "testing" "github.com/matryer/is" ) func TestGetMessage(t *testing.T) { t.Run("When get encoded message with symmetrical messages", func(t *testing.T) { is := is.New(t) kenobi := []string{"este", "", "", "mensaje", ""} skywalker := []string{"", "es", "", "", "se...
package utils import ( "regexp" "time" ) const ( emailPattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" format = "2006-01-02T15:04:05Z" mySQLDbFormat = "2006-01-02 15:04:05" ) func IsValidEmail(email string) ...
package main import ( "io" "os" ) func main() { // open input file input_file, error := os.Open("input.txt") if error != nil { panic(error) } // close file on exit and check for its returned error defer func() { if error := input_file.Close(); error != nil { panic(error) } }() // ope...
package controllor import ( "encoding/json" "os" "strconv" "strings" "xiaodaimeng/public" ) type XDM struct { Menu []string `json:"menu"` About string `json:"about"` Update Update `json:"update"` } type Update struct { Version int `json:"version"` //当前 Info []UpdateInfo `json:"info"` } ...
package main import ( "database/sql" "fmt" "log" "net/http" "github.com/julienschmidt/httprouter" ) var db *sql.DB func main() { fmt.Println("Building router..") router := httprouter.New() router.GET("/", Index) router.GET("/plot", Plot) router.GET("/split", Split) router.GET("/train", Train) router.G...
//Package glog 学习自FLogger https://github.com/cyfonly/FLogger.git package glog import ( "fmt" "runtime" "runtime/debug" "time" "github.com/dalixu/glogger" ) // import ( // "log" // "os" // ) //Properties LogEvent属性 方便添加自定义字段 type Properties map[string]interface{} //LogEvent log的具体内容 type LogEvent struct { ...
package cmd import ( "os" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/Zenika/marcel/config" ) func preRunForServer(cfg *config.Config) func(*cobra.Command, []string) error { return func(_ *cobra.Command, _ []string) error { log.SetOutput(os.Stdout) bindLogLevel(cfg) if err := ...
package main import ( "fmt" "net/http" "strconv" "github.com/gin-gonic/gin" ) var messages []string // func GetMessages(c *gin.Context) { // version := c.Param("version") // fmt.Println("Version", version) // c.JSON(http.StatusOK, gin.H{"messages": messages}) // } func OptionMessage(c *gin.Context) { c.Hea...
package server import ( "net/http" "reflect" "github.com/ItsJimi/casa/logger" "github.com/ItsJimi/casa/utils" "github.com/labstack/echo" ) type addHomeReq struct { Name string Address string WifiSSID string } // AddHome route create and add user to an home func AddHome(c echo.Context) error { req := n...
package main import ( "fmt" "encoding/json" ) type Usuario struct{ Nome string SobreNome string } func main(){ usuario := Usuario{"vinicius","dias das silva"} usuAux,_ := json.Marshal(usuario) fmt.Println(string(usuAux)) }
package model import ( // "encoding/json" "github.com/astaxie/beego/orm" ) func init() { orm.RegisterModel(new(RainlabBlogPosts)) }
package main import( "fmt" "net/http" "crypto/tls" "crypto/x509" "io/ioutil" "log" ) func reqHandler(w http.ResponseWriter, req *http.Request) { fmt.Fprint( w, "Hello From Server 1\n" ) } func main() { http.HandleFunc("/", reqHandler) // Add the selfca certificate to the certificate pool /...
package products // User provides Use function for interact with products type User interface { Use() string }
package rpc type RGBA struct { R int32 `json:"r"` G int32 `json:"g"` B int32 `json:"b"` A int32 `json:"a"` } func (rgba RGBA) ToRGBInt() int32 { rgb := rgba.R<<16 + rgba.G<<8 + rgba.B return rgb } func (rgba RGBA) ToRGB() (int32, int32, int32) { return rgba.R, rgba.G, rgba.B } type Theme struct { Accent ...
package mysqldb import ( "context" "time" ) // QRCode 二维码 type QRCode struct { SceneID int32 `gorm:"primary_key"` // 场景ID RawURL string `gorm:"column:raw_url"` // 原始URL Ticket string `gorm:"column:ticket"` // Ticket Account string `gorm:"column:account"` ...
package cmd import ( "fmt" "os" "sort" "strings" "github.com/spf13/cobra" "github.com/spf13/viper" ) var targetsPruneCmd = &cobra.Command{ Use: "prune <target> [<target>...]", Short: "Prune target(s)", Run: doTargetsPrune, Args: cobra.MinimumNArgs(1), } var ( pruneNoTail bool pruneByTag bool prun...
package main import ( "golang/helper" "testing" ) func TestRottingOranges(t *testing.T) { input := [][]int{{2, 1, 1}, {1, 1, 0}, {0, 1, 1}} helper.AssertInt(orangesRotting(input), 4, t) input = [][]int{{2, 1, 1}, {0, 1, 1}, {1, 0, 1}} helper.AssertInt(orangesRotting(input), -1, t) input = [][]int{{0, 2}} he...
package full_test import ( "testing" "github.com/mkamadeus/cipher/cipher/vigenere/full" ) func TestEncrypt(t *testing.T) { plain := "thisisplaintext" key := "sony" expected := "DPYFNWKHRDCABKO" encrypted := full.Encrypt(plain, key) if encrypted != expected { t.Fatalf("full vignere encryption failed, expect...
package oidc import ( "time" "github.com/google/uuid" "github.com/mohae/deepcopy" "github.com/ory/fosite" "github.com/ory/fosite/handler/openid" "github.com/ory/fosite/token/jwt" ) // Session holds OpenID Connect 1.0 Session information. type Session struct { *openid.DefaultSession `json:"id_token"` Challen...
package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" ) // サーバーサイドのDBと仮定 var DB = map[string]string{ "TEST1Key": "TEST1Secret", } // サーバーサイドでクライアントから受け取った情報が正しいものか判定する関数 // 引数はクライアントから送られてきたデータというイメージ func Server(apiKey, sign string, data []byte) { // TEST1のSecretはDBから参照する apiSecret := DB[a...
// go test -v -race package main import ( "os" "os/exec" "sync" "testing" ) func TestNotRace(t *testing.T) { cl := []string{"sh", "-c", `for x in $(seq 3); do echo "$x loops"; sleep 1; done`} wg := new(sync.WaitGroup) run := func() { defer wg.Done() cmd := exec.Command(cl[0], cl[1:]...) cmd.Stdout = os.S...
/* * Copyright 2020 The Multicluster-Scheduler 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 appl...
package config import "fmt" // StorageConfig describes various configurations of a storage layer type StorageConfig struct { Postgres *PostgresConfig `yaml:"postgres"` } func (c *StorageConfig) validate() error { var err error if c.Postgres != nil { err = c.Postgres.validate() } return err } // PostgresConfi...
package bot import ( "fmt" "strings" "github.com/bwmarrin/discordgo" ) type Command interface { Run(bot *Bot, args string, message *discordgo.Message) Sendable } type CommandGroup map[string]Command func (c CommandGroup) Run( bot *Bot, args string, message *discordgo.Message, ) Sendable { spaceIndex := str...
package users import ( "crypto/sha1" "encoding/hex" "errors" "fmt" "strconv" jwt "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" . "go-sugar/config" . "go-sugar/db" "go-sugar/db/request" ) // Columns const ( ID string = "id" Name string = "name" Password string = "password" Role...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //719. Find K-th Smallest Pair Distance //Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) ...