text
stringlengths
11
4.05M
package main import ( "bufio" "fmt" "io" "os" ) func CopyFile(dstName, srcName string) (w int64, err error) { //打开已存在的源文件,构造reader srcFile, err := os.Open(srcName) if err != nil { fmt.Printf("err=%v\n", err) return } defer srcFile.Close() reader := bufio.NewReader(srcFile) //打开要copy的路径,如果没有就创建,构造wri...
package main import ( "fmt" "github.com/jackytck/projecteuler/tools" ) func pandigitalPrime(upper int) int { var ans int primes := tools.SievePrime(upper) for i := len(primes) - 1; i >= 0; i-- { p := primes[i] if tools.IsPandigital(p) { ans = p break } } return ans } func main() { fmt.Println(pa...
// Copyright (c) 2017, Xiaomi, Inc. All rights reserved. // This source code is licensed under the Apache License Version 2.0, which // can be found in the LICENSE file in the root directory of this source tree. package pegasus import ( "bytes" "context" "errors" "fmt" "math" "sort" "sync" "testing" "time" ...
package main import ( "log" "net/http" "github.com/gorilla/mux" ) func main() { // create Gorilla mux router r := mux.NewRouter() // serve static files r.Handle("/", http.FileServer(http.Dir("./static/"))) r.PathPrefix("/dist/").Handler(http.FileServer(http.Dir("./static/"))) log.Fatal(http.ListenAndServe...
// Copyright 2022 Google LLC. 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 applica...
package auth import ( "sync" "golang.org/x/crypto/bcrypt" "github.com/ipastushenko/simple-chat/server/models" ) //TODO: test user var password, _ = bcrypt.GenerateFromPassword( []byte("password"), bcrypt.DefaultCost, ) var testUser = &models.User{ Username: "test", Password: string(passwor...
package request import ( "context" b64 "encoding/base64" "encoding/json" "strings" "github.com/pivotal-cf/brokerapi/v8/middlewares" ) func DecodeOriginatingIdentityHeader(ctx context.Context) map[string]interface{} { var originatingIdentityMap map[string]interface{} originatingIdentityHeader := ctx.Value(mid...
// // Licensed to 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. Apache Software Foundation (ASF) licenses this file to you under // the Apache License, Version 2.0 (the ...
package core import ( peer "github.com/libp2p/go-libp2p-core/peer" mh "github.com/multiformats/go-multihash" "github.com/textileio/go-textile/crypto" "github.com/textileio/go-textile/pb" ) // AddInvite creates an outgoing add block, which is sent directly to the recipient // and does not become part of the hash c...
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
package handler import ( "net/http" "github.com/gin-gonic/gin" ) // 状态码 const ( Success = iota // 成功 ) // Response 响应 type Response interface{} type response struct { Code int `json:"code"` Data interface{} `json:"data"` } // ErrResponse 错误响应 type ErrResponse struct { Status int `json:"-"` ...
package body import ( "bytes" "github.com/imulab/coldcall" "io" "io/ioutil" "net/http" "strings" ) // Read option sets the io.Reader body on the http.Request. func Read(body io.Reader) coldcall.Option { return func(req *http.Request) error { rc, ok := body.(io.ReadCloser) if !ok && body != nil { rc = io...
package ibmcloud import ( "fmt" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" machineapi "github.com/openshift/api/machine/v1beta1" "github.com/openshift/installer/pkg/types" "github.com/openshift/installer/pkg/types/ibmclo...
package main import ( "flag" "fmt" "github.com/fleegrid/core" "log" "os" "os/signal" ) var clientMode = false var serverMode = false var helpFlag = false func main() { flag.BoolVar(&helpFlag, "h", false, "") flag.BoolVar(&helpFlag, "help", false, "show help") flag.BoolVar(&clientMode, "c", false, "") flag....
package main import ( "graphql-study/query" "net/http" "github.com/graphql-go/graphql" "github.com/graphql-go/handler" ) func main() { config := graphql.SchemaConfig{ Query: query.Object, } schema, _ := graphql.NewSchema(config) http.Handle("/", handler.New(&handler.Config{ Schema: &schema, Pretty:...
package baremetal import ( "github.com/AlecAivazis/survey/v2" "github.com/openshift/installer/pkg/types/baremetal" "github.com/openshift/installer/pkg/validate" ) // Host prompts the user for hardware details about a baremetal host. func Host() (*baremetal.Host, error) { var host baremetal.Host if err := surve...
package repeater import ( "context" "errors" "fmt" "testing" "time" "github.com/go-pkgz/repeater/strategy" "github.com/stretchr/testify/assert" ) func TestRepeatFixed(t *testing.T) { e := errors.New("some error") called := 0 fun := func() error { called++ if called == 5 { // only 5th call returns ok ...
package image import ( "testing" "github.com/stretchr/testify/assert" "github.com/openshift/installer/pkg/asset" "github.com/openshift/installer/pkg/asset/agent" "github.com/openshift/installer/pkg/asset/agent/manifests" ) func TestInfraBaseIso_Generate(t *testing.T) { GetIsoPluggable = func(archName string)...
package mysqldb import ( "context" "time" ) // OrganizationOwner 组织所有者 type OrganizationOwner struct { OrganizationID int `gorm:"primary_key;column:organization_id"` // 组织ID OwnerID int `gorm:"primary_key;column:owner_id"` // 所有者ID CreatedAt time.Time // 创建时间 UpdatedAt tim...
package penawaran type UserModel struct { UserId string `db:"USER_ID" json:"userId"` UserNama string `db:"USER_NAMA" json:"userNama"` UserEmail string `db:"USER_EMAIL" json:"userEmail"` UserPhone string `db:"USER_PHONE" json:"userPhone"` UserJoin string `db:"USER_JOIN" json:"userJoin"` } type UserAw struct ...
// Copyright 2023 Google LLC. 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 applica...
package cache import ( "errors" "time" ) var ErrNotFound = errors.New("key doesn't exist in cache") type Cache interface { Store(key string, value interface{}) error StoreWithTTL(key string, value interface{}, ttl time.Duration) error Get(key string, value interface{}) error Delete(key string) Keys() []string...
package main import ( "fmt" "net/url" "sync" "testing" ) func TestCrawl(t *testing.T) { expected := "https://en.wikipedia.org/wiki/Make_Peace" expectedScript := "https://en.wikipedia.org/w/load.php?debug=false&lang=en&modules=startup&only=scripts&skin=vector" title := "Make Peace - Wikipedia" css := "https:/...
package controllers import ( "github.com/go-openapi/runtime/middleware" "github.com/pottava/spiraloop/api/generated/restapi/operations" ) func postStart(params operations.PostStartParams) middleware.Responder { return operations.NewPostStartCreated() }
package persist_lib import ( "fmt" "golang.org/x/net/context" ) type AmazingMethodReceiver struct { Handlers AmazingQueryHandlers } type AmazingQueryHandlers struct { UniarySelectHandler func(context.Context, *Test_PartialTableForAmazing, func(Scanable)) error UniarySelectWithHooksHandler func(contex...
package utils import ( "golang.org/x/crypto/bcrypt" ) // GetBcryptHash 生成 bcrypt的hash字符串 func GetBcryptHash(password string) (string, error) { hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) return string(hash), err } // VerifyBcryptHash 验证hash与原文 func VerifyBcryptHash(hash, passwor...
package config_test import ( "testing" . "github.com/andygrunwald/perseus/config" ) func TestNewSatis_NoProvider(t *testing.T) { _, err := NewSatis(nil) if err == nil { t.Error("Expected an error. Got none.") } }
package comparisons import ( "instructions/base" "rtda" ) // LCMP Compare long /** 比较指令可以分为两类:一类将比较结果推入操作数栈顶,一 类根据比较结果跳转。比较指令是编译器实现if-else、for、while等 语句的基石 */ type LCMP struct{ base.NoOperandsInstruction } func (self *LCMP) Execute(frame *rtda.Frame) { stack := frame.OperandStack() v2 := stack.PopLong() v1 := s...
/* * Get a list of invoicing data (estimates) for a given account alias for a given month. */ package main import ( "flag" "fmt" "os" "time" "github.com/grrtrr/clcv2/clcv2cli" "github.com/grrtrr/exit" "github.com/olekukonko/tablewriter" ) func main() { var now = time.Now() var pricingAcct = flag.String("p...
// 4.5 Write an in-place fn to eliminate adjacent duplicates in a []string slice package main import "fmt" // Eliminates (consecutive) duplicates func eliminateDuplicates(strings []string) []string{ i := 0 var prev string for _, s := range(strings) { if s != prev { strings[i] = s i++ } prev = s } re...
package datastore import "github.com/google/wire" var ( WireSet = wire.NewSet(ProvideDBConnection, ProvideSessionStore) )
package win import ( //"fmt" "reflect" "syscall" "unicode/utf16" "unsafe" ) // From MSDN: Windows Data Types // http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx // http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751.aspx // ATOM WORD // BOOL int32 // BOOLEAN ...
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() //基本認證 authorized := r.Group("/", gin.BasicAuth(gin.Accounts{ "Eric": "123456", "Andy": "556888", })) authorized.GET("/hello/:name/*action", func(c *gin.Context) { //一般取值 ...
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { next := func() func() int { scan := bufio.NewScanner(os.Stdin) scan.Split(bufio.ScanWords) return func() int { scan.Scan() i, _ := strconv.Atoi(scan.Text()) return i } }() t := next() for ; t > 0; t-- { n := next() a := ...
/*package main import "fmt" var MAX int = 5 func f (n int) { for i := 0; i < MAX; i++ { fmt.Println(n, ":", i) } } func main () { go f(0) var input string fmt.Scanln(&input) } */ /*package main import ( "fmt" "time" "math/rand" ) var MAX int = 5 func f (n int) { for i := 0; i < MAX; i++ { fmt.Printl...
package nougat import ( "io" "io/ioutil" "net/http" ) // Do sends an HTTP request and returns the response. Success responses (2XX) // are JSON decoded into the value pointed to by successV and other responses // are JSON decoded into the value pointed to by failureV. // If the status code of response is 204(no co...
/* Copyright (c) 2016-2018 Jason Ish * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of condi...
package types const ( AvailabilityZoneLabel = "availability_zone" ClusterNameLabel = "cluster_name" PodIDLabel = "pod_id" )
// Copyright 2016 The go-qemu 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...
package tpns type CommonRspEnv string const ( // EnvProd EnvProd CommonRspEnv = "product" // EnvDev EnvDev CommonRspEnv = "dev" ) type CommonRsp struct { // TODO: doc this Seq int64 `json:"seq"` PushID string `json:"push_id"` RetCode int `json:"ret_code"` Environment CommonRspEnv `json:"environment"` E...
package group import ( "strings" "github.com/gomeetups/gomeetups/fixtures" "github.com/gomeetups/gomeetups/models" ) //ServiceMemory In memory groups service type ServiceMemory struct{} //SearchGroups Finds all groups for fiven filters func (*ServiceMemory) SearchGroups(filter *models.ValidGroupSearchParams) (gr...
package main import ( "fmt" ) func main () { var t int; fmt.Scanf("%d\n", &t) for ;t>0;t-- { var n int; fmt.Scan(&n) var x int; fmt.Scan(&x) if n <= 2 { fmt.Println(1) } else { i := 2 for ;;i++ { from := (i-2) * x + 3 to := (i-1) * x + 2 if n >= from ...
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger import ( "time" ) // 200 ok object type GetCharactersCharacterIdPlanets200Ok struct { // last_update string LastUpdate ti...
// +build linux package fsutil import ( "bytes" "io/ioutil" "os" "path/filepath" "sync" "testing" "github.com/docker/docker/builder" "github.com/pkg/errors" "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) type hashed interface { Hash() string } func TestCopySimple(t *testing.T) { d, e...
package bytes import ( crand "crypto/rand" "github.com/savsgio/gotils/strconv" "github.com/valyala/bytebufferpool" ) var randBytesPool = bytebufferpool.Pool{} // Rand returns dst with a cryptographically secure string random bytes. // // NOTE: Make sure that dst has the length you need. func Rand(dst []byte) []b...
package encoder import ( "io" "sync" "time" ) type fakeEncoder struct { singleFrameEncodingTimeInMs time.Duration totalFrames int curFrameNo int m sync.Mutex } func NewEncoder(singleFrameEncodingTimeInMs time.Duration, totalFrames int) *fakeEncoder { ...
package cron import ( "context" "errors" "fmt" "sync" "time" ) type Schedule interface { NextRunTime(now time.Time) time.Time } type Job struct { Name string Run func(context.Context) Schedule Schedule } type Cron struct { done chan (struct{}) } type timedJob struct { NextRun time.Time Job ...
// Package client is a Go client for the RESTful TupleSpace service. package client import ( "bytes" "errors" log "github.com/alecthomas/log4go" "github.com/alecthomas/tuplespace" "github.com/vmihailenco/msgpack" "net/http" "time" ) // TupleSpaceClient is the a Go client for the tuplespace service. type TupleS...
package cmd import ( "errors" "fmt" "os/exec" "regexp" "sort" "strings" ) type GitCmdResult struct { result []string executedCmd []string success bool } type GitRunner interface { Run(*GitCmdExecutor) (*GitCmdResult, error) } type GitStatusRunner struct { } func (g *GitStatusRunner) Run(gitCmd *...
package study import "fmt" type Connecter interface { Connect() } type USB interface { Name() string Connecter } type ComputerConnecter struct { ConnName string } func (computerconn ComputerConnecter) Name() string { return computerconn.ConnName } func (compuerconn ComputerConnecter) Connect() { fmt.Printf("链接...
package main import ( "fmt" "log" T "gorgonia.org/gorgonia" ) func main() { g := T.NewGraph() var x, y, z *T.Node var err error // define the expression x = T.NewScalar(g, T.Float64, T.WithName("x")) y = T.NewScalar(g, T.Float64, T.WithName("y")) //z, err = Add(x, y) z, err = T.Sub(x, y) if err != nil ...
package beginner import "fmt" /** * created: 2019/5/8 9:19 * By Will Fan */ func main() { isSpace := func(ch byte) bool{ switch ch { case ' ': //fallthrough case '\t': return true } return false } fmt.Println(isSpace('\t')) fmt.Println(isSpace(' ')) }
package http import ( "fmt" "github.com/davepgreene/slackmac/errors" "github.com/davepgreene/slackmac/utils" log "github.com/sirupsen/logrus" "net/http" "time" ) var requiredHeaders = [2]string{slackTimestampHeader, slackSignatureHeader} func timestamp(skew time.Duration) func(http.ResponseWriter, *http.Reques...
// Copyright 2018 Twitch Interactive, Inc. 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. A copy of the License is // located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license"...
package nrpc import ( "context" "github.com/stretchr/testify/assert" "net/http" "testing" "time" ) func TestCall_Do(t *testing.T) { s := NewServer(ServerOptions{Addr: "127.0.0.1:10099"}) s.Register(&TestService{}) s.Start(nil) defer s.Shutdown(context.Background()) time.Sleep(time.Second) c := &Call{ c...
package main import ( "compress/gzip" "fmt" "log" "os" ) const MAGIC = 64251 var dbPath = "/home/nia/Development/_Python/_DCat/Export10/app2/oxygen_16x16.hmap.gz" func main() { fmt.Println("start") f, err := os.Open(dbPath) if err != nil { log.Fatal(err) } defer f.Close() log.Println("file opened") fi...
package time import ( "time" ) const limit = -time.Minute * 30 var now = time.Now func CanNotify(deliveryTime time.Time) bool { deadline := deliveryTime.Add(limit) //fmt.Println("Delivery time:", deliveryTime) //fmt.Println("Deadline:", deadline) //fmt.Println("Now:", now()) if now().Equal(deliveryTime) || ...
package main import ( "bufio" "image" "image/png" "io" "log" "os" "github.com/stephenwithav/ssvgc" ) func main() { if len(os.Args) < 3 { log.Fatal(`Error! ssvgc requires two arguments. $ ssvgc <in.svg> <out.png>`) } r, f := LoadSVG(os.Args[1]) defer f.Close() p := ssvgc.NewParser(r) svg, err := p.P...
// Copyright 2013 Beego Authors // Copyright 2014 Unknwon // // 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 app...
package form3 import ( "context" "errors" "fmt" "net/http" "net/url" "regexp" "strconv" "github.com/google/uuid" ) const accountsPath = "/v1/organisation/accounts" // client side account validation errors var ( ErrInvalidCountry = errors.New("country should match '^[A-Z]{2}$'") ErrInvalidBaseCurrency...
package service import ( m "randy/model" ) type Service struct { } type RandyService interface { Health(*m.ServiceCommand) (*m.ServiceCommand, error) } func NewService() *Service { return &Service{} } func (s *Service) Health(sc *m.ServiceCommand) (*m.ServiceCommand, error) { sc.Completed = true return sc, n...
// Copyright 2017 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 config type BackupConfig struct { MetaAddrs []string StorageAddrs []string SpaceNames []string BackendUrl string StorageUser string MetaUser string } type RestoreConfig struct { MetaAddrs []string StorageAddrs []string BackendUrl string MetaUser string StorageUser st...
package models type Void struct{} type HistoryRecord struct { User *User UserName string Message *Message } type User struct { Name string AllNames map[string][]*Room Rooms map[string]*Room Messages []*Message } type Message struct { Text string Owner* User Room* Room } type Room struct { Name ...
package vulcanizer import ( "errors" "fmt" "strings" "github.com/tidwall/gjson" ) func excludeSettingsFromJson(settings []gjson.Result) ExcludeSettings { excludeSettings := ExcludeSettings{} if settings[0].String() == "" { excludeSettings.Ips = []string{} } else { excludeSettings.Ips = strings.Split(sett...
/* * @lc app=leetcode id=42 lang=golang * * [42] Trapping Rain Water * * https://leetcode.com/problems/trapping-rain-water/description/ * * algorithms * Hard (43.53%) * Likes: 3742 * Dislikes: 68 * Total Accepted: 303.6K * Total Submissions: 697.4K * Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]' * ...
package checkers import ( "os" "rego-go-parser/pkg/helpers" "rego-go-parser/pkg/schema" "strconv" "strings" ) /* This functions generates a rego policy as below with proper indentations: Role check with org check api_roles := ["CONTENT_CREATOR", "COURSE_CREATOR"] some i api_roles[_] == token.payload....
//go:build !windows // +build !windows package higgs import ( "errors" "io/ioutil" "os" "path/filepath" "strings" "testing" ) var tmpDir string func touch(path, content string) { path = filepath.FromSlash(path) dir := filepath.Dir(path) if dir != "" { os.MkdirAll(filepath.Join(tmpDir, dir), 0755) } iou...
package gcp import ( "context" "fmt" "github.com/pkg/errors" "google.golang.org/api/iam/v1" "k8s.io/apimachinery/pkg/util/sets" "github.com/openshift/installer/pkg/types/gcp" ) // listServiceAccounts retrieves all service accounts with a display name prefixed with the cluster's // infra ID. Filtering is done ...
package api import ( "github.com/gin-gonic/gin" "github.com/goboilerplates/core" "github.com/gonitor/gonitor-websocket/env" "github.com/gorilla/websocket" ) // GetSamplesAPI is the interface for GetSamplesAPI. type GetSamplesAPI interface { HanldeWebSocket(context *gin.Context) HandleMessage(conn *websocket.Con...
package cache import ( "bytes" "encoding/json" "strings" "sync" "github.com/serverless/event-gateway/function" "github.com/serverless/event-gateway/libkv" "go.uber.org/zap" ) type functionCache struct { sync.RWMutex cache map[libkv.FunctionKey]*function.Function log *zap.Logger } func newFunctionCache(l...
package main import ( "flag" "fmt" "os" "github.com/golevi/cfallow/cmds" ) func main() { if len(os.Args) < 2 { cmds.AddMyIP() return } switch os.Args[1] { case "myip": cmds.AddMyIP() case "file": fileCmd := flag.NewFlagSet("file", flag.ExitOnError) fileName := fileCmd.String("name", "", "filename...
package usecase import ( "context" "github.com/Azimkhan/go-calendar-grpc/internal/calendar" "github.com/Azimkhan/go-calendar-grpc/internal/models" "time" ) func NewCalendarUsecase(repository calendar.Repository, contextTimeout time.Duration) calendar.Usecase { return &CalendarUsecase{repository, contextTimeout} ...
package main import ( "embed" "io/fs" "log" "os" "path/filepath" "github.com/bvieira/sv4git/v2/sv" "github.com/urfave/cli/v2" ) // Version for git-sv. var Version = "source" const ( configFilename = "config.yml" repoConfigFilename = ".sv4git.yml" configDir = ".sv4git" ) var ( //go:embed res...
package problem0503 func nextGreaterElements(nums []int) []int { stack := []int{} result := make([]int, len(nums)) for i := 0; i < len(nums); i++ { result[i] = -1 } for i := 0; i < len(nums)*2; i++ { index := i if i >= len(nums) { index = i - len(nums) } for len(stack) > 0 && nums[stack[len(stack)-1]...
package middleware import ( "fmt" "github.com/gin-gonic/gin" "github.com/sulin2018/go-web-base/src/utils" ) func AppLogger() gin.HandlerFunc { return gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { return fmt.Sprintf("%s %s %s %s %s %d %s %s %s \n", param.TimeStamp.Format(utils.TIMEFORMA...
package main var sayingsEn = []string{ "Let's see weather or not you should leave umbrella at home.", "The best and the worst thing about the weather is that it changes.", "Conversation about the weather is the last refuge of the unimaginative.", "Weather forecast for tonight: dark.", "There is no such thing as b...
package mysql import ( "bufio" "context" "fmt" "github.com/gin-gonic/gin" "mysql-agent/common/env" "mysql-agent/common/http/client" "mysql-agent/common/logger" "mysql-agent/common/resultcode" "mysql-agent/common/service" "mysql-agent/controller/domain" "os" "strconv" ...
package models // github.com/growlog/things-server/internal/models import ( "fmt" "log" _ "github.com/lib/pq" "github.com/jmoiron/sqlx" ) type DataAccessLayer struct { db *sqlx.DB } /** * Function initializes our connection with the `postgres` database for this * web-application and saves the...
package endpoints import ( "encoding/json" "fmt" "net/http" "strconv" act "github.com/ebikode/eLearning-core/domain/activity_log" aps "github.com/ebikode/eLearning-core/domain/app_setting" md "github.com/ebikode/eLearning-core/model" tr "github.com/ebikode/eLearning-core/translation" ut "github.com/ebikode/e...
package gui import ( "../listener" "../constants" "github.com/andlabs/ui" ) func SetUpUI() { mainWindow := ui.NewWindow(constants.APP_NAME + constants.SPACE + constants.APP_VERSION, constants.APP_HEIGHT, constants.APP_WIDTH, true) mainWindow.OnClosing(func(*ui.Window) bool { mainWindow.Destroy() ui...
func superPow(a int, b []int) int { if len(b) == 1 { return helper(a, b[0]) } else { return merge(superPow(helper(a, 10), b[0:len(b)-1]), helper(a, b[len(b)-1])) } } func merge(a, b int) int { return ((a % 1337) * (b % 1337)) % 1337 } func helper(a, power int) int { if power == 0 { return 1 } return merg...
package service import ( "github.com/lxt1045/VisionSMS/thrift/gen-go/rpc/sms" "github.com/lxt1045/VisionSMS/util" ) var logger = util.Mylog func init() { typeMap = make(map[string]NewHandlerObj) } type HandlerObj interface { //发送短信的接口,只需要 一个函数 Send(mobile string, smsType int, params map[string]string) (success...
package utils import ( "testing" "time" ) func TestConvertToString(t *testing.T) { type args struct { currentTime time.Time } var tests []struct { name string args args want string } = []struct { name string args args want string }{ { name: "Test time", args: args{ currentTime: time.D...
package main import ( "fmt" "log" ) func user() { log.Println("================= USER =================") if err := checkEnv(); err != nil { fmt.Println(err) return } username := c.CheckUserName("jack.z@ssl.report") // user, err := c.ViewUser("1546247") // user, err := c.ListUsers("88217") user, err := c...
package 链表 func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { // 1. 初始化。 carry := 0 dummyHead := &ListNode{ Val: 0, Next: nil, } // 2. 计算。 for resultNode := dummyHead; l1 != nil || l2 != nil || carry != 0; { // 2.1 获取总和。 sum := carry if l1 != nil { sum += l1.Val l1 = l1.Next } if l2...
package xpost import ( "runtime" "time" "github.com/hypnoswang/xlog" ) var logger xlog.Logger var defaltXp *Xpost func init() { if defaltXp == nil { defaltXp = &Xpost{ inited: false, started: false, hasSender: false, infoIntv: 0, ex: GetExchanger(), pool: nil, couriers: ...
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "strings" "machaao-go/extras" "github.com/dgrijalva/jwt-go" witai "github.com/wit-ai/wit-go" ) //Get MachaaoApiToken from https://portal.messengerx.io var machaaoAPIToken string = os.Getenv("MachaaoApiToken") //Get Wit...
package main import "fmt" func main() { var arr [7]int = [7]int{1,2,3,6,48,299,4990} reverse(&arr) fmt.Println("In main(), arr values:", arr) } func reverse(arr *[7]int) { // 分别去两端后赋值 for i, j := 0, len(*arr) -1; i < j; i,j = i+1, j-1 { (*arr)[i], (*arr)[j] = (*arr)[j], (*arr)[i] } }
package dandler import ( "fmt" "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestHeader(t *testing.T) { ts := httptest.NewServer(Header("superheader", "secret value", Success("yay"))) defer ts.Close() resp, err := http.Get(ts.URL) assert.Nil(t, err) assert...
package config import ( "errors" "fmt" ) // DeployArgs are arguments passed to the deploy command type DeployArgs struct { IAAS string AWSRegion string Domain string TLSCert string TLSKey string WorkerCount int WorkerSize string SelfUpdate bool } // WorkerSizes are the permitted co...
package cachebig import ( "context" "time" "github.com/allegro/bigcache/v3" "github.com/atcharles/gof/v2/g2cache/store" ) // BigCache ... type BigCache struct { inc *bigcache.BigCache } func (b *BigCache) Instance() *bigcache.BigCache { return b.inc } // New ... func (*BigCache) New() *BigCache { inc := new...
// +build ignore package main import ( "fmt" "os" "github.com/google/uuid" ) func main() { testdata, err := os.Create("testdata") if err != nil { panic(err) } overlapped := "overlapped" for i := 0; i < 333333; i++ { for _, dc := range []string{"ams", "sh", "sf"} { // testdata.WriteString("disk.used")...
/* Copyright 2021 RadonDB. 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 distri...
package main import ( "TBC" "fmt" ) var SysIdentifier string = "系统" var NodeIdentifier string = "矿工" //////////////////////////////////////////////////////////////////////////// //新交易 //@app.route('/transactions/new', methods=['POST']) func new_transaction(self *TBC.BlockChain, sender, recver, amount string) int {...
package command import ( "fmt" "time" "github.com/altipla-consulting/chrono" pb_empty "github.com/golang/protobuf/ptypes/empty" "github.com/juju/errors" "github.com/spf13/cobra" "golang.org/x/net/context" ) func init() { FunctionsCmd.AddCommand(FunctionsListCmd) } var FunctionsListCmd = &cobra.Command{ Use...
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) type Direction int const ( DOWN Direction = iota RIGHT UP LEFT ) func (d Direction) next() Direction { switch d { case DOWN: return RIGHT case RIGHT: return UP case UP: return LEFT case LEFT: return DOWN } return d } func locato...
package cipher import ( "crypto/aes" "crypto/cipher" "crypto/rand" "log" ) // CryptoMode ... const ( Aes256Gcm = iota Aes256Cbc ) // aesEncryptCBC ... func aesEncryptCBC(plaindata []byte, key []byte) (cipherdata []byte, iv []byte, err error) { data := plaindata block, err := aes.NewCipher(key) if err != nil...
package main import ( "github.com/tasks/Redirect-HttpToHTTPS/config" "log" "net/http" "os" ) //Init: Initialize before the main function for loading environment file func init() { err := config.FunInitEnvironment() if err != nil { log.Fatal("ERROR init: couldn't initialize environment-> ", err.Error()) } } ...
package main import ( "fmt" "github.com/magarcia/intel8080/io" ) func hexdump(rom []byte) { for i, element := range rom { if (i % 16) == 0 { fmt.Printf("\n%08x ", i) } fmt.Printf("%02x", element) if (i % 16) != 15 { fmt.Printf(" ") } } fmt.Printf("\n") } func main() { rom, err := io.LoadROM("i...