text
stringlengths
11
4.05M
package helper import ( "fmt" "reflect" ) func MapToStruct(m interface{}, s interface{}) error { r := reflect.ValueOf(m) switch reflect.TypeOf(m).Kind() { case reflect.Map: keys := r.MapKeys() for _, k := range keys { err := setfield(k.Interface().(string), r.MapIndex(k).Interface(), s) if err != nil {...
package main /* * Given a complete binary tree, count the number of nodes in faster than O(n) * time. Recall that a complete binary tree has every level filled except the * last, and the nodes in the last level are filled starting from the left. * "Complete" means: every level, except possibly the last, is complet...
package core type Place struct { XPos float64 `json:"pos_x"` YPos float64 `json:"pos_y"` Priority float64 `json:"priority"` ExpectedArriveTime float64 `json:"expected_arrive_time"` OperationTime float64 `json:"operation_time"` Arrived float64 `json:"arrived"`...
/* Copyright 2021 The Skaffold Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
package pubsub_test import ( "context" "fmt" "net/http/httptest" "net/url" "testing" "github.com/go-restit/lzjson" "github.com/gorilla/websocket" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/tomatorpg/tomatorpg/protocol/pubsub" ) func TestServer_ServeHTTP(t *testing.T) { ...
package consumable func retrieveAd(decision decision) string { if decision.Contents != nil && len(decision.Contents) > 0 { return decision.Contents[0].Body } return "" }
package main import ( "fmt" ) type person struct { name string surname string icecream string } func main() { p1 := person{ name: "Onur", surname: "Gurel", icecream: "Chocalate", } p2 := person{ name: "Ugur", surname: "Gurel", icecream: "Lemon", } slice := []string{p1.icecream, p...
package kubesystem import "os" func IsRunLocally() bool { return os.Getenv("RUN_LOCAL") == "true" }
package source import ( "testing" "github.com/onsi/gomega" ) func Test_invokeFilter_ShouldHandleDateparse(t *testing.T) { g := gomega.NewWithT(t) format := "200601021504" // "2006-01-02T15:04:05Z07:00" timeTS := "202007021120" f := FilterService{} result, err := f.Filter("dateparse", format, timeTS) g.Expe...
// Package rinex provides functions for reading and writing RINEX files. // Note observation data files are ASCII! package rinex import ( "bufio" "bytes" "fmt" "log" "math" "math/big" "os" "os/exec" "path/filepath" "strconv" "strings" "time" ) // ObsFil contains fields and methods for RINEX observation fi...
package gofastcgi import ( "testing"; // "bytes"; "strings"; "reflect"; // "io"; "os"; "fmt"; ) type StrictWriter struct { data []byte; pos int; } func (s *StrictWriter) Write(p []byte) (n int, err os.Error) { count := 0; if len(p) == 0 { return 0, nil } if s.pos >= len(s.data) { return 0, os.NewError("St...
package users import () type UsersMessage struct { Status int8 `json:"status"` Message string `json:"message"` Users []User `json:"users"` } func UserList() UsersMessage { users := []User{ {"Bob", "Smith", "bsmith@gmail.com", "bob"}, {"John", "Little", "little@gmail.com", "jLit"}, {"Red", "Wonkers", "...
package lambda import ( "fmt" "log" "os" "os/exec" "io/ioutil" "path/filepath" "github.com/dougkirkley/trex/config" "github.com/dougkirkley/trex/terraform" ) const GO = "go" func WorkingDir() string { wd, err := os.Getwd() if err != nil { log.Print(err) } return wd } func notInConfig(configFile co...
package main import ( "crypto/md5" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "github.com/bitly/go-simplejson" "github.com/couchbase/go-couchbase" "log" "math" "net/http" "regexp" "strconv" "strings" "time" ) /* json返回对象 */ type MyReturn struct { State bool `json:"state"` Mes...
package feature type IT1 interface { Hello() string Bye() string } type Node struct{} func CreateIT1() IT1 { node := &Node{} return node } func (st *Node) Hello() string { return "hello world!" } func (st *Node) Bye() string { return "Bye!" } type Node2 struct { *Node } func CreateIT2() IT1 { node := &No...
package task import ( "clickpaas-exporter/pkg/storage" "clickpaas-exporter/pkg/util" "context" "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/kubernetes" ) const ( DefaultAllocatedIfNodeSet = 1024*1024 * 2 ...
package main import ( "flag" "fmt" "io/ioutil" "os" "strings" "golang.org/x/crypto/ssh/terminal" ) const ( errNoArgs = 1 errRead = 2 ) func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: %v <left file> <right file>\n\n", os.Args[0]) flag.PrintDefaults() } w, _, err := terminal.GetSi...
package common import ( "bytes" "encoding/json" "fmt" aterror "github.com/apitable/apitable-sdks/apitable.go/lib/common/error" athttp "github.com/apitable/apitable-sdks/apitable.go/lib/common/http" "github.com/apitable/apitable-sdks/apitable.go/lib/common/profile" "io" "log" "mime/multipart" "net/http" "net...
package main import ( "context" "crypto/tls" "encoding/json" "fmt" "net/url" "os" "time" "github.com/go-jose/go-jose/v3" "github.com/spf13/cobra" "github.com/pomerium/pomerium/internal/authclient" ) func init() { addBrowserFlags(kubernetesExecCredentialCmd) addTLSFlags(kubernetesExecCredentialCmd) kube...
package handler import ( "encoding/json" "errors" "fmt" "github.com/gorilla/mux" "net/http" "os" "user-service/dto" "user-service/model" "user-service/service" ) type UserHandler struct { UserService *service.UserService } func (handler *UserHandler) RegisterUser (res http.ResponseWriter, req *http.Request...
package github import ( "fmt" "net/url" "strings" ) type Repository struct { Owner string Name string } func ParseRepositoryURL(urlstr string) (*Repository, error) { u, err := url.Parse(urlstr) if err != nil { return nil, fmt.Errorf("invalid url: %w", err) } path := u.Path path = strings.TrimSuffix(path...
package models import( "encoding/json" ) /** * Type definition for CategoryEnum enum */ type CategoryEnum int /** * Value collection for CategoryEnum enum */ const ( Category_KDISK CategoryEnum = 1 + iota Category_KNODE Category_KCLUSTER Category_KNODEHEALTH Category_KC...
package api import ( "context" "corona/helpers" "corona/models" "database/sql" uuid "github.com/satori/go.uuid" "net/http" ) type ( RateLimitModule struct { db *sql.DB logger *helpers.Logger name string } RateLimitDetailParam struct { Id uuid.UUID `json:"id"` } RateLimitAddParam struct { ...
package endpoints import ( "encoding/json" "log" "net/http" "github.com/anabiozz/yotunheim/backend/common" "github.com/anabiozz/yotunheim/backend/common/datastore" "github.com/anabiozz/yotunheim/backend/internal/config" "github.com/anabiozz/yotunheim/backend/metrics" ) // GetCommonCharts ... func GetCommonCha...
package toast import ( "os/exec" ) type SnoreToast struct { Path string } func New(path string) *SnoreToast { if path == "" { path = "SnoreToast.exe" } return &SnoreToast{Path: path} } func (s *SnoreToast) Toast(title string, message string) error { err := exec.Command(s.Path, "-t", title, "-m", message, "-...
package octo /* * UI for admins */ import ( "appengine" "appengine/blobstore" "appengine/datastore" "appengine/taskqueue" "archive/zip" "bufio" "bytes" "encoding/csv" "fmt" "html" "html/template" "io" "net/http" "net/url" "path" "strings" "time" ) type AdminAccountRecord struct { ID string ...
// Copyright © 2015-2016 Pierre Neidhardt <ambrevar@gmail.com> // Use of this file is governed by the license that can be found in LICENSE. /* A filesystem hierarchy synchronizer Rename files in TARGET so that identical files found in SOURCE and TARGET have the same relative path. The main goal of the program is to ...
package practice import ( "testing" "time" ) func TestTLS(t *testing.T) { server := &TLSEchoServer{} go server.Listen(9999, "testcert.pem", "testkey.pem") time.Sleep(time.Second * 3) client := &TLSClient{} client.Connect("localhost:9999", "testcert.pem") err := client.Write("hello") if err != nil { ...
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build linux && !android // +build linux,!android package hostinfo import ( "bytes" "fmt" "io/ioutil" "os" "strings" "syscall" "tailsc...
package main import ( "strings" ) // Palindrome returns true if input string is palindrome func Palindrome(s string) bool { str := strings.ToLower(s) str = strings.Replace(str, " ", "", -1) arr := []byte(str) mid := len(arr) / 2 for i, j := 0, len(arr)-1; i < mid; i, j = i+1, j-1 { if arr[i] != arr[j] { ...
package notification //Sender sender interafce type Sender interface { //Send send notification and return any error if raised. Send(*Notification) error } //SenderFunc sender func interface type SenderFunc func(*Notification) error //Send send notification and return any error if raised. func (f SenderFunc) Send(...
package main import ( "testing" "strconv" "github.com/stretchr/testify/assert" ) func TestCases(t *testing.T) { tcs := []struct { cur, pos, exp int }{ {90, 359, -91}, {315, 45, 90}, {180, 270, 90}, {45,270, -135}, } for idx, tc := range tcs { t.Run(strconv.Itoa(idx), func(inner *testing.T) { as...
package tree import ( "reflect" "testing" ) func TestNewBT(t *testing.T) { i := map[int]int{1: 10, 2: 20, 3: 30} node := NewBT(i) want := []int{10, 20, 30} got := make([]int, 3, 3) got[0] = node.Val got[1] = node.Left.Val got[2] = node.Right.Val if !reflect.DeepEqual(want, got) { t.Errorf("Wrong") }...
package customproperties import ( "github.com/Dynatrace/dynatrace-operator/src/logger" ) var ( log = logger.Factory.GetLogger("activegate-customproperties") )
package main // Version: 1.4 // Script to check hashrate of miner and reset if it falls below expected hashrate // Script will kill and restart the miner a few times and recheck hashrate // If hashrate continues to be low, it will restart the computer // Requries 2 arguments. First is wallet address/api key, second is...
package main import ( "bufio" "fmt" "log" "net" ) func main() { li, err := net.Listen("tcp", ":8080") if err != nil { log.Fatalln(err) } defer li.Close() for { conn, err := li.Accept() if err != nil { log.Println(err) continue } go handle(conn) } } func handle(conn net.Conn) { // NewScan...
// Copyright 2016 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import "fmt" // https://www.codewars.com/kata/5671d975d81d6c1c87000022/train/go // SolvePuzzle solves the puzzlr func SolvePuzzle(clues []int) [][]int { p := permutations{} p.init() mh0 := getMustHaves(0, clues) mh1 := getMustHaves(1, clues) mh2 := getMustHaves(2, clues) mh3 := getMustHaves(3, cl...
package config import ( "fmt" "github.com/flyleft/gprofile" ) var AppConfig = ApplicationConfig{} func init() { config, err := gprofile.Profile(&ApplicationConfig{}, "./application.yaml", true) if err != nil { fmt.Errorf("Profile execute error", err) } AppConfig = *config.(*ApplicationConfig) }
package main /* --- Day 7: The Sum of Its Parts --- You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed ashore. It's quite cold out,...
package heap import "strings" type MethodDescriptorParser struct { raw string offset int parsed *MethodDescriptor } func parseMethodDescriptor(descriptor string) *MethodDescriptor { parser := &MethodDescriptorParser{} return parser.parse(descriptor) } func (mdp *MethodDescriptorParser) parse(descriptor stri...
package main import ( "bufio" "flag" "fmt" "github.com/lnsyyj/SSTDV/DBs" "github.com/lnsyyj/SSTDV/analysis" "github.com/lnsyyj/SSTDV/common" "os" ) func InitDataTimeInterval(logPath *string, summaryData *analysis.SummaryData, outputInterval *int) { file, err := os.Open(*logPath) lineInfo := "" defer file.Cl...
// Copyright (C) 2018 Google 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 t...
package main import ( "nes" "os" "fmt" "log" ) func main() { path := os.Args[1] var file *os.File var err error if file, err = os.Open(path); err != nil { log.Fatal(err) return } var rom *nes.ROM rom, err = nes.ReadROM(file) if err != nil { log...
package app import ( "fmt" "github.com/fvukojevic/matchingservice/controller" socketio "github.com/googollee/go-socket.io" "log" "net/http" ) func mapUrls() { router.GET("/session", controller.Session) router.POST("/join", controller.Join) router.POST("/leave", controller.Leave) go router.Run(":8080") } fun...
package keeper import ( "encoding/json" tmbytes "github.com/tendermint/tendermint/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/irismod/service/types" ) // CompleteBatch completes a running batch func (k Keeper) CompleteBatch(ctx sdk.Context, requestContext types.RequestContext, requestConte...
package memberlist // IpAddress is the struct for the collection type IpAddress struct { Name string `firestore:"name,omitempty"` Ip string `firestore:"ip,omitempty"` Port string `firestore:"port,omitempty"` Protocol string `firestore:"protocol,omitempty"` // "tcp" or "udp" } // Structure of the col...
// Package dbmigrate is a sql database migration tool. // // dbmigrate can be used both as a CLI application and as a Go package, does not use any DSL for migrations, // just plain old SQL we all know and love so it is compatible with any framework and programming language. package dbmigrate import ( "path/filepath" ...
// Copyright 2018 Authors of Cilium // // 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 saba /* Creation Time: 2019 - Sep - 23 Created by: (ehsan) Maintainers: 1. Ehsan N. Moosa (E2) Auditor: Ehsan N. Moosa (E2) Copyright Ronak Software Group 2018 */ const ( SuccessfulCode = "SC000" SubscriptionAlreadyExists = "SC012" ) var Codes = map[string]string{ "SC000"...
package main import "fmt" func Join(sep string, vals ...string) string { var result string for _, val := range vals { if result != "" { result += sep } result += val } return result } func main() { fmt.Println(Join("-", "a", "b", "c", "d", "e")) }
/* Interface for Views. This is important to ensure modularity. do not edit or delete. Must be implemented by every new View. For more information please read ./TemplateView.go @author SashaCollins @version 1.0 */ package viewmodel import "github/SashaCollins/Wisehub-Connect/model/plugins" type ViewI interface { /* ...
package server import ( "errors" "fmt" "net/http" "github.com/dgrijalva/jwt-go" "github.com/labstack/echo/v4" "github.com/sirupsen/logrus" ) // loginRequest specifies the structure of json in an authentication request. type loginRequest struct { Password string `json:"password"` } // refreshRequest specifies...
package main import ( "fmt" "io" "os" ) var writer io.Writer func init() { writer = os.Stdout } type View struct { Repositories []Repository } func NewView(repos []Repository) *View { return &View{ Repositories: repos, } } func (v *View) Show() { reviewCount := 0 for _, repo := range v.Repositories { ...
import "sort" /* * @lc app=leetcode id=41 lang=golang * * [41] First Missing Positive * * https://leetcode.com/problems/first-missing-positive/description/ * * algorithms * Hard (31.60%) * Likes: 3635 * Dislikes: 811 * Total Accepted: 344.2K * Total Submissions: 1.1M * Testcase Example: '[1,2,0]' ...
package kustomize import ( "path/filepath" "strings" "testing" "github.com/stretchr/testify/require" "github.com/tilt-dev/tilt/internal/testutils/tempdir" ) func TestNoFile(t *testing.T) { f := newKustomizeFixture(t) f.assertErrorContains("unable to find one of [kustomization.yaml kustomization.yml Kustomiz...
package main // import "github.com/arribada/smartconnect/tools/uploader" import ( "bytes" "crypto/tls" "fmt" "io" "io/ioutil" "log" "net/http" "os" "path/filepath" "strconv" "mime/multipart" "github.com/pkg/errors" "gopkg.in/alecthomas/kingpin.v2" ) func main() { log.SetFlags(log.Ltime | log.Lshortfi...
package config import ( "os" "testing" ) func b2s(v bool) string { if v { return "true" } return "false" } func getTestConfig() *Config { wantOpts := newConfig() wantOpts.Name = "gleafd" wantOpts.Addr = "localhost:7890" wantOpts.Segment.Enable = false wantOpts.Segment.DBHost = "example.com:3306" wantOpt...
package kafka import ( "fmt" "time" "github.com/Shopify/sarama" ) type logData struct { topic string data string } var ( gClient sarama.SyncProducer logDataChan chan *logData ) func KafakInstance() *sarama.SyncProducer { return &gClient } func Init(address string, kafkaMaxSize int) (err error) { conf...
package main import ( "fmt" "log" "net/http" "strconv" "sync" ) var mu sync.Mutex func main() { db := database{"shoes": 50, "socks": 5} http.HandleFunc("/list", db.list) http.HandleFunc("/add_item", db.create) http.HandleFunc("/price", db.read) http.HandleFunc("/update_item", db.update) http.HandleFunc("...
package main import ( "strconv" "strings" ) // Leetcode 297. (hard) type Codec struct { l []string } func Constructor() Codec { return Codec{} } // Serializes a tree to a single string. func (this *Codec) serialize(root *TreeNode) string { return subSerialize(root, "") } func subSerialize(root *TreeNode, s st...
package vindinium import ( "errors" "math" "strconv" ) const ( WALL = iota - 2 AIR TAVERN AIR_TILE = " " WALL_TILE = "#" TAVERN_TILE = "[" MINE_TILE = "$" HERO_TILE = "@" ) var ( AIM = map[Direction]*Position{ "North": &Position{-1, 0}, "East": &Position{0, 1}, "South": &Position{1, 0}, ...
package dockerfile import ( "testing" "github.com/stretchr/testify/assert" ) func TestFindImages(t *testing.T) { df := Dockerfile(`FROM gcr.io/image-a`) images, err := df.FindImages(nil) assert.NoError(t, err) if assert.Equal(t, 1, len(images)) { assert.Equal(t, "gcr.io/image-a", images[0].String()) } } fu...
package system import ( "festival/app/model" ) type SysMenu struct { model.BaseModel Name string `json:"name" gorm:"column:name;not null;type:varchar(20);comment:名称;"` ParentId uint `json:"parentId" gorm:"column:parent_id;type:bigint(20);comment:父ID;"` Sort uint `json:"sort" gorm:"colu...
package quadtree import ( "container/list" ) // // A Simple quadtree collector which will push every element into col // func SimpleSurvey() (fun func(x, y float64, e interface{}), col *list.List) { col = list.New() fun = func(x, y float64, e interface{}) { col.PushBack(e) } return } // // A Simple quadtree d...
package main import ( "container/heap" "fmt" ) /* Implement FreqStack, a class which simulates the operation of a stack-like data structure. FreqStack has two functions: push(int x), which pushes an integer x onto the stack. pop(), which removes and returns the most frequent element in the stack. If there is...
package cluster import ( "github.com/bengtrj/cfcr-cluster-diagram/infra-diagram/generator/deployment" "fmt" "strings" "sort" ) type Cluster struct { Name string Masters []Node Workers []Node } type Node struct { Id string Name string Type string Jobs []Job } type Job struct { Id string ...
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( "fmt" "os" "bufio" "strings" "regexp" "strconv" ) var m = map[string]int{ "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000, } var mCredits = map[string][]string{} var mQuestion = map[string][]string{} var def = map[string]string{} var value string func isSymbo...
package tcpip import "log" func dst_neigh_output(skb *sk_buff) error { // struct iphdr *iphdr = ip_hdr(skb); // struct netdev *netdev = skb->dev; // struct rtentry *rt = skb->rt; // uint32_t daddr = ntohl(iphdr->daddr); // uint32_t saddr = ntohl(iphdr->saddr); // uint8_t *dmac; // if (rt->flags & RT_GATEWAY)...
package main import ( "fmt" "log" "net/http" "os" "github.com/ninckblokje/golang-bits-n-bytes/RESTService/handlers" "github.com/ninckblokje/golang-bits-n-bytes/RESTService/persistence" ) func main() { db, err := persistence.Init() if err != nil { fmt.Printf("FATAL: %+v\n", err) os.Exit(1) } r := handl...
package data import ( "database/sql" "database/sql/driver" "fmt" "strconv" "strings" _ "github.com/mattn/go-sqlite3" ) func OpenDB(conn string) (*sql.DB, error) { db, err := sql.Open("sqlite3", conn) if err != nil { return nil, err } return db, nil } type DBID int64 type Box [4]int func (box *Box) Sca...
package majiangserver import ( cmn "common" "logger" "math" "math/rand" "time" ) const ( LCNone = iota HuPengSimultaneously TestHu TestErLongTouYi ) var SpecificLicensingType int = LCNone var FixedBankerIndex int = -1 // var SpecificLicensingType int = TestHu // var FixedBankerIndex int = 0 var MeanwhileM...
// Derived from the Eclipse Project for JMS, available at; // https://github.com/eclipse-ee4j/jms-api // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0, which is available at // http://www.eclipse.org/legal/epl-2.0. // // SPDX-License-Identifie...
package main import ( "encoding/json" "fmt" "io" "os" wasm "github.com/wasmerio/go-ext-wasm/wasmer" ) type WasmFormat struct { Bytes []byte `json:"bytes"` Params []WasmParam `json:"params"` } type WasmParam struct { Value interface{} `json:"value"` WasmParamType WasmParamType `json:"type"` ...
package infrastructure import "net/http" //go:generate mockgen -package mocks -destination $ROOTDIR/mocks/$GOPACKAGE/mock_$GOFILE . HTTPClient type HTTPClient interface { Do(req *http.Request) (*http.Response, error) }
package sql import( "fmt" "github.com/myxtype/filecoin-client/models" "github.com/myxtype/filecoin-client/pkg/setting" "log" "reflect" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) var db *gorm.DB func InitSql()(db *gorm.DB) { var ( err ...
package main import ( "encoding/json" "fmt" "lobby_server/lobby" "log" "net" ) //LobbyHandle 大厅 var LobbyHandle *lobby.Lobby const ( //SERVERIP 服务器IP SERVERIP = ":7000" ) //ClientMsg 客户端消息 type ClientMsg struct { Order int `json:"order"` } //RobbyMsg 大厅消息 type RobbyMsg struct { Joinlobby bool `json:"join...
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( "log" "net/http" "os" "github.com/jinzhu/gorm" "github.com/gin-gonic/contrib/static" "github.com/gin-gonic/gin" "github.com/joho/godotenv" "./rest-api" "./settings" ) var db *gorm.DB func init() { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } d...
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package supervisor import log "github.com/sirupsen/logrus" type installationDBRestorationLockStore interface { LockInstallationDBRestorationOperations(id []string, lockerID string) (bool, error) Unloc...
package model type User struct { ID int `gorm:"primaryKey;type:int;autoIncrement;not null" json:"id"` Name string `gorm:"type:varchar(255);not null" json:"name"` Email string `gorm:"uniqueIndex;type:varchar(255);not null" json:"email"` Password string `gorm:"type:string;not null;" json:"-"` }
package heartmon import ( "fmt" "log" "os" "sync" "time" ) // NOTE: I'm not 100% sure this first sample is perfectly normal. type MonitorReader struct { outfile string incoming chan uint16 stop chan struct{} sync.Mutex // There's a bit of dodginess here, since if any of these block // they end up block...
package main import ( "encoding/json" "fmt" "log" "net/http" "strconv" "strings" "github.com/gorilla/mux" "gopkg.in/redis.v5" ) type App struct { Router *mux.Router RedisClient *redis.Client } func (a *App) Initialize(port string, password string, dbStr string) { if len(port) == 0 { port = "6379" ...
package main import ( "log" zmq "github.com/pebbe/zmq4" ) type Handler func(msg []byte) []byte func NewServer(target string, handler Handler) *Server { log.Println("initializing server", target) return &Server{target: target, workers: 10, handler: handler} } type Server struct { target string workers int ...
/** * Copyright (C) 2021 The poly network Authors * This file is part of The poly network library. * * The poly network is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the Lice...
package main import ( "path/filepath" "time" "github.com/spf13/cobra" "restic" "restic/debug" "restic/errors" "restic/repository" ) var cmdFind = &cobra.Command{ Use: "find [flags] PATTERN", Short: "find a file or directory", Long: ` The "find" command searches for files or directories in snapshots stor...
/* * Copyright (c) CERN 2016 * * 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 w...
package main import ( "fmt" "net" "os" "github.com/kalimatas/network-in-go" ) func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Usage: %s host:port\n", os.Args[0]) os.Exit(1) } service := os.Args[1] addr, err := net.ResolveUDPAddr("udp4", service) gonet.CheckError(err) conn, err := net.Di...
package jago import ( "encoding/binary" "unsafe" ) var bigEndian = binary.BigEndian type ClassReader struct { bytecode []uint8 classfile *ClassFile } func NewClassReader(bytecode []byte) *ClassReader { return &ClassReader{bytecode: bytecode} } func (this *ClassReader) readU4() u4 { value := bigEndian.Uint32(...
package usecase import ( "context" "time" ) type messageUsecase struct { contextTimeout time.Duration } func (m *messageUsecase) Store(c context.Context) (err error) { return }
package lc // Time: O(n) // Benchmark: 8ms 5.8mb | 91% 69% func transpose(A [][]int) [][]int { m2 := make([][]int, len(A[0])) for i := 0; i < len(A[0]); i++ { row := make([]int, len(A)) for j := 0; j < len(A); j++ { row[j] = A[j][i] } m2[i] = row } return m2 }
package database import ( "context" "database/sql" "log" "sync" "time" "gorm.io/driver/postgres" "gorm.io/gorm" "github.com/kyos0109/test-wallet/modules" ) // DBConn ... type DBConn struct { conn *gorm.DB } var ( ctx context.Context once sync.Once dbClient *DBConn ) // InitWithCtx ... func In...
package main import ( "fmt" "log" "os" "path/filepath" "strings" "github.com/spf13/pflag" "github.com/spf13/viper" "go.uber.org/zap" "github.com/transcom/mymove/pkg/cli" "github.com/transcom/mymove/pkg/logging" "github.com/transcom/mymove/pkg/services/invoice" ) // Call this from command line with go run...
package user_group import ( "github.com/gin-gonic/gin" "lhc.go.game.center/model" "net/http" ) func Index(c *gin.Context) { c.HTML(http.StatusOK,"user_group/index.html",gin.H{}) } func Add(c *gin.Context) { c.HTML(http.StatusOK,"user_group/add.html",gin.H{}) } func GetUserGourpList(c *gin.Context) { var s...
package exchange import ( gpplib "github.com/prebid/go-gpp" gppConstants "github.com/prebid/go-gpp/constants" "github.com/prebid/prebid-server/gdpr" "github.com/prebid/prebid-server/openrtb_ext" gppPolicy "github.com/prebid/prebid-server/privacy/gpp" ) // getGDPR will pull the gdpr flag from an openrtb request f...
package search func (t *TuiScreen) HttpCode() { t.Files = append(t.Files, "HTTPCODE 100 Continue") t.Files = append(t.Files, "HTTPCODE 101 Switching Protocols") t.Files = append(t.Files, "HTTPCODE 102 Processing") t.Files = append(t.Files, "HTTPCODE 103 Checkpoint") t.Files = append(t.Files, "HTTPCODE 122 Request...
package wallclock_test import ( "testing" "time" "github.com/r3code/wallclock" ) var dontOptimizeMePlease time.Time func BenchmarkTimeNow(b *testing.B) { for i := 0; i <= b.N; i++ { dontOptimizeMePlease = time.Now() } } func BenchmarkWallclockNow(b *testing.B) { for i := 0; i <= b.N; i++ { dontOptimizeMe...
//todo: refactor //todo: move database access to databaseaccess.go package main import ( "log" "net/http" "os" "os/signal" "syscall" "github.com/gorilla/mux" ) //setup server with REST api func setRoutesAndStartServer() { //database set schema. use only once. should be in the migration part butfor testing p...
package list import ( "encoding/json" "github.com/commitdev/kafka-connect/config" "github.com/commitdev/kafka-connect/pkg/client" "github.com/k0kubun/pp" "github.com/tidwall/pretty" ) func List(config *config.KafkaConnectorConfig, client client.KafkaConnectClient) error { results, err := client.List() if err !...