text
stringlengths
11
4.05M
// Copyright 2020, Jeff Alder // // 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 a...
package main import ( "container/heap" "fmt" . "github.com/zhouziqunzzq/osexperiment1/PCB" . "github.com/zhouziqunzzq/osexperiment1/priorityqueue" ) const ( DefaultQueueLength = 0 ClearScreenCMD = "\033[2J\033[1;1H" MemoryCapacity = 1024 MemoryBarLength = 30 MaxPid = 65535 MinPid ...
package Solution func moveZeroes(nums []int) []int { count := 0 for _, i := range nums { if i != 0 { nums[count] = i count++ } } for i := count; i < len(nums); i++ { temp := i nums[temp] = 0 } return nums } func moveZeroes2(nums []int) []int { n := len(nums) if n > 1 { for z, nz := 0, 0; nz < ...
package lock import ( "KServer/library/kiface/ilock" "KServer/library/kiface/iredis" "KServer/library/kiface/iutils" "KServer/library/utils" "fmt" "time" ) type Lock struct { IRedis iredis.IRedisPool LockText string QueueId int64 pdtool iutils.IProtobuf } func NewILock(LockText string, redis iredis.IR...
package main // see the docs https://godoc.org/gonum.org/v1/gonum/mat import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { u := mat.NewVecDense(3, []float64{1, 2, 3}) println("u: ") matPrint(u) v := mat.NewVecDense(3, []float64{4, 5, 6}) println("v: ") matPrint(v) w := mat.NewVecDen...
package main import "fmt" func main() { fmt.Println(string(20154)) // "人" fmt.Println(string(0x4eba)) // "人" }
package main import ( "bytes" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "regexp" "sync/atomic" "github.com/gorilla/mux" "github.com/labstack/gommon/log" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/plugin" "github....
// Copyright 2016-2021, Pulumi Corporation. package main import ( "archive/zip" "bytes" "compress/gzip" ctx "context" "encoding/json" "flag" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "sort" "strings" "github.com/pulumi/pulumi/pkg/v3/codegen" "github.com/aws/aws-sdk-go-v2/config" "githu...
package services import ( "LivingPointAPI/database/server/database" "LivingPointAPI/database/server/models" "fmt" "log" "os" "strconv" ) // GetHistories returns history func GetHistories(queries map[string]interface{}) (out map[int64]map[string]string) { out = make(map[int64]map[string]string) var users []mod...
package sapexport import ( "encoding/json" "fmt" "log" "github.com/antihax/sapexport/cmd/sapexport/sap" "github.com/spf13/cobra" ) func init() { var where string var cmdTable = &cobra.Command{ Use: "table [SAP Table]", Short: "Extract a table to JSON", Long: `table will extract a table from the SAP s...
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package messages import ( "fmt" "encoding/json" ) type UpdateCard struct { Cards []int } func (m UpdateCard) ToBytes() []byte { if cards, err := json.Marshal(m.Cards); err == nil { return []byte(fmt.Sprintf("card %s", cards)) } return []byte{} }
// Copyright 2019-present 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 agr...
package container import ( "github.com/bitmaelum/bitmaelum-suite/internal/account" "github.com/bitmaelum/bitmaelum-suite/internal/config" ) // GetAccountRepo retrieves an account repository func GetAccountRepo() account.Repository { return account.NewFileRepository(config.Server.Paths.Accounts) }
package router import ( "encoding/json" "github.com/golang/glog" "qipai/dao" "qipai/enum" "qipai/game" "qipai/model" "qipai/srv" "qipai/utils" "time" "zero" ) func init() { game.AddAuthHandler(game.ReqGameStart, gameStart) game.AddAuthHandler(game.ReqSetTimes, gameSetTimes) game.AddAuthHandler(game.ReqSe...
// ˅ package main import "strconv" // ˄ // A node corresponding to "repeat". type Repeat struct { // ˅ // ˄ number int commandList INode // ˅ // ˄ } func NewRepeat() *Repeat { // ˅ return &Repeat{number: 0} // ˄ } func (self *Repeat) Parse(context *Context) { // ˅ context.SlideToken("repeat") self...
// 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 client import ( "bytes" "encoding/xml" "fmt" "io/ioutil" "net/http" "net/url" "github.com/BenjaminLam1202/test-go-config-cameras/hkvision/types/streaming" ) /** * @author : Donald Trieu * @created : 9/24/21, Friday **/ /* It is used to get the properties of streaming channels for the device. */ fun...
package main import ( "fmt" "log" "os" "strconv" "time" "example.com/finder/models" "example.com/finder/services" "github.com/fatih/color" "github.com/rodaine/table" ) var dirPath string func main() { start := time.Now() arguments := os.Args if len(arguments) < 2 { fmt.Println("what's the source fol...
package Iterator import ( "fmt" "testing" ) func TestArrayIterator(t *testing.T) { array := []interface{}{1,2,4,5,7,9} a := 0 iterator := ArrayIterator{array:array,index:&a} for it:=iterator;iterator.HasNext() ;iterator.Next() { //取到索引、值,判断后续是否还有东西,若有则取出来返回给迭代器 index,value := it.Index(),it.Value().(int) ...
package transport import ( "time" ) type Message struct { From string To string Payload []byte Meta interface{} Date time.Time }
package main import ( "fmt" "go-basic/hsp/chart/server/model" "net" "time" ) func initUserDao() { //说明pool 是一个全局变量,在redis.go中初始化的 //因此这里可以直接使用 model.MyuserDao = model.NewUserMgr(pool) } func process(conn net.Conn) { // 创建一个client,相当于一个控制器 cp := &ClientProcessor{ conn: conn, } // 让client进行处理,其实主要是让 cli...
package ch2 var pc [256]byte func init() { // i&1: i为奇数则为1,偶数则为0 for i := range pc { pc[i] = pc[i/2] + byte(i&1) } } // 统计二进制中1bit的个数 // todo:不懂,日后再说 func PopCount(x uint64) int { return int(pc[byte(x>>(0*8))] + pc[byte(x>>(1*8))] + pc[byte(x>>(2*8))] + pc[byte(x>>(3*8))] + pc[byte(x>>(4*8))] + pc[by...
package utils func CheckIin(iin string) bool { if len(iin) != 12 { return false } for _, number := range iin { if number < 48 && number > 57 { return false } } month := strToInt(iin[2:4]) if month < 0 || month > 12 { return false } day := strToInt(iin[4:6]) if day < 0 || day > 31 { return fals...
/* * Copyright 2018, CS Systemes d'Information, http://www.c-s.fr * * 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 requir...
package apiv1 import ( "phrases-rest-api/api/v1/phrases" "github.com/gin-gonic/gin" ) // ApplyRoutes applies router to gin Router func ApplyRoutes(r *gin.RouterGroup) { v1 := r.Group("/v1") { phrases.ApplyRoutes(v1) } }
package plugin import "github.com/urfave/cli" type Plugin interface { Name() string Commands() cli.Commands }
package chapter6 import ( "fmt" "testing" ) func TestDutchNationalFlag(t *testing.T) { var dutchNationalFlagTests = []struct { a []int p int }{ {[]int{1}, 0}, {[]int{1, 2, 3}, 1}, {[]int{5, 3, 9, 3, 8, 1}, 1}, } for _, tt := range dutchNationalFlagTests { fmt.Println(tt.a) DutchNationalFlag(tt.a,...
package frame type Frame struct { Command string Headers map[string]string Body []byte } func NewFrame(command string, body []byte) *Frame { frame := &Frame{ Command: command, Body: body, Headers: make(map[string]string), } return frame } func (frame *Frame) AddHeader(key, value string) { frame....
package client import ( "time" "github.com/giantswarm/api-schema" ) func (this *Client) Create(username, email, password string) (string, error) { var noExpirationDate time.Time return this.CreateTimeLimited(username, email, password, noExpirationDate) } func (this *Client) CreateTimeLimited(username, email, pa...
// This file was generated for SObject CustomObjectUserLicenseMetrics, API Version v43.0 at 2018-07-30 03:47:55.619902082 -0400 EDT m=+41.964083122 package sobjects import ( "fmt" "strings" ) type CustomObjectUserLicenseMetrics struct { BaseSObject CustomObjectId string `force:",omitempty"` CustomObjectName s...
package systemd import ( "fmt" "github.com/miekg/vks/pkg/system" ) // defaultEnvironment returns the environment that the kubelet uses. // It returns a list of strings VAR=VALUE. func (p *P) defaultEnvironment() []string { env := []string{} env = append(env, fmt.Sprintf("HOSTNAME=%s", system.Hostname())) env = ...
package command import ( "encoding/json" "errors" "fmt" "strings" "text/template" "github.com/spf13/cobra" yaml "gopkg.in/yaml.v2" "go.mercari.io/hcledit" ) type ReadOptions struct { OutputFormat string } func NewCmdRead() *cobra.Command { opts := &ReadOptions{} cmd := &cobra.Command{ Use: "read <qu...
package cli import ( "encoding/json" "fmt" "log" "os" "os/exec" "github.com/spf13/afero" "github.com/spf13/cobra" fp "github.com/ocramh/fingerprinter/pkg/fingerprint" ) var ( inputFile string ) func init() { rootCmd.AddCommand(fpCmd) fpCmd.Flags().StringVarP(&inputFile, "audiofile", "a", "", "path to in...
//+build js,wasm package gonreli import ( "bufio" "fmt" "io" "net/http" "net/url" "strings" "sync" "syscall/js" ) type request struct { js.Value headers http.Header } func newRequest(v js.Value) *http.Request { r := &request{ Value: v, headers: http.Header{}, } pr, bodyWritter := io.Pipe() br :...
/* * Copyright © 2018-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 zset import ( "fmt" "testing" ) func TestNewZSet(t *testing.T) { z := NewZSet() z.Add("a", 1) z.Add("b", 2) z.Add("c", 3) fmt.Println(z.Range(0, 3)) // [{a 1} {b 2} {c 3}] fmt.Println(z.Range(0, 2)) // [{a 1} {b 2}] fmt.Println(z.Range(0, 1)) // [{a 1}] fmt.Println(z.Range(1, 3)) // [{b 2} {c 3...
//+build tools package main import ( _ "github.com/google/wire/cmd/wire" _ "github.com/jessevdk/go-assets-builder" _ "github.com/lestrrat-go/server-starter/cmd/start_server" _ "honnef.co/go/tools/cmd/megacheck" )
package unicorn import ( "runtime" "unsafe" ) // #include <unicorn/unicorn.h> import "C" type Context **C.uc_context func (u *uc) ContextSave(reuse Context) (Context, error) { ctx := reuse if ctx == nil { ctx = new(*C.uc_context) } if err := errReturn(C.uc_context_alloc(u.handle, ctx)); err != nil { retur...
package database import ( "fmt" "github.com/go-ozzo/ozzo-dbx" // Mysql driver _ "github.com/go-sql-driver/mysql" "github.com/kataras/iris" ) var conn *dbx.DB func GetDB(ctx iris.Context) *dbx.DB { if conn == nil { user := ctx.Values().GetString("DB_USER") pass := ctx.Values().GetString("DB_PASS") db := ...
/* Description A knight piece in chess can only make L-shaped moves. Specifically, it can only move x steps to the right and y steps up if (x,y) is one of: (-1,-2) ( 1,-2) (-1, 2) ( 1, 2) (-2,-1) ( 2,-1) (-2, 1) ( 2, 1) (For this problem, assume the board extends infinitely in all directions, so a knight may always ...
package database import ( "fmt" "github.com/jeffleon/api-rest-users/model" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) var ( DBConn *gorm.DB ) func InitDatabase(){ var err error DBConn, err = gorm.Open("sqlite3", "users.db") if err != nil { panic("Failed to connect to database") ...
package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface" ) type...
package main import ( "io" "os" ) type Packet struct { Data []byte Duration uint64 // in ms DTS uint64 PTS uint64 } // Track is the struct of track in a media source file. // It contains the overall information about the track. type Track struct { Type TrackType // Audio/Video/Subtitle Track...
package app import ( "net/http" "github.com/naowal/paypal2/pkg/view" ) func PaymentHandler(w http.ResponseWriter, r *http.Request) { view.Payment(w, r, view.PaymentData{}) } func PSuccessHandler(w http.ResponseWriter, r *http.Request) { view.Success(w, r, view.PSuccessData{}) } func PDenyHandler(w http.Respons...
package storage import ( "bytes" "encoding/gob" //"fmt" ) func Serialize(obj interface{}) []byte { //fmt.Println("testing out serializer...") // the result goes into this buffer var buf bytes.Buffer // make an encoder that will write into the buffer encoder := gob.NewEncoder(&buf) // actually encode encoder...
package core import ( "github.com/cilium/kubenetbench/utils" ) func (s *ContainerSpec) hostOptsWrite(pw *utils.PrefixWriter, params map[string]interface{}) { l := func(s string) { pw.AppendNewLineOrDie(s) } if s.HostNetwork { l(`hostNetwork: true`) } if s.HostIPC { l(`hostIPC: true`) } if s.HostPID {...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package clickhousespanstore import ( "container/heap" "fmt" "sync" "github.com/jaegertracing/jaeger/model" ) // WriteWorkerPool is a worker pool for writing batches of spans. // Given a new batch, WriteWorkerPool creates a new WriteWorker. // If the number of currently processed spans if more than maxSpanCount, ...
package rpcRouter import ( "github.com/go-xe2/x/os/xlog" "github.com/go-xe2/xthrift/pdl" ) func (p *TRouterClient) Install(pdl *pdl.FileProject, md5 string) { if pdl == nil { return } if err := p.sendRegProject(pdl, md5); err != nil { xlog.Error(err) } //pktId := time.Now().UnixNano() // //data := makeRe...
package main import ( "errors" "os" "path/filepath" "github.com/containernetworking/cni/pkg/types" ) const ( // confFileName is the name of the dns masq conf file confFileName = "dnsmasq.conf" // hostsFileName is the name of the addnhosts file hostsFileName = "addnhosts" // pidFileName is the file where the...
package chanutil import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestBatch(t *testing.T) { ch1 := make(chan int) go func() { for _, i := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} { ch1 <- i } close(ch1) }() ch2 := Batch(ch1, WithBatchMaxWait(time.Millisecond*10), WithBatchMaxS...
//import "github.com/solomonooo/mercury" //author : solomonooo //create time : 2016-09-08 package client type Client interface { GetCost() uint32 GetLastInfo() (string, uint32) }
package midi import ( "errors" "reflect" "testing" ) func TestEventCopy(t *testing.T) { event := &Event{} event.TimeSignature = &TimeSignature{} event.SmpteOffset = &SmpteOffset{} if !reflect.DeepEqual(event, event.Copy()) { t.Fatal(errors.New("Expected copy to be equal")) } } func TestEventString(t *testi...
package requestHandlers import ( "fmt" "github.com/alaaattya/recipy-admin-api/models" "github.com/gin-gonic/gin" "github.com/go-bongo/bongo" ) // HandleCreateNewRecipy create new recipy handler func HandleCreateNewRecipy(context *gin.Context) { connection, ok := context.Keys["DBConnection"].(*bongo.Connection)...
package dto import ( "github.com/artrey/go-bank-service/pkg/models" ) type Card struct { Id int64 `json:"id"` Number string `json:"number"` Balance int64 `json:"balance"` Issuer string `json:"issuer"` Holder string `json:"holder"` OwnerId int64 `json:"ownerId"` Status string `json:"s...
package algorithm import ( "fmt" "math/rand" "sort" "testing" ) func TestBinarySearch(t *testing.T) { items1 := rand.Perm(20) items2 := rand.Perm(25) sort.Ints(items1) sort.Ints(items2) fmt.Println(items1) fmt.Println(items2) target1 := 11 target2 := 18 index1 := BinarySearch(items1, target1) index2...
package persistence import ( "context" "database/sql" "time" "github.com/google/uuid" "github.com/lib/pq" "github.com/pkg/errors" "github.com/dollarshaveclub/acyl/pkg/models" ) // CreateAPIKey creates a new user api key func (pg *PGLayer) CreateAPIKey(ctx context.Context, permissionLevel models.PermissionLev...
package main import "fmt" func main() { ch := make(chan string, 2) ch <- "hello" ch <- "world" ch <- "!" // extra message in buffer fmt.Println(<-ch) } // => fatal error: all goroutines are asleep - deadlock!
package base type Base interface { Insert () Update () Delete () Find () FindAll () FindBy () FindOne () } type A struct { } type B struct { a A }
package sqsmv import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sqs" ) func receiveMessage(queueName string, longPollSeconds int64) ([]*sqs.Message, error) { resp, err := getSQSClient(queueName).ReceiveMessage(&sqs.ReceiveMessageInput{ QueueUrl: aws.String(queueName), Att...
package main import ( "sort" ) // Вычисление всех возможных валидных состояний и позиций func (p *Pantograph) Evaluate() { N1 := p.E1.MaxVal - p.E1.MinVal + 1 N2 := p.E2.MaxVal - p.E2.MinVal + 1 p.Cloud = make([]Projection, 0, N1*N2) for a1 := 0; a1 < N1; a1++ { for a2 := 0; a2 < N2; a2++ { p.A1 = float64(p...
package accesstoken import ( "fmt" "net/http" "strconv" "github.com/spf13/cobra" "github.com/makkes/gitlab-cli/api" ) func NewCommand(client api.Client) *cobra.Command { var projectFlag string cmd := &cobra.Command{ Use: "access-token ID|NAME", Args: cobra.ExactArgs(1), Short: "Revoke a project acc...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //400. Nth Digit //Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... //Note: //n is positive and will fit with...
// (C) Copyright 2012, Jeramey Crawford <jeramey@antihe.ro>. All // rights reserved. Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package common import ( "testing" "fmt" "strings" ) var _Salt = &Salt{ MagicPrefix: []byte("$foo$"), SaltLenMin: 1, SaltLenM...
// curl -X POST -H "Content-Type: application/octet-stream" --data-binary '@filename' http://127.0.0.1:5050/upload package main import ( "bufio" "encoding/binary" "encoding/json" "flag" "fmt" "hash/fnv" "io" "net/http" "os" "path/filepath" "regexp" "strconv" "time" "github.com/dippynark/kubecast/pkg/as...
package room func createNewBattle(args []interface{}) interface{} { return -1 }
package main import ( "fmt" ) func main() { student := []string{} students := [][]string{} student[0] = "Todd" // student = append(student, "Todd") fmt.Println(student) fmt.Println(students) } // panic: runtime error: index out of range [0] with length 0 // goroutine 1 [running]: // main.main() // /ho...
package _74_Search_a_2D_Matrix import "testing" func TestIdxToPos(t *testing.T) { var ( i, j int ) if i, j = idxToPos(0, 10); i != 0 && j != 0 { t.Errorf("wrong ret with i=%d, j=%d", i, j) } } func TestSearchMatrix(t *testing.T) { var ( matrix [][]int target int ) matrix, target = [][]int{{1, 3, 5, 7}...
package timesafeguard import ( "testing" "time" ) func TestGood(t *testing.T) { if !timeInSync([]timeResult{ { Start: time.Unix(1432323893, 0), End: time.Unix(1432323893, 500*int64(time.Millisecond)), Result: time.Unix(1432323893, 1), }, { Start: time.Unix(1432323893, 0), End: time.Uni...
package main // go install ./project/main/ && ../../../../bin/main // curl -d --header "Content-Type: application/json" --request POST http://localhost:5000/api/forum/create --data '{"title":"Pirate","user":"j.sparrow","slug":"pirate-stories"}' // curl --header "Content-Type: application/json" --request POST --dat...
package main import stack "awesomeProject" func main() { reverse := "" subRev := "" _stack := new(stack.Stack) input := "foo(bar(baz))blim" _stack.Initialize(len(input)) for _, char := range input { if _stack.Size == 0 && string(char) != "(" { reverse += string(char) } if string(char) == "(" || (s...
package api import ( "encoding/json" "fmt" "net/http" "github.com/himu62/vcpod/object" ) func libraryRootHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: listRootObjects(w) } } func listRootObjects(w http.ResponseWriter) { roots := make([]object.RootObject, 1) w.Wr...
package errors var ErrUserExists = New("user already exists", 400) var ErrUserNotExists = New("user with this id doesn't exist", 404) var ErrWrongCreds = New("wrong login or password", 401)
package main import "text/template" var pkgbuildTemplate = template.Must( template.New("pkgbuild").Parse( `{{if ne .Maintainer ""}}# Maintainer: {{.Maintainer}} {{end}}pkgname={{.PkgName}} _pkgname={{.ProgramName}} pkgver=${PKGVER:-autogenerated} pkgrel={{if eq .PkgRel "1"}}${PKGREL:-1}{{else}}{{.PkgRel}}{{end}} p...
package domain import ( "regexp" "github.com/Tanibox/tania-core/src/helper/validationhelper" ) func validateFarmName(name string) error { if name == "" { return FarmError{FarmErrorNameEmptyCode} } if !validationhelper.IsAlphanumSpaceHyphenUnderscore(name) { return FarmError{FarmErrorNameAlphanumericOnlyCode...
/* Write a function that calculates the [intersection](http://en.wikipedia.org/wiki/Intersection_(set_theory)) of two rectangles, returning either a new rectangle or some kind of null value. You're free to represent these rectangles in any way you want: tuples of numbers, class objects, new datatypes, anything goes. ...
package sysio import ( "errors" "fmt" "io" "os" "runtime" ) type Pin struct { no uint8 fd *os.File } var ( ErrInvalidPin = errors.New("invalid pin number") ErrPinClosed = errors.New("pin closed") ) func OpenPin(n uint8) (p *Pin, err error) { if n&PI_GPIO_MASK != 0 { err = ErrInvalidPin return } fd,...
package main import ( "encoding/json" "fmt" "path/filepath" "strings" "time" "github.com/automattic/go/jaguar" ) // struct for reading local file in type Page struct { Title, Content, Category, Status, Tags string Date time.Time } func getApiFetcher(endpoint string) (j jagu...
/* There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations: Serve 100 ml of soup A and 0 ml of soup B, Serve 75 ml of soup A and 25 ml of soup B, Serve 50 ml of soup A and 50 ml of soup B, and Serve 25 ml of soup A and 75 ml of soup B. When we s...
package gogit import ( "encoding/json" "fmt" "sort" "github.com/NavenduDuari/goinfo/gogit/utils" ) var ( // totalByteCount float64 ) func getLanguages(userName string) []utils.LanguageWithByteMap { var languages []utils.LanguageWithByteMap repos := getRepos(userName) go func() { for _, repo := range repos ...
package main import "fmt" func getGoodBye(name string) string { return "Good Bye " + name } func main() { // function as value sayGoodBye := getGoodBye result := sayGoodBye("Danil") fmt.Println(result) fmt.Println(getGoodBye("haykal")) }
package bingSpellCheck import ( "encoding/json" "io/ioutil" "net/http" "net/url" "strings" "time" ) // BingHost is the host/domain for Bing Spell Check API const BingHost = "https://api.cognitive.microsoft.com" // BingSpellCheckPath is the url path of the Bing spell check, version 7, API const BingSpellCheckPa...
package models import "github.com/jinzhu/gorm" const ( ArticleStatusPublished = 0 // 已发布 ArticleStatusLower = 1 // 已下架 ArticleStatusDraft = 2 // 草稿 TopicStatusOk = 0 TopicStatusDeleted = 1 TopicTagStatusOk = 0 TopicTagStatusDeleted = 1 ContentTypeHtml = "html" ContentTypeMarkdown = "...
package main_test import ( "testing" ) func TestGopherit(t *testing.T) { t.Logf("Testing all of Gopherit....") }
package util import ( "fmt" "github.com/golang-jwt/jwt" "time" ) var mySigningKey = []byte("a343be788860d10ef767c078884cccaf") func CreateJwtToken(id string) (string ,error){ claims := &jwt.StandardClaims{ ExpiresAt: time.Now().Add(time.Hour*24).Unix(), Issuer: "neko", Subject: id, } token := jwt.New...
package main import ( "bufio" "fmt" "io" "log" "os" ) const ( openGroup byte = 123 closeGroup byte = 125 openGarbage byte = 60 closeGarbage byte = 62 cancelChar byte = 33 ) func checkErr(err error) { if err != nil { log.Fatalf("Error: %v", err) } } func main() { f, err := os.Open("input.txt") checkEr...
package addons import ( "fmt" addonsv1alpha1 "github.com/kyma-project/helm-broker/pkg/apis/addons/v1alpha1" ) // RepositoryCollection keeps and process collection of RepositoryController type RepositoryCollection struct { Repositories []*RepositoryController } // NewRepositoryCollection returns pointer to Reposi...
package support import ( "context" "fmt" "github.com/go-kit/kit/log" auth "github.com/inhumanLightBackend/auth/logic" user "github.com/inhumanLightBackend/user/logic" ) type Service interface { CreateTicket(context.Context, *Ticket) (string, error) GetTicket(context.Context, int) (*Ticket, error) Tickets(con...
package archive import ( "os" "sort" "github.com/argoproj/pkg/errors" log "github.com/sirupsen/logrus" "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo/cmd/argo/commands/client" workflowarchivepkg "github.com/argoproj/argo/pkg/apiclient/workflowarchive" wfv1 "...
// Package vultr implements a DNS provider for solving the DNS-01 challenge using // the vultr DNS. // See https://www.vultr.com/api/#dns package vultr import ( "errors" "fmt" "log" "strings" vultr "github.com/JamesClonk/vultr/lib" "github.com/xenolf/lego/acme" dp "gomodules.xyz/dns/provider" "gomodules.xyz/e...
package main /** 343. 整数拆分 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 示例1: ``` 输入: 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。 ``` 示例2: ``` 输入: 10 输出: 36 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。 ``` */ /** 思路就是 3 * 3 > 2 * 2 * 2 >>> 即每次将数减去 3 直到不够3,最小到4,因为 4 可以分解成 1 * 3 | 2 * 2, 应取 2 * 2 */ func IntegerBreak(n int) in...
package main import ( "time" ) type Image struct { UUID string path string thumbPath string Added string // RFC3339 Unlisted bool Expires string // RFC3339 Delete string Owner string cookie string RecentKey []byte } func NewImage(owner string, UUID string, path string, thumbPath...
package rpcd import ( "io" "github.com/Cloud-Foundations/Dominator/fleetmanager/hypervisors" "github.com/Cloud-Foundations/Dominator/lib/log" "github.com/Cloud-Foundations/Dominator/lib/srpc" "github.com/Cloud-Foundations/Dominator/lib/srpc/serverutil" ) type srpcType struct { hypervisorsManager *hypervisors.M...
package config import ( "fmt" "os" "gopkg.in/yaml.v3" ) type dashboardConfig struct { FeedConfig FeedConfig `yaml:"feeds"` } var cfg = &dashboardConfig{} func LoadYAML(path string) error { content, err := os.ReadFile(path) if err != nil { return fmt.Errorf("failed to read config at %q: ...
package templates import ( "fmt" "github.com/david-sorm/montesquieu/globals" "github.com/radovskyb/watcher" "html/template" "io/ioutil" "regexp" "strings" "time" ) var Store *template.Template // Hot Swap Templates should be run as a singleton, so that's the reason for this variable var liveTemplatesRunning ...
package spider import ( "fmt" "log" "math" "strings" "time" "github.com/antchfx/htmlquery" "github.com/gocolly/colly" "github.com/gocolly/colly/debug" "github.com/gocolly/colly/extensions" ) // 总代理量 var total = 4296 var limit = 20 type Spider struct { Referer string UserAgent string Collector *colly....
package polymorphism type Iduck interface { Quack() }
package main import ( "context" "fmt" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" database "graphql-mongo/data" "graphql-mongo/mutations" "graphql-mongo/queries" "log" "net/http" "os" "time" "github.com/graphql-go/graphql" ...
/* * Copyright 2017 - 2019 KB Kontrakt 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 require...