text
stringlengths
11
4.05M
package db import ( _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "github.com/spf13/viper" ) var db *gorm.DB func Init() (err error) { db, err = gorm.Open("mysql", viper.GetString("db.server")) if err != nil { return } db.SingularTable(true) if viper.GetString("log.level") == "debug" { db....
package main func main() { consumer() }
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "github.com/syndtr/goleveldb/leveldb" ) // CreateStreamRequest represents a request to create a stream type CreateStreamRequest struct { StreamName string ShardCount int } type EnhancedMonitoringData struct { ShardLevelMetrics []strin...
package pacs import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00200106 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:pacs.002.001.06 Document"` Message *FIToFIPaymentStatusReportV06 `xml:"FIToFIPmtStsRpt"` } func (d *Document002...
package core import ( "YNM3000/code/logger" "YNM3000/code/scripts" "YNM3000/code/utils" "github.com/robertkrimen/otto" ) const ( Append = "Append" Cleaning = "Cleaning" ExecCmd = "ExecCmd" CreateFolder = "CreateFolder" DeleteFile = "DeleteFile" ) // InitVM init scripting engine func (r *Ru...
package encode_test import ( "testing" "github.com/openacid/slim/encode" "github.com/stretchr/testify/require" ) func TestI8(t *testing.T) { ta := require.New(t) cases := []struct { input int8 want string wantsize int }{ {0, string([]byte{0}), 1}, {1, string([]byte{1}), 1}, {0x12, string([...
package cas import ( "fmt" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) func TestUnauthenticatedRequestShouldRedirectToCasURL(t *testing.T) { url, _ := url.Parse("https://cas.example.com/") client := NewClient(&Options{ URL: url, }) handler := client.HandleFunc(func(w http.ResponseWrite...
package endpoint import ( "context" "github.com/go-kit/kit/endpoint" "github.com/go-kit/kit/log" "github.com/mashenjun/courier/pkg/service" ) type Endpoints struct { PingEndpoint endpoint.Endpoint SubscribeEndpoint endpoint.Endpoint SendEndpoint endpoint.Endpoint CloseEndpoint endpoint.Endpoint } func New(sr...
package main import ( "encoding/json" "io/ioutil" "os" "path/filepath" "github.com/otiai10/copy" ) const ( root = "./settings-to-copy" ) type config struct { UserPath string `json:"user_path"` BackupPath string `json:"backup_path"` FoldersToSave []string `json:"folders_to_save"` FoldersT...
package migrationutils import ( "crypto/rand" "os" "path/filepath" ) // RandomSlice returns a randomly filled byte array with length of given size func RandomSlice(size int) (out []byte) { r := make([]byte, size) _, err := rand.Read(r) // Note that err == nil only if we read len(b) bytes. if err != nil { pan...
// 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 law or agreed to in writing...
// 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 caryatid import ( "flag" "fmt" "os" "path" "runtime" "testing" ) const integrationTestDirName = "integration_tests" var ( _, thisfile, _, runtimeCallerOk = runtime.Caller(0) thisdir, _ = path.Split(thisfile) integrationTestDir = path.Join(thisdir, integrationTestDir...
package model import ( "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/bson/primitive" "github.com/mongodb/mongo-go-driver/mongo" log "github.com/sirupsen/logrus" ) // SlugGenesis ... const ( SlugGenesis = "genesis" NameGenesis = "超级管理员" SlugAdmin = "admin" NameAdmin = "节点管理员...
package entities import ( "strconv" // "github.com/ventuary-lab/cache-updater/enums" ) const NEUTRINO_ORDERS_NAME = "f_neutrino_orders" type NeutrinoOrder struct { tableName struct{} `pg:"f_neutrino_orders"` OrderId *string `pg:"order_id,pk"` Currency, Owner, Status, Type *string Height uint64 OrderPrev *str...
package mill import ( "bytes" "fmt" "image" "image/color/palette" "image/draw" "image/gif" "image/jpeg" "image/png" "io" "strconv" "github.com/disintegration/imaging" "github.com/rwcarlsen/goexif/exif" ) // Format enumerates the type of images currently supported type Format string const ( JPEG Format ...
/* * @lc app=leetcode.cn id=142 lang=golang * * [142] 环形链表 II */ // @lc code=start /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ package main import "fmt" type ListNode struct { Val int Next *ListNode } func main() { v1 := &ListNode{Val: 1}...
package models type HealthConfig struct { Port int `yaml:"port"` }
package jwt import ( "github.com/gin-gonic/gin" ) const TokenKey = "Authorization" type GinJwtMiddleware struct { Signer JwtSigner Unauthorized interface{} } func (g *GinJwtMiddleware) Jwt(c *gin.Context) { token := c.Request.Header.Get(TokenKey) claims, isUpdate, err := g.Signer.Verification(token) if ...
// Copyright 2019 The go-interpreter Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !appengine package exec import ( "bytes" "runtime" "testing" "github.com/go-interpreter/wagon/disasm" "github.com/go-interpreter/...
package model import ( "strings" "time" "walletApi/src/common" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) //签名数据表 type SignData struct { Id int64 `orm:"auto" json:"id" description:"主键ID"` QrCode string `orm:"size(64)" json:"qrCode" description:"二维码标识"` //二维码 ...
package main import ( "encoding/json" "fmt" "github.com/levigross/grequests" ) func main() { netReceiveAmount, confirmations, err := ZecBlocksChainCheck(0.02588889, "t1aZ2DGuiokCxHVfb4cGQqXghxy9hUpE6xQ", "t1J7StFmqay9sWHMtUhXseLRMzvm1vLE7i7") if err != nil { fmt.Println("request failed...") return } fmt.P...
/* description : ex0101 prints the name of the command that invoked it and its command-line arguments author : Tom Geudens (https://github.com/tomgeudens/) modified : 2017/07/18 */ package main import ( "fmt" "os" "strings" ) func main() { fmt.Println("invoking command = " + os.Args[0]) fmt.Print...
package main import ( "fmt" "github.com/karantin2020/csvgen/parser" "os" ) var ( pp = parser.Parser{AllStructs: true} ) func main() { fname := "./fixture" fInfo, err := os.Stat(fname) if err != nil { return } // pp := parser.Parser{AllStructs: true} if err := pp.Parse(fname, fInfo.IsDir()); err != nil { ...
// Note the Library is a Portfolio Specific Library, Should Not be used on Schemes // Monte Carlo Simulation Algorithm : // The inputs to the process are: // 1) Start capital // 2) Annual mean return taken from the (10 portfolios) // 3) Annual mean standard deviation // 4) Number of years (observations) // 5) Number of...
package gettime import ( "log" "time" ) const ( TimeFormart = "2006-01-02 15:04:05" TimeFarmart1 = "20060102" ) func GetNowTime() (starttime string, stoptime string) { now := time.Now() yesterday, err := time.ParseDuration("-48h") if err != nil { log.Println(err) } start := now.Add(yesterday).Format(Time...
package account // NotFoundError represents account not found error type NotFoundError struct{} func (anf NotFoundError) Error() string { return "Account Not Found" } // AlreadyExistError represents account already exist error type AlreadyExistError struct{} func (aee AlreadyExistError) Error() string { return "A...
package iface import "github.com/PuerkitoBio/goquery" type IParse interface { //传入待爬地址,返回文档对象 GetDocument(url string) (*goquery.Document, error) //传入需要解析的文档对象 ParseHtml(doc *goquery.Document) }
package receiver import ( l "github.com/b2wdigital/goignite/pkg/log" natsce "github.com/cloudevents/sdk-go/v2/protocol/nats" "github.com/nats-io/nats.go" ) func NewSender(conn *nats.Conn, subject string) (*natsce.Sender, error) { sender, err := natsce.NewSenderFromConn(conn, subject) if err != nil { l.Fatalf(...
package main import "testing" func TestDaoOfficer(t *testing.T) { u := &Officer{} u.Officerid = 0 u.Name = "niko" u.Gender = 1 u.IdentityCard = "441599" u.Phone = "17396157096" u.Address = "升升公寓" u.Position = "学生" d := NewDaoOfficer() defer d.Close() d.Insert(u) }
/* The MIT License (MIT) Copyright (c) 2019 Microsoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, pu...
package model import ( "github.com/alec-z/interests-back/util" ) type ItemsInput struct { Amount float64 `json:"amount" form:"amount" query:"amount"` AnnualInterest float64 `json:"annualInterest" form:"annualInterest" query:"annualInterest"` Period int `json:"period" form:"period" query:"period"` } func (i *It...
package context import ( "sync" ) const defaultScope = "" var currentContext Context var lock sync.RWMutex type dependencyRequest struct { Type interface{} Waiter chan interface{} Scope string } type Context interface { Ask(interfaceNil interface{}) chan interface{} Reg(interfaceNil interface{}, construct...
package goproxmoxapi_test import ( "strings" "testing" "github.com/lnxbil/goproxmoxapi" ) func TestVersionAPI(t *testing.T) { t.Parallel() c, err := goproxmoxapi.New(GetProxmoxAccess()) if err != nil { t.Log(c) t.Error(err) } // test version number of the PVE pvever, err := goproxmoxapi.Get...
package business import ( "fmt" "github.com/police-police-mashed-potatoes/console" "github.com/police-police-mashed-potatoes/data" ) type FetchCycle struct { hours int location string crimeType string } func (f FetchCycle) Start(config EventsConfig) { fmt.Println("Thank you for using Police Police Mashed...
package com import ( "database/sql" "reflect" ) /** `*@数据库查询映射为对象 */ func CreateObjectResultSet(rows *sql.Rows,objects ...interface{}) { columns, err := rows.Columns(); if (nil != err) { panic("get data Columns err ,on method:CreateObjectResultSet"); } var clen int = len(columns); values := make([]interf...
package goney // Currency represents an ISO4217 currency type Currency struct { Code string Precision int32 } func (c Currency) String() string { return c.Code } // Find returns the currency having provided code, if found, // or XXX (= no currency) if not found func Find(code string) Currency { for _, curr ...
package controllers type TestController struct { BaseController } func (c *TestController)Fire() { c.Layout = "index.html" c.TplName = "demo.html" c.Data["frameName"] = c.URLFor("TestController.FireFrame") } func (c *TestController)FireFrame() { c.TplName = "demo/fire.html" } func (c *TestController)Jell...
// Package xaction provides core functionality for the AIStore extended actions. /* * Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. */ package xaction import ( "errors" "fmt" "strconv" "time" "github.com/NVIDIA/aistore/3rdparty/atomic" "github.com/NVIDIA/aistore/3rdparty/glog" "github.com...
package main import ( "archive/zip" "bufio" "fmt" "github.com/cavaliercoder/grab" "github.com/garyburd/redigo/redis" "io" "log" "net/http" "os" "path/filepath" "regexp" "sync" "time" ) // Get html page that has list of files and return the // actual URL for the webpage (after the redirect) func writeHTML...
package cmd import ( "github.com/Files-com/files-cli/lib" "github.com/spf13/cobra" files_sdk "github.com/Files-com/files-sdk-go" "fmt" "os" remote_server "github.com/Files-com/files-sdk-go/remoteserver" ) var ( RemoteServers = &cobra.Command{ Use: "remote-servers [command]", Args: cobra.ExactArgs(1), ...
package command import ( "fmt" "github.com/DmiAS/cube_cli/internal/app/cli" "github.com/DmiAS/cube_cli/internal/app/connection/tcp" "github.com/DmiAS/cube_cli/internal/app/delivery/iproto" ) const ( argsError = iota connectionError internalError argsLen = 4 ) func Run(args []string) int { if len(args) < ar...
package frenyard import ( "github.com/veandco/go-sdl2/sdl" "runtime" ) var fySDL2CRTCRegistry *crtcRegistry = newCRTCRegistryPtr() // sdl2RendererCore is the crtcContext. type sdl2RendererCore struct { base *sdl.Renderer } func (r *sdl2RendererCore) osDelete() { if r.base == nil { panic("Renderer was alrea...
package herd import ( "bytes" "os/exec" "runtime" "time" ) var ( carriageReturnLiteral = []byte{'\r'} newlineLiteral = []byte{'\n'} newlineReplacement = []byte{'\\', 'n'} ) type completionType struct { failed bool hostname string } type installerQueueType struct { entries map[string]*queueEntr...
// Shows example use of the keyring package // // May need to be built with a platform-specific build flag to specify a // provider. See keyring documentation for details. // package main import ( "os" "fmt" "github.com/tmc/keyring" ) func main() { args := os.Args[1:] if len(args) < 1 { fmt.Fprintf(os.Stderr...
package main //func test() { // defer func() { // err := recover() // if err != nil{ // fmt.Println(err) // } // }() // num1 := 10 // num2 := 0 // res := num1/num2 // fmt.Println(res) //} //func main() { // test() // fmt.Println("ok") //} //array //func main() { ////var shuzu [6]float64 ////shuzu[0] = 3.0 ////...
package colr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01400104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:colr.014.001.04 Document"` Message *InterestPaymentResponseV04 `xml:"IntrstPmtRspn"` } func (d *Document01400104)...
package main import "fmt" type ListNode struct { Val int Next *ListNode } /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil && l2 == nil { return nil } lm := new(ListNode) l...
package main import ( "fmt" "html/template" "os" rt "runtime" "strings" "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/libpod/define" "github.com/containers/libpod/pkg/adapter" "github.com/containers/libpod/version" "github.com/...
package main import "fmt" func main() { var countryCapitalMap map[string]string countryCapitalMap = make(map[string]string) countryCapitalMap["1"] = "yi" countryCapitalMap["2"] = "er" countryCapitalMap["3"] = "san" countryCapitalMap["4"] = "si" for k, v := range countryCapitalMap { fmt.Println(k, "==", v) ...
package 位运算 // ----------- 位运算解法 ----------- func singleNumber(nums []int) int { twos, ones := 0, 0 for _, num := range nums { ones = (ones ^ num) & ^twos twos = (twos ^ num) & ^ones } return ones } // ----------- bitMap解法 ----------- func singleNumber(nums []int) int { countOfBit := make([]int, 64) for _, ...
package Problem0164 func maximumGap(nums []int) int { if len(nums) < 2 { return 0 } // 自己实现了一个简易的快排 var quickSort func(i, j int) quickSort = func(i, j int) { ci, cj := i, j c := i for i < j { for nums[j] >= nums[c] && i < j { j-- } for nums[i] <= nums[c] && i < j { i++ } nums[i], n...
package datasource import ( "context" "fmt" "os" "sort" "strings" "time" "github.com/vmware/kube-fluentd-operator/config-reloader/fluentd" "github.com/vmware/kube-fluentd-operator/config-reloader/util" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "github.com/sirupsen/logrus" "gi...
package factorial import "testing" func TestFactorial(t *testing.T) { check := func(in uint, expected uint) { if out := Factorial(in); out != expected { t.Errorf("factorial of %d is %d and not %d", in, expected, out) } } check(0, 1) check(1, 1) check(2, 2) check(3, 6) check(4, 24) }
package paizaio_test import ( "net/url" "testing" "github.com/pocke/paizaio" ) var api = paizaio.NewAPI() var idCh = make(chan string, 1) var getID = func() func() string { var id string return func() string { if id != "" { return id } id = <-idCh return id } }() const code = ` package main import ...
package main import ( "fmt" "sort" ) func sumSubseqWidths(A []int) int { sort.Ints(A) const mod = 1e9 + 7 var c = 1 var res = 0 var n = len(A) for i, v := range A { res = (res+v*c - A[n-1-i]*c)%mod c = (c << 1) % mod } return res } func main() { fmt.Printl...
package main import ( "html" "regexp" "strings" ) var ( ReIgnoreBlock = map[string]*regexp.Regexp{ "doctype": regexp.MustCompile(`(?ims)<!DOCTYPE.*?>`), // raw doctype "comment": regexp.MustCompile(`(?ims)<!--.*?-->`), // raw comment "script": regexp.MustCompile(`(?ims)<sc...
package response type Maven struct { ArtifactId string `json:"artifactId"` LatestVersion string `json:"latestVersion"` GroupId string `json:"groupId"` } func (m *Maven) SetProperties(ArtifactId,GroupId ,LatestVersion string) { m.ArtifactId = ArtifactId m.LatestVersion = LatestVersion m.GroupId=G...
package caryatid import ( "encoding/json" "fmt" "testing" ) func TestJsonDecodingProvider(t *testing.T) { jstring := `{"name":"testname","url":"http://example.com/whatever","checksum_type":"dummy","checksum":"dummy"}` var prov Provider err := json.Unmarshal([]byte(jstring), &prov) if err != nil { t.Fatal(fmt...
package main import ( "net/http" "log" "io/ioutil" "github.com/json-iterator/go" cmc "github.com/coincircle/go-coinmarketcap" "net/url" "fmt" "telegram-bot-api" "strings" ) var ( json = jsoniter.ConfigCompatibleWithStandardLibrary ) func getTransactions(address string, timestamp string) (txsSuccess []Tran...
package main import "fmt" //------------------------------------------------------------------------------ // https://leetcode-cn.com/problems/total-hamming-distance/ func totalHammingDistance(nums []int) int { return totalHammingDistance2(nums) } func totalHammingDistance2(nums []int) int { const bitNum = 30 N...
package main import ( "path/filepath" "os" ) type Repo struct { mainPath string objPath string } func (r *Repo) createObjectDatabase() { dirName, err := filepath.Abs(r.mainPath + "objects") check(err) os.Mkdir(dirName, 0755) r.objPath = dirName }
package alicloud import ( "net/http" "testing" ) func TestHttpCall_Get(t *testing.T) { req, _ := http.NewRequest("GET", "http://www.baidu.com", nil) bytes, err := http_call(req) if err != nil { t.Log("output:" + string(bytes)) t.Error(err) } } func TestHttpCall_with_error(t *testing.T) { req, _ := http.Ne...
package Problem0137 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { nums []int ans int }{ { []int{43, 16, 45, 89, 45, -2147483648, 45, 2147483646, -2147483647, -2147483648, 43, 2147483647, -2147483646, -2147483648, 89, -2147483646, 89, -21474836...
type TileQueueNode struct { next *TileQueueNode tile *Tile } type TileQueue struct { current *TileQueueNode end *TileQueueNode } func (q TileQueue) push(tile *Tile) { node := &TileQueueNode{ next: nil, tile: tile, } if q.current == nil { q.current = node q.end = node } else { q.end.next = node q...
package phone_dao import ( _db "database/sql" "log" ) //查询所有部门列表 func GetAllDepartment(db * _db.DB) ([] Department,error ){ rows,err:=db.Query(`select d_id,d_name from department order by 1`) if nil!=err{ log.Fatal(err) } var ret [] Department for rows.Next() { var d * Department d=new(Department) r...
package main import ("fmt" "math") func main(){ var a,vo,so,t float64 fmt.Println("Enter value for acceleration:") fmt.Scan(&a) fmt.Println("Enter value for initial velocity:") fmt.Scan(&vo) fmt.Println("Enter value for initial displacement:") fmt.Scan(&so) fmt.Println("Enter value for time:") fmt.Scan(&t) f...
package main import ( "bufio" "log" "net" ) func main() { ln, err := net.Listen("tcp", ":2020") if err != nil { log.Fatalf("listen error: %v", err) } accepted := 0 for { conn, err := ln.Accept() if err !...
package gamesapi import ( "backend/internal/domain" "backend/internal/usecase/startgameusecase" "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) func Test_Start_a_new_game(t *testing.T) { baseP...
package main import ( "context" "log" "github.com/micro/go-micro/v2" microclient "github.com/micro/go-micro/v2/client" pb "github.com/vlasove/Lec14/usercli/proto/user" ) func main() { srv := micro.NewService( micro.Name("usercli"), micro.Version("latest"), ) srv.Init() //создаем функционал клиента ...
package middleware import ( "github.com/gin-gonic/gin" "github.com/satori/go.uuid" ) const ( RequestIDHeaderKey = "X-Request-Id" ServerHeaderValue = "MessageDB" ) func RequestIdMiddleware() gin.HandlerFunc { return func(ctx *gin.Context) { ctx.Writer.Header().Set("X-Request-Id", uuid.NewV4().String()) ctx....
// // hgps -- a resource class for caching Horizon GPS data // // Cache your Horizon GPS data in a "smart" GpsCache instance. Cache features: // - (optional) obfuscate location within specified distance from actual loc // (note that this works correctly for any location anywhere on the globe) // - (optional) can d...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/6/26 4:07 下午 # @File : lt_offer_链表反转.go # @Description : # @Attention : */ package v2 // 链表反转 func reversePrint(head *ListNode) []int { if nil == head { return nil } stack := make([]int, 0) for nil != head { stack = append(stack, head.Val) head = h...
package instance_test import ( . "github.com/onsi/ginkgo" "github.com/pivotal-cf/spring-cloud-services-cli-plugin/instance" ) var _ = Describe("Restage", operationTest("restage", instance.NewRestageOperation))
package cbs import ( "bytes" "code.google.com/p/lzma" ) func lzmaCompress(size int64, data []byte) ([]byte, error) { var buf bytes.Buffer wr := lzma.NewWriterSizeLevel(&buf, size, 9) if _, err := wr.Write(data); err != nil { return nil, err } if err := wr.Close(); err != nil { return nil, err } return bu...
package makeusers import ( "Neo/codes/jsonstruct" "Neo/codes/platform" "strings" "time" "os" "github.com/tebeka/selenium" ) var err error //Sevenmaster make sd user func Sevenmaster(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } t...
/* 转移所有图片到一个统一文件夹的工具 */ package main import ( "fmt" "io" "log" "os" "path" "sync" ) var ( // 控制程序结束栅栏 waitGroup = sync.WaitGroup{} // 文件转移线程池 fileChan = make(chan struct{}, 20) ) func main() { handTask("H:/wallpaper/P站壁纸/电脑壁纸,质量保证", "images/横屏") handTask("H:/wallpaper/P站壁纸/电脑壁纸,质量保证", "images/竖屏") han...
package controller import ( "fmt" "make_invoice/model" "make_invoice/service" "net/http" "strconv" "github.com/gin-gonic/gin" ) func AddInvoice(c *gin.Context) { invoice := &model.Invoice{} binderr := c.Bind(invoice) if binderr != nil { c.String(http.StatusBadRequest, "Bad request") ...
package ui import ( "fmt" "github.com/askovpen/gocui" "log" ) func setCurrentViewOnTop(g *gocui.Gui, name string) (*gocui.View, error) { if _, err := g.SetCurrentView(name); err != nil { return nil, err } return g.SetViewOnTop(name) } // Layout default func Layout(g *gocui.Gui) error { maxX, maxY := g.Size(...
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -o ../../fakes/fake_strategy.go resolver.go Strategy //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -o ../../fakes/fake_strategy_installer.go resolver.go StrategyInstaller //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -o ../../...
package datastore import ( "context" "testing" ) func TestSaveStruct_Basic(t *testing.T) { ctx := context.Background() type Data struct { Str string } ps, err := SaveStruct(ctx, &Data{"Test"}) if err != nil { t.Fatal(err) } if v := len(ps); v != 1 { t.Fatalf("unexpected: %v", v) } p := ps[0] if ...
package server import ( "strconv" "github.com/Tanibox/tania-core/src/assets/domain" "github.com/Tanibox/tania-core/src/assets/storage" "github.com/gofrs/uuid" ) func (rv *RequestValidation) ValidateReservoir(s FarmServer, reservoirUID uuid.UUID) (storage.ReservoirRead, error) { result := <-s.ReservoirReadQuery....
package NoQ_RoomQ_Exception type InvalidApiKeyException struct{} func (ex *InvalidApiKeyException) Error() string { return "Invalid api key" }
// Copyright © 2018 NAME HERE <EMAIL ADDRESS> // // 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 ...
package sequence import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) type Sequence_Student struct { Key string `json:"student_id_seq"` Number int `json:"number"` } func GetNextID(col *mongo.Collection, seq string) int { var sequence Sequence_Student filter...
// Licensed to SolID under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. SolID licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
package run import ( "sync" floc "gopkg.in/workanator/go-floc.v1" ) /* RaceLimit runs jobs in their own goroutines and waits until first N jobs finish. During the race only first N calls to update are allowed while further calls are discarded. Before starting the race the function synchronizes start of the each jo...
package spec import ( "testing" "github.com/stretchr/testify/assert" ) var ( defaultSpec = &Spec{ Config{ HTTPPort: 8080, HTTPSPort: 8443, }, []HTTPMock{ HTTPMock{ HTTPExpect: HTTPExpect{ Methods: []string{"GET"}, Path: "/", Prefix: false, Queries: nil, Headers: ni...
package models import ( "fmt" "github.com/hxangel/dogo" db "github.com/hxangel/bot/libs/db" utils "github.com/hxangel/bot/libs/utils" "strings" ) type Model struct { TableName string PrimaryKey string Data map[string]string where string args []interface{} limit string orderby string groupby s...
package levels import ( "fmt" "os" "os/exec" "os/signal" "regexp" "strings" "syscall" "time" ) func CmdOK(cmd string) (bool, string) { if cmd == "" { return true, "" } output, err := exec.Command("sh", "-c", cmd).Output() return err == nil, string(output) } var key_pressed = false func print_line(text...
package identity import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestClaims_Flatten(t *testing.T) { var claims Claims _ = json.Unmarshal([]byte(` { "a": { "aa": { "aaa": 12345 }, "ab": [1, 2, 3, 4, 5] } } `), &claims) flattened := claims.Flatten() as...
package v1 import ( "github.com/coreos/prometheus-operator/pkg/client/versioned" "k8s.io/client-go/rest" ) type PrometheusMonitoringInterface interface { PrometheusGetter PrometheusRulesGetter //ServiceMonitorsGetter } type PrometheusMonitoring struct { client *versioned.Clientset } func NewForConfig(c *rest....
package httputil import ( "bytes" "io/ioutil" "net/http" ) // FakeTransport represents a fake http.Transport that returns prerecorded responses. type FakeTransport struct { responses map[string]*responseCollection } // NewFakeTransport creates a new FakeTransport instance without any responses. func NewFakeTrans...
package main import ( "math/rand" "time" "golang.org/x/mobile/app" "golang.org/x/mobile/event/key" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/paint" "golang.org/x/mobile/event/size" "golang.org/x/mobile/event/touch" "golang.org/x/mobile/exp/gl/glutil" //"golang.org/x/mobile/exp/sprite/...
package main // 한글 '가' 부터 '갛' 까지 unicode 값을 사용하여 출력하는 예제 import "fmt" func main() { start := 44032 end := 44059 for i := start; i<=end; i++{ fmt.Print(string(i)) } }
package sort import ( "github.com/google/go-cmp/cmp" "math/rand" "sort" "testing" "time" ) func generateRandomSlice(maxSize, maxValue int) ([]int, []int) { rand.Seed(time.Now().UnixNano()) nums1 := make([]int, rand.Intn(maxSize+1)) nums2 := make([]int, len(nums1)) for i := 0; i < len(nums1); i++ { // 表达式后面...
package main import ( "fmt" "log" "os" ) func main() { archivo := "prueba.txt" f, err := os.Open(archivo) // defer no se ejecuta secuencialmente, solo lo hace al final defer f.Close() if err != nil { fmt.Println("error abriendo el archivo") // os.Exit(1) } ejemploPanic() } func ejemploPanic() { // de...
package common import ( "github.com/google/logger" . "myproj.com/clmgr-coordinator/config" "os" ) func InitLogger() error { lf, err := os.OpenFile(Config.LogCoordPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660) if err != nil { logger.Fatalf("Failed to open log file: %v", err) } logger.Init("Logger", false, ...
package main import ( "fmt" "os" ) func main() { fp, err := openFile(os.Args[1]) if err != nil { os.Exit(1) } fmt.Println(string(readFile(fp))) os.Exit(0) } func openFile(filename string) (*os.File, error) { fp, err := os.Open(filename) if err != nil { fmt.Println("Error while opening the file with name...
package diff import ( "bytes" "database/sql" "fmt" "github.com/ngaut/log" "github.com/onsi/gomega" "github.com/pingcap/errors" ) func init() { log.SetLevelByString("error") } // Diff contains two sql DB, used for comparing. type Diff struct { cfg *Config db1 *sql.DB db2 *sql.DB } // New returns a Diff in...