text
stringlengths
11
4.05M
package models import "github.com/astaxie/beego/orm" type Status struct { Id int Name string `orm:"unique"` } func (s *Status) Insert() error { if _, err := orm.NewOrm().Insert(s); err != nil { return err } return nil } func (s *Status) Read(fields ...string) error { if err := orm.NewOrm().Read(s, fields....
package database import ( "context" "fmt" "log" "os" "github.com/jackc/pgx/v4/pgxpool" ) const errMsgConnection = "The environment variable '%s' is not defined, it is required to establish a connection with the database" var dBVariables = [...]string{"CTIPO_DB_NAME", "CTIPO_DB_HOST", "CTIPO_DB_USERNAME", "CTIP...
package app import "github.com/thoohv5/template/internal/pkg/config" type IApp interface { GetConfig() config.IConfig Run(addr ...string) error }
package main import ( "bufio" "fmt" "os" ) func main() { counts := make(map[string]int) files := os.Args[1:] if len (files) == 0 { countLines(os.Stdin, counts) } else { for _, arg := range files { f, err := os.Open(arg) /*os.Open returns two values. First - opened file (*os.File). Fi...
// Copyright 2013-2014 go-diameter authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package diamtype import "fmt" // Grouped Diameter Type type Grouped []byte func DecodeGrouped(b []byte) (DataType, error) { return Grouped(b), ni...
// Copyright 2021 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 main import ( "context" "fmt" "net/http" "os" "os/signal" "time" "github.com/gorilla/mux" "github.com/hrishin/pokemon-shakespeare/pkg/pokemon" "github.com/op/go-logging" ) var log = logging.MustGetLogger("pokemon") func main() { wait := time.Second * 15 port := 5000 r := mux.NewRouter() r.Hand...
package main import ( "fmt" ) func main() { // panic produces a quick exit panic("Jim, we have a problem.") fmt.Println("You will not even see this line. The panic creates a fast fail.") }
package main import ( "bytes" "flag" "fmt" "log" "math/rand" "os" "sort" "text/template" "time" "github.com/yanzay/tbot" ) var local = flag.Bool("local", false, "Launch bot without webhook") var dataFile = flag.String("data", "tamago.db", "Database file") type application struct { petStore *PetStorag...
package main import ( "fmt" hyperclient "github.com/Cloud-Foundations/Dominator/hypervisor/client" "github.com/Cloud-Foundations/Dominator/lib/errors" "github.com/Cloud-Foundations/Dominator/lib/log" "github.com/Cloud-Foundations/Dominator/lib/srpc" fm_proto "github.com/Cloud-Foundations/Dominator/proto/fleetma...
/* * Copyright © 2019-2022 Software AG, Darmstadt, Germany and/or its licensors * * SPDX-License-Identifier: Apache-2.0 * * 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://...
package leetcode import "testing" func TestTribonaci(t *testing.T) { if tribonacci(4) != 4 { t.Fatal() } if tribonacci(25) != 1389537 { t.Fatal() } }
package main import "fmt" import "math" const ( width,height=600,320 cells =100 xyrange =30.0 xyscale =width /2/xyrange zscale =height*0.4 ) func main() { }
package configuration const ( // ServerVersion specifies the current GOST Server version ServerVersion string = "v0.3" // SensorThingsAPIVersion specifies the supported SensorThings API version SensorThingsAPIVersion string = "v1.0" )
package clitest import ( "encoding/json" "fmt" "os" "testing" "github.com/cosmos/cosmos-sdk/cmd/gaia/app" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/tests" ) var ( democoindHome = "" democliHome = "" ) func init() { democoindHome, democli...
package main import ( "fmt" ) var tabla [10]int func main() { tabla[0] = 1 tabla[5] = 15 fmt.Println(tabla) vector := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} fmt.Println(vector) for i := 0; i < len(vector); i++ { fmt.Println(vector[i]) } //matrices var matriz [3][3]int matriz[2][2] = 1 fmt.Println(ma...
package sheetsproxy import ( "bytes" "context" "encoding/json" "fmt" "github.com/google/go-cmp/cmp" "github.com/jakubincloud/sheetsproxy/sheetsproxy/util" "io" "io/ioutil" "log" "net/http" "net/http/httptest" "strings" "testing" "time" ) func TestHelloHTTP(t *testing.T) { var buf bytes.Buffer log.SetO...
package onelogin import ( "errors" ) func ErrorOcurred(err error)(error) { logger.Errorf("An error occurred, %s", err.Error()) return errors.New("An error ocurred.") }
package controllers import ( "encoding/json" "fmt" "github.com/revel/revel" "log" "testapp/app/dbmanager" "testapp/app/providers" ) type TaskController struct { *revel.Controller model *providers.TaskModel } func (c *TaskController) Init() *TaskController { c.model = providers.NewTaskModel() c.model.DB = d...
package structs type Pods []Pod type Pod struct { Name string `json:"name"` CPURequest float64 `json:"cpuRequest"` MemoryRequest float64 `json:"memoryRequest"` Zone string `json:"zone"` } type TotalReq struct { A_totalCPU float64 A_totalMemory float64 B_totalCPU float64 B_totalMe...
package handler import "net/http" type RoundTripperMock struct { RoundTripFunc func(req *http.Request) (*http.Response, error) } func (rt *RoundTripperMock) RoundTrip(req *http.Request) (*http.Response, error) { return rt.RoundTripFunc(req) }
package psql import ( "bytes" "strconv" ) func (c *compilerContext) alias(alias string) { c.w.WriteString(` AS `) c.quoted(alias) } func aliasWithID(w *bytes.Buffer, alias string, id int32) { w.WriteString(` AS `) w.WriteString(alias) w.WriteString(`_`) int32String(w, id) } func colWithTableID(w *bytes.Buff...
package leetcode import "testing" func TestBackspaceCompare(t *testing.T) { if backspaceCompare("ab#c", "ad#c") != true { t.Fatal() } if backspaceCompare("ab##", "c#d#") != true { t.Fatal() } if backspaceCompare("a##c", "#a#c") != true { t.Fatal() } if backspaceCompare("a#c", "b") != false { t.Fatal() ...
package config // ConverterFFmpegConfig stores the configuration for the FFmpeg program type ConverterFFmpegConfig struct { ExecutableName string }
// package auth will encapsulate authentication backends such as facebook, oauth, google auth... // For now auth only implements the use of our userservice backend. package auth import ( "net/http" "github.com/gin-gonic/gin" "github.com/pkg/errors" "github.com/totalsynthesis/autoromance/lib/userservice" ) // Aut...
package win32 // Handle is a handle to an object. type Handle uintptr // HBitmap is a handle to a bitmap. type HBitmap Handle // HBrush is a handle to a brush. type HBrush Handle // HColorSpace is a handle to a color space. type HColorSpace Handle // HConv is a handle to a DDE conversation. type HConv Handle // H...
/* Copyright 2020 Humio https://humio.com 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, ...
package controller import ( "github.com/gin-gonic/gin" ) // ListAccounts godoc // @Summary List Account // @Description get Account libs // @Tags account // @Accept json // @Produce json // @Success 200 {object} protocol.AccountPaginator // @Failure 400 {object} protocol.Error // @Failure 404 {object} protocol.Er...
package algorithm func Calculate(calc string, operator1 float64, operator2 float64) float64 { switch calc { case "mul": return operator1 * operator2 case "sub": return operator1 - operator2 case "add": return operator1 + operator2 case "div": return operator1 / operator2 default: return 0 ...
package checkout import ( "flag" "fmt" "io" "os" ) // Constants CheckoutPath and ProductsPath serve as default paths to JSON data files should they not be given. const ( // Default checkout data filePath CheckoutPath = "./checkout_data.json" // Default price data filePath ProductsPath = "./product_data.json"...
package models import ( "dappapi/global/orm" "fmt" ) type Perm struct { Id int `gorm:"column:permid;" json:"permid"` Roleid int32 `gorm:"column:roleid;" json:"roleid"` } func (p *Perm) TableName() string { return "role_permissions" } func (p *Perm) GetByRoleid(roleid int) (permList []*Perm, err error) { ...
package common import ( "encoding/base64" "fmt" "net/http" "strings" "time" "github.com/root-gg/utils" ) // Ensure HTTPError implements error var _ error = (*HTTPError)(nil) // HTTPError allows to return an error and a HTTP status code type HTTPError struct { Message string Err error StatusCode i...
package tiled import ( "encoding/xml" "fmt" "io/ioutil" "os" ) // TileMap represents a Tiled Map type TileMap struct { XMLName xml.Name `xml:"map"` Height int `xml:"height,attr"` Infinite bool `xml:"infinite,attr"` NextLayerID int `xml:"nextlayerid,attr"` NextObjectID int `xml:"nex...
package miner import ( "testing" "github.com/filecoin-project/go-state-types/abi" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDeadlineAssignment(t *testing.T) { const partitionSize = 4 type deadline struct { liveSectors, deadSectors uint64 expectSectors ...
package routers_test import ( "bytes" "github.com/haithanh079/go-leaderboard/routers" "github.com/stretchr/testify/assert" "net/http" "net/http/httptest" "testing" ) func TestLeaderboardRouters(t *testing.T) { router := routers.Router{} router.Init(true) w := httptest.NewRecorder() /* Ping to Get Leaderboa...
package netipv4 import ( "encoding/binary" "errors" "net" ) // Get IPv4 list from IPNET func GetIPv4AddressesFromNet(netAddr *net.IPNet) (out []net.IP, err error) { var ipv4 net.IP if ipv4 = netAddr.IP.To4(); ipv4 == nil { err = errors.New("It's not ip version 4 address") return nil, err } num := binary....
package game_map import ( "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/steelx/go-rpg-cgm/gui" ) type ArenaCompleteState struct { Stack *gui.StateStack prevState gui.StackInterface captions gui.SimpleCaptionsScreen } func ArenaCompleteStateCreate(stack *gui.StateStack, prevStat...
package flyingbehavior type FlyWithWings struct {} func (FlyWithWings) Fly() string { return "I am flying with wings" }
package _283_Move_Zeroes func moveZeroes(nums []int) { if len(nums) == 0 || len(nums) == 1 { return } for i := 0; i < len(nums); i++ { if nums[i] != 0 { continue } // 如果发现0了,向后找第一个不是0的交换, j := i + 1 for j <= len(nums)-1 && nums[j] == 0 { j++ } if j >= len(nums) { // 后面全是0 return } // 找到...
package main import ( "sync" ) type deal struct { table *table communityCards []*card } func newDeal(table *table) *deal { newDeal := deal{ table: table, communityCards: make([]*card, 0), } return &newDeal } // dealFlops deals 2 cards for each player. func (r *deal) dealFlops() { for _...
package main import ( "fmt" "math/rand" ) func main() { doneChan := make(chan bool) stream := getProducer(doneChan) for i := 0; i < 5; i++ { fmt.Printf("%d. Value %d\n", i+1, <-stream) } close(doneChan) fmt.Println("Done!") } func getProducer(done <-chan bool) <-chan int { stream := make(chan int) go...
// CereVoice Cloud API Library for Go // https://www.cereproc.com/files/CereVoiceCloudGuide.pdf // This is a pre-release version and is subject to change // Copyright 2018 Bryan Anderson (https://www.bganderson.com) // Relesed under a BSD-style license which can be found in the LICENSE file package cerevoicego impor...
package models import ( "github.com/jinzhu/gorm" "github.com/satori/go.uuid" "time" ) type BaseModel struct { ID uuid.UUID `gorm:"type:uuid;primary_key" json:"id"` // Date auto generation by gorm CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time } // Auto generate uuid on new record func (BaseMod...
package api import ( "net/http" "time" "github.com/direktiv/direktiv/pkg/util" "github.com/direktiv/direktiv/pkg/version" "github.com/gorilla/mux" "go.uber.org/zap" "google.golang.org/protobuf/types/known/emptypb" ) var logger *zap.SugaredLogger // Server struct for API server. type Server struct { logger *...
package proxy import ( "net" "strconv" "strings" "golang.org/x/net/dns/dnsmessage" "github.com/nextdns/nextdns/resolver" ) func replyNXDomain(q resolver.Query, buf []byte) (n int, i resolver.ResolveInfo, err error) { var p dnsmessage.Parser h, err := p.Start(q.Payload) if err != nil { return 0, i, err } ...
package exchange import ( "context" "fmt" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCSVFeed(t *testing.T) { feed, err := NewCSVFeed("1d", PairFeed{ Timeframe: "1d", Pair: "BTCUSDT", File: "../../testdata/btc-1d.csv", }) candle ...
package main import ( "encoding/json" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "log" "net/http" "net/http/httptest" "testing" ) const message = "message" var drinkList = [3]string{"beer", "wine", "coke"} func TestPingPong(t *testing.T) { // Build our expected body body := gin.H{ me...
package bslib import ( "fmt" "time" ) type SettingInfo struct { DatabaseId string `json:"database_id"` } const sqlCreateTableSettings = ` CREATE TABLE IF NOT EXISTS settings ( database_id CHAR PRIMARY KEY NOT NULL, keyword CHAR NOT NULL, crypt_id CHAR NOT NULL, database_version INT...
package lintcode /** * @param nums: A list of integers * @return: A integer indicate the sum of max subarray */ func maxSubArray(nums []int) int { maxNum := nums[0] result := nums[0] for i := 1; i < len(nums); i++ { // dp[i+1]=max(dp[i],dp[i]+dp[i+1]) maxNum = max(maxNum+nums[i], nums[i]) if maxNum > resul...
package rtmp import ( "fmt" "net/url" "reflect" "strings" "time" "github.com/ubinte/livego/av" "github.com/ubinte/livego/protocol/rtmp/core" "github.com/ubinte/livego/utils/uid" log "github.com/sirupsen/logrus" ) type VirWriter struct { Uid string closed bool av.RWBaser conn StreamReadWriteCl...
package middleware import ( "log" "net/http" "github.com/Kaukov/gopher-translator/handlers" "github.com/Kaukov/gopher-translator/utils" ) var storedData utils.Storage = utils.Storage{ Words: make(map[string]string), Sentences: make(map[string]string), } // NewTranslatorStorage - returns a storage middlewa...
package repositories import ( "io/ioutil" "net/http" "net/url" "os" ) // NewsAPIRepository is a repository to dealing with NewsAPI. type NewsAPIRepository struct { Client *http.Client } // NewNewsAPIRepository returns an instance of NewsAPIRepository. func NewNewsAPIRepository() *NewsAPIRepository { client := ...
package handlers import ( "testing" "github.com/decentraland/content-service/mocks" "github.com/golang/mock/gomock" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" ) func TestValidateRequestSize(t *testing.T) { mockController := gomock.NewController(t) defer mockController.Finish() for ...
package main import "fmt" func main() { a, b := "100", "10" fmt.Println(addBinary(a, b)) } func addBinary(a string, b string) string { p, q := a, b if len(a) < len(b) { p, q = b, a } pLen, qLen := len(p), len(q) res := "" j := 0 carry := 0 for i := pLen - 1; i >= 0; i-- { tmp := 0 if qLen >= pLen-i {...
// Copyright 2019 GoAdmin Core Team. All rights reserved. // Use of this source code is governed by a Apache-2.0 style // license that can be found in the LICENSE file. package language import "strings" var cn = LangSet{ "managers": "管理员管理", "name": "用户名", "nickname": "昵称", "role": "角色", "createdat"...
package test import ( "fmt" "reflect" "testing" ) func init() { } func IsEmpty(a interface{}) bool { v := reflect.ValueOf(a) fmt.Println("kind:", v.Kind()) //fmt.Println("kindOf:",reflect.KindOf(a)) switch v.Kind() { case reflect.Invalid: { return true } case reflect.Ptr: { return v.IsNil() }...
// 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...
// Copyright 2019 The Dice Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by app...
package ds func Repeat(c string) string { var res string for i := 0; i < 5; i++ { res = res + c } return res }
/* * @Description: * @Author: JiaYe * @Date: 2021-04-12 13:08:03 * @LastEditTime: 2021-04-12 13:16:33 * @LastEditors: JiaYe * @Descripttion: * @version: */ package main import "fmt" func main() { /* 多个defer,先defer的最后被执行 */ defer func() { fmt.Println("defer 1") }() defer func() { ...
package integration import ( "context" "fmt" "io/ioutil" "log" "os" "path" "testing" "time" "bldy.build/build" "bldy.build/build/builder" "bldy.build/build/graph" ) var tests = []struct { name string label string err error }{ { name: "empty", label: "//empty:nothing", err: nil, }, { na...
// Copyright 2020 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable ...
package main import ( "reflect" "testing" ) func TestSorter(t *testing.T) { tests := []struct { name string args flags filename string want []string wantErr bool }{ { name: "simple sort", args: flags{}, filename: "data.txt", want: []string{"Apple", "BOOK", "Book", ...
package main import "fmt" /* 一个结构体就是一个成员变量的集合 结构体的成员变量使用点号来访问,类似于javascript的对象一样 */ /* Go 有指针,但没有指针运算 结构体成员变量可以通过结构体指针来访问。 通过指针的间接访问也是透明的 */ type Classes struct { student string teacher string } /* 结构体有自己的一种文法 structName{} 通过结构体成员变量的值作为列表来新分配一个结构体 使用key: value 预发可以仅列出部分字段(顺序无所谓) 特殊的前缀&构造了指向结构体文法的指针 */ type Ver...
package rabbit import ( "common/clog" "github.com/streadway/amqp" "strconv" ) type QueMsg <-chan amqp.Delivery type Rabbit struct { Host string Port int user string pw string conn *amqp.Connection ch *amqp.Channel sque amqp.Queue rque amqp.Queue } type RabbitMgr interface { ConnectRabbit(host strin...
package tonberry import ( "github.com/zeroshade/Go-SDL/sdl" "image" ) type Camera struct { sdl.Rect } func NewCamera(bounds image.Rectangle) Camera { var c Camera c.Rect = sdl.RectFromGoRect(bounds) return c } type Screen struct { *sdl.Surface } type Event interface { sdl.Event } type QuitEvent struct { ...
package ds import ( "fmt" "math" ) type MaxHeap struct { Nodes []int } func NewMaxHeap(arr []int) *MaxHeap{ heap := MaxHeap{} for _, num := range arr { heap.Add(num) } return &heap } func (heap *MaxHeap) Add(value int) { heap.Nodes = append(heap.Nodes, value) heap.Heapify(len(heap.Nodes)-1, value) } fu...
package service import ( "context" "fmt" "testing" "time" "github.com/go-ocf/cloud/resource-aggregate/cqrs/eventbus/nats" pbCQRS "github.com/go-ocf/cloud/resource-aggregate/pb" pbRS "github.com/go-ocf/cloud/resource-directory/pb/resource-shadow" kitNetGrpc "github.com/go-ocf/kit/net/grpc" "github.com/go-ocf/...
package datastruct import "fmt" func ExampleQueue() { // test for type int intQueue := NewQueue(10) intQueue.Push(10) intQueue.Push(1) intQueue.Push(-5) fmt.Println(intQueue.Front()) intQueue.Pop() intQueue.Push(5) for !intQueue.IsEmpty() { fmt.Println(intQueue.Front()) intQueue.Pop() } // test for...
package rpc import ( "context" "time" mlog "github.com/jinmukeji/go-pkg/v2/log" "github.com/micro/go-micro/v2/server" "github.com/sirupsen/logrus" ) var ( // log is the package global logger log = mlog.StandardLogger() ) const ( logCidKey = "cid" logLatencyKey = "latency" logRpcCallKey = "rpc.call" ...
package dto import ( "github.com/artrey/go-bank-service/pkg/models" ) type Transaction struct { Id int64 `json:"id"` From *Card `json:"from"` To *Card `json:"to"` Sum int64 `json:"sum"` Mcc *Mcc `json:"mcc"` Icon *Icon `json:"icon"` Description *str...
package main import ( "bufio" "flag" "fmt" "github.com/climber73/tendermint-challenge/worldx" "os" "path/filepath" "strings" ) func main() { n := flag.Int("n", 3, "number of rows") m := flag.Int("m", 3, "number of cols") path := flag.String("path", "", "path to map file") flag.Parse() if len(*path) == 0 ...
package main import ( "io" "github.com/prologic/toybox/applets/arp" "github.com/prologic/toybox/applets/ash" "github.com/prologic/toybox/applets/base64" "github.com/prologic/toybox/applets/basename" "github.com/prologic/toybox/applets/cat" "github.com/prologic/toybox/applets/chgrp" "github.com/prologic/toybox...
package utils import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "math/rand" "net" "runtime" "strconv" "strings" "text/scanner" "time" "unicode" "unsafe" "github.com/skoo87/log4go" ) // FormatJSONStr format no-stand json str func FormatJSONStr(str string) string { replacer := strings.N...
/* You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times: Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1. Return the ...
package renderer import ( "io" "io/ioutil" "log" "path/filepath" "os" ) type RenderContext struct { BaseDir string } func NewRenderContext() RenderContext { path, err := ioutil.TempDir("", "render-context") if err != nil { log.Fatal(err) } copyStyle(path) path = filepath.ToSlash(path) rc := RenderCo...
/* SPDX-License-Identifier: Apache-2.0 * Copyright (c) 2019 Intel Corporation */ package ngcnef import "context" /* The SB interface towards the AF for sending the notifications received from different NF's */ // AfNotification definesthe interfaces that are exposed for sending // nofitifications towards the AF...
package index import ( "io/ioutil" "os" "testing" ) var postFiles = map[string]string{ "file0": "", "file1": "Tester Code Search", "file2": "Tester Code Project Hosting", "file3": "Tester Web Search", } func tri(x, y, z byte) uint32 { return uint32(x)<<16 | uint32(y)<<8 | uint32(z) } func TestTrivialPosting...
package test import ( // "fmt" "testing" // "portal/service" // "portal/database" ) // func TestSignin(t *testing.T) { // id, name := service.Signin("test@qq.com", "123456") // if id != 1 { // t.Error("查询错误", id, name) // } // } // func TestQueryUser(t *testing.T) { // res, err := service.QueryUserList(...
package app import "github.com/stretchr/testify/mock" import "github.com/bryanl/dolb/entity" type MockLoadBalancerFactory struct { mock.Mock } func (_m *MockLoadBalancerFactory) Build(bootstrapConfig *BootstrapConfig) (*entity.LoadBalancer, error) { ret := _m.Called(bootstrapConfig) var r0 *entity.LoadBalancer ...
package products import ( "context" "fmt" "log" "os" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) var DB *mongo.Database // DBConnect : Function for return a Mongo DB client func DBConnect() { // Set client options clientOptions := options.Client().ApplyURI(os.Getenv("M...
package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", handler) /*If we get request to "/*", call handler function*/ http.ListenAndServe(":9000", nil) //Port adress } //Answer to port:9000 request func handler(w http.ResponseWriter, r *http.Request) { //request handler fmt.Fprint(w, "Hell...
/* ** Copyright 2019 Bloomberg Finance L.P. ** ** 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 applicab...
package api func Create(titre string, description string, dueDate int) (error, int) { var myTodo Todo myTodo.Titre = titre myTodo.Description = description myTodo.DueDate = dueDate myTodo.Id = ClePrimaire ClePrimaire++ Todos = append(Todos, myTodo) return nil, ClePrimaire }
package handler import ( "os" "time" "github.com/openfaas/nats-queue-worker/nats" ) type NATSConfig interface { GetClientID() string GetMaxReconnect() int GetReconnectDelay() time.Duration } type DefaultNATSConfig struct { maxReconnect int reconnectDelay time.Duration } func NewDefaultNATSConfig(maxRecon...
// Package lexer contains the code to lex input-programs into a stream // of tokens, such that they may be parsed. package lexer import ( "fmt" "strings" "unicode" "github.com/kasworld/nonkey/enum/tokentype" "github.com/kasworld/nonkey/interpreter/token" ) // Lexer holds our object-state. type Lexer struct { /...
package resolvers import ( "context" "github.com/syncromatics/kafmesh/internal/graph/generated" "github.com/syncromatics/kafmesh/internal/graph/model" "github.com/pkg/errors" ) //go:generate mockgen -source=./processorOutput.go -destination=./processorOutput_mock_test.go -package=resolvers_test // ProcessorOut...
// Copyright 2016 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 mint import ( "github.com/irisnet/irishub/app/v1/mint/tags" sdk "github.com/irisnet/irishub/types" ) // Called every block, process inflation on the first block of every hour func BeginBlocker(ctx sdk.Context, k Keeper) sdk.Tags { ctx = ctx.WithLogger(ctx.Logger().With("handler", "beginBlock").With("module...
package api import ( "github.com/jlyon1/Burndown/database" "time" ) type API struct { Database database.DB Key string } type Label struct { Name string `json:"name"` } type Issue struct { Name string `json:"title"` Number int `json:"number"` State string `json:"state"` Created time.Ti...
package tomltest type versionSpec struct { inherit string exclude []string } var versions = map[string]versionSpec{ "next": versionSpec{ exclude: []string{ "invalid/datetime/no-secs", // Times without seconds is no longer invalid. "invalid/string/basic-byte-escapes", // \x is now valid. "invali...
package example_test import ( "testing" "time" "github.com/bearchit/goclock/example" "github.com/bearchit/goclock" ) func TestApp_NewUser_Realtime(t *testing.T) { clock := goclock.New() now := clock.Now() app := example.App{ Clock: clock, } user := app.NewUser("mock") if user.CreatedAt == now { t.Fa...
package mt import ( "math" "time" ) type ToolCaps struct { //mt:if _ = %s; false NonNil bool //mt:end //mt:lenhdr 16 //mt:ifde //mt:if r.N > 0 { %s.NonNil = true}; /**/ //mt:if %s.NonNil // Version. //mt:const uint8(5) AttackCooldown float32 MaxDropLvl int16 //mt:len32 GroupCaps []ToolGroupCap...
/* Copyright (c) 2014-2015, Daniel Martí <mvdan@mvdan.cc> */ /* See LICENSE for licensing information */ package jutgelint import ( "encoding/json" "io" "os/exec" ) const ( CheckDeadAssign int = 1 << iota CheckFors CheckLocalDecl CheckVariableInit CheckAll int = -1 ) var optArgs = map[int]string{ CheckDea...
package vo import "go-gin-start/app/ent" /** * Value Object Converter * 关于 VO 类型数据的相关转换器,通常实现 PO2VO、VO2VO、ANY2MAP */ // One Po -> One Vo func (*User) FromPo(item *ent.User) *User { return &User{ UserName: item.UserName, Password: item.Password, } } // Some Po -> Some Vo func (o *User) FromSomePo(items []*e...
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type AlterDefaultPrivilegesStmt struct { Options *ast.List Action *GrantStmt } func (n *AlterDefaultPrivilegesStmt) Pos() int { return 0 }
package datatype import ( "github.com/emicklei/go-restful" api "github.com/emicklei/go-restful-openapi" . "grm-service/util" "data-manager/dbcentral/pg" . "data-manager/types" ) type DataTypeSvc struct { SysDB *pg.SystemDB } // WebService creates a new service that can handle REST requests for resources. fun...
package ws type Message struct { Host string `json:"host"` Name string `json:"name"` Text string `json:"text"` } func (self *Message) String() string { return self.Host + "::" + self.Name + "::" + self.Text }
package controller import ( "testing" "time" "github.com/reef-pi/reef-pi/controller/storage" "github.com/reef-pi/reef-pi/controller/telemetry" ) func TestHomestasis(t *testing.T) { store, err := storage.TestDB() if err != nil { t.Fatal(store) } config := HomeoStasisConfig{ Name: "test", Upper: "1", ...
package main import ( "fmt" ) func main() { a := 1 b := 1 fmt.Println(a) for i := 0; i < 60; i++ { fmt.Println(b) tmp := a a = b b = tmp + a } }