text
stringlengths
11
4.05M
package main import ( "context" "log" "github.com/fergusn/capi-controller/pkg/clusters" "k8s.io/apimachinery/pkg/runtime" controller "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/log/zap" "sigs.k8s.io/controller-runtime/pkg/manager" corev1 "k8s.io/client-go/kubernetes/scheme" capiv1 "...
package queries import ( "database/sql" "encoding/json" "net/url" "time" "github.com/pwang347/cs304/server/common" ) func QueryEventLogsForVirtualMachine(db *sql.DB, params url.Values) (data []byte, err error) { var ( response = SQLResponse{} tx *sql.Tx vmIp string ) if tx, err = db.Begin();...
package main import ( "log" "strconv" ) type Alpha struct { Number int Length int } var alphaMap = map[string]Alpha{ "ze": {0, 4}, "on": {1, 3}, "tw": {2, 3}, "th": {3, 5}, "fo": {4, 4}, "fi": {5, 4}, "si": {6, 3}, "se": {7, 5}, "ei": {8, 5}, "ni": {9, 4}, } func solution(s string) int { res := 0 le...
package nifi import ( "bytes" "encoding/json" "fmt" "io" "log" "net/http" "sync" "time" ) type Client struct { Config Config Client *http.Client // The mutex is used by the plugin to prevent parallel execution of some update/delete operations. // There are scenarios when updating a connection involves mo...
package main import ( "encoding/json" "fmt" "os" "github.com/davecgh/go-spew/spew" "github.com/keybase/client/go/libkb" "github.com/keybase/client/go/logger" "github.com/keybase/client/go/protocol/keybase1" "github.com/keybase/client/go/teams" ) type ChainFile struct { Chain []teams.SCChainLink `json:"chain...
package master import ( "github.com/OHopiak/fractal-load-balancer/core" "github.com/jinzhu/gorm" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) type ( UserMiddlewareConfig struct { // Skipper defines a function to skip middleware. Skipper middleware.Skipper DB *gorm.DB } ) ...
package crypto import ( "crypto/rsa" "crypto/x509" "encoding/json" "encoding/pem" "errors" "fmt" "io/ioutil" "github.com/lestrrat/go-jwx/jwk" ) func PublicKeysJWK(keys map[string]*rsa.PublicKey) ([]byte, error) { set := &jwk.Set{} for kid, key := range keys { rk, err := jwk.New(key) if err != nil { ...
package cmd import ( "fmt" "io/ioutil" "os" "path" "regexp" "time" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/config" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/transport/http" "github.com/integr8ly/delorean/pk...
package que_test import ( "bytes" "context" "crypto/rand" "database/sql" "encoding/hex" "encoding/json" "errors" "fmt" "io" "math" "os" "reflect" "strings" "sync" "testing" "time" _ "github.com/lib/pq" "github.com/tnclong/go-que" "github.com/tnclong/go-que/pg" ) func TestQueue_Queue(t *testing.T) ...
// Copyright (c) 2020 Xiaozhe Yao & AICAMP.CO.,LTD // // This software is released under the MIT License. // https://opensource.org/licenses/MIT package utilities import ( "log" "os" "os/user" "path/filepath" "time" ) const ( defaultTimeout = 5 * time.Second ) // GetHomeDir returns current user's home directo...
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later package controller import ( "fmt" pbc "github.com/swinslow/peridot-core/pkg/controller" pbs "github.com/swinslow/peridot-core/pkg/status" ) // Start tries to start the Controller, and returns error message explaining // why not if it can't. func (c *Cont...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00300105 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.003.001.05 Document"` Message *MeetingEntitlementNotificationV05 `xml:"MtgEntitlmntNtfctn"` } func (d...
// Copyright 2023 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 user import "context" type Storage interface { GetByID(id string) (u User, err error) FindOneByNickName(nickname string) (u User, err error) PingPool(ctx context.Context) error Close() }
package pool import "errors" type op string const ( // Hash is the bcrypt work type Hash op = "encrypt" // Compare is bcrypt compare work Compare = "decrypt" ) // WorkRequest is a worker req type WorkRequest struct { Op op Text []byte Compare []byte // optional } // WorkResponse is a worker resp typ...
package sync import ( syncComm "github.com/HNB-ECO/HNB-Blockchain/HNB/sync/common" ) type blockSyncReq struct { chainID string beginIndex uint64 endIndex uint64 replyChain chan error peerID uint64 notifyHandler syncComm.NotifyFunc version uint32 } func (sh *SyncHandler) blockSyn...
// Copyright 2020 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 ( "fmt" ) type Bootcamp struct { Lat float32 Lon float32 } func main() { x := new(Bootcamp) x.Lat = 12.3123 y := Bootcamp{} y.Lat = 12.3123 fmt.Println(x) fmt.Println(y) fmt.Println(*x == y) }
package bot import ( "strings" "fmt" ) const ( success = "SUCCESS" failure = "FAILURE" ) const ( build = "build" status = "status" alias = "alias" ) type BotCommand interface { Execute([]string) (string, error) Usage() string Options() []Option } type argError struct { arg string prob string } func (e...
package lib import ( "crypto/tls" "encoding/json" "fmt" "net/http" "net/url" "strings" log "github.com/sirupsen/logrus" ) const contentTypeHeader = "content-type" var Chan chan []*http.Request func ConfigureProxy(proxy string) { proxyUrl, err := url.Parse(proxy) if err != nil { log.Warnf("Error configur...
package main func main() { switch tag { case 0, 1, 2, 3: s1() case 4, 5, 6, 7: s2() default: s3() } switch x := f(); { // missing switch expression means "true" case x < 0: return -x default: return x } switch { case x < y: f1() case x < z: f2() case x == 4: f3() } }
package main import ( "bytes" "encoding/json" "fmt" "github.com/yddeng/raft/kv" "net/http" ) var ( // raft 对外地址 peers = map[string]string{ "kv1": "127.0.0.1:7000", "kv2": "127.0.0.1:7001", "kv3": "127.0.0.1:7002", } list []string ) func makeList(leader string) { list = []string{leader} for name := r...
package network import ( "fmt" "math" ) //MLNetwork . type MLNetwork struct { netdef []int in *mlLayer layers []*mlLayer out *mlLayer phi float64 biais bool created bool } var dataFileMap = make(map[string]*MlDataSet) func sigmoid(value float64) float64 { return 1 / (1 + math.Exp(-value))...
package collectors import ( "time" cfclient "github.com/cloudfoundry-community/go-cfclient" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/log" ) type IsolationSegmentsCollector struct { namespace string environment ...
package port import ( "github.com/mirzaakhena/danarisan/domain/repository" "github.com/mirzaakhena/danarisan/domain/service" ) // BukaAplikasiOutport ... type BukaAplikasiOutport interface { repository.FindOnePesertaRepo repository.FindOneArisanRepo repository.FindAllPesertaRepo repository.FindAllSlotRepo repo...
package ewallet import ( "os" "github.com/xendit/xendit-go/ewallet" "github.com/imrenagi/go-payment/invoice" ) // NewLinkAja is factory for LinkAja payment with xendit latest charge API func NewLinkAja(inv *invoice.Invoice) (*ewallet.CreateEWalletChargeParams, error) { props := map[string]string{ "succ...
package main import ( "github.com/miekg/dns" "testing" ) func TestFilters(t *testing.T) { // Enable debug logging log_debug = true } func TestNoFilters(t *testing.T) { filterer := QueryFilterer{} msg := generateDNSMessage("discodns.net", dns.TypeA) if filterer.ShouldAcceptQuery(msg) != true { t.Error("Expe...
package main import ( "encoding/json" "fmt" "log" "net" "net/rpc" "os" "strconv" "strings" "time" ) //struttura dei topic type Topic struct { //argomento del messaggio topic string //IP []byte IP []string //numero di porta port []int } var msgs *[]Message var topics []Topic var semantica int var tim...
package main import ( "net/http" "html/template" "github.com/gorilla/mux" ) var t *template.Template func init(){ t=template.Must(template.ParseFiles("catindex.html")) } func main() { router:=mux.NewRouter() router.Handle("/background.jpg",http.StripPrefix("/",http.FileServer(http.Dir("./")))) router.Han...
package main import "os" func getNodeName() string { h, err := os.Hostname() if err != nil { return "unknown" } return h }
/* Challenge: Given a string s on the characters a-z, A-Z, 0-9, append the length of s to itself, counting the additional character(s) in the length as part of the total length of s. Input: Just a string of arbitrary length (can be empty). Output: The same string, but with its length appended to the end. The chara...
/* Copyright 2021 The KubeVela 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 writ...
package main import ( "net/http" "html/template" ) type controller string func (h controller) Fire(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("views/example.html") //setp 1 t.Execute(w, "Programmer") //step 2 } // Controller exported name var Controller controller
package trigger // ButtonTrigger is trigger for creating events on each push button. type ButtonTrigger struct { triggersChan chan bool } // NewButtonTrigger creates a new NewButtonTrigger. func NewButtonTrigger(ch chan bool) *ButtonTrigger { return &ButtonTrigger{triggersChan: ch} } // TriggersChan returns the ...
package main import ( "github.com/valyala/fasthttp" ) /* circuit breaker, response for handle requests, decide reject it or not, record response status. */ // Breaker is circuit breaker, it's a collection of Application type Breaker struct { apps map[string]*Application } // NewBreaker return a brand new circuit ...
package records import ( "testing" "github.com/coredns/caddy" ) func TestRecordsParse(t *testing.T) { tests := []struct { input string shouldErr bool expectedOrigins []string }{ { `records { @ IN MX 10 mx1.example.org. } `, false, []string{"."}, }, } for i, test := range ...
package leetcode /*Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree...
package cache import ( "sync" "container/list" ) // LFU(Least Frequently Used) // paper :http://dhruvbird.com/lfu.pdf // head 1 2 5 9 freqNode list // x z b c dataNode // y a // or: // 3 map:(k-v)、(k-count)、(count-keySet)。 // get:O(1);put:O(1):Space: O(n); type dataNode struct { key ...
package main import ( "context" "fmt" "github.com/olivere/elastic/v7" ) // 构造一个student结构体 type Student struct { Name string `json:"name"` Age int `json:"age"` Married bool `json:"married"` } func (s *Student)run() *Student { fmt.Printf("%s在跑...", s.Name) return s } func (s *Student)play()*Stud...
package wire import ( "bytes" "io" "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/protocol" "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/internal/utils" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("BLOCKED frame", func() { Context("whe...
package node import ( "context" "errors" "log" "sync" "time" data "github.com/bgokden/veri/data" "github.com/bgokden/veri/util" pb "github.com/bgokden/veri/veriservice" ) func GetDataSourceClient(p *pb.Peer, name string, idOfPeer string, connectionCache *util.ConnectionCache) data.DataSource { return &DataS...
package main import ( "fmt" ) func main() { var a, b = 1, "This is string" fmt.Printf("\nType: %T, Data: %d", a, a) fmt.Printf("\nType: %T, Data: %s", b, b) fmt.Println() var c, d, e = 1, 3.14, true fmt.Printf("\nType: %T, Data: %d", c, c) fmt.Printf("\nType: %T, Data: %f", d, d) fmt.Printf("\nType: %T, Da...
package main import ( "bufio" "bytes" "os" "strings" ) func readLines(path string) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } re...
package log import ( "net/http" log "github.com/Sirupsen/logrus" ) func LogError(r *http.Request, err error, info string, logger *log.Logger) { logger.WithFields(log.Fields{ "error": err.Error(), "method": r.Method, "url": r.URL.String(), }).Error(info) } func Error(msg string) map[string]interface{} ...
package cachegroup_test import ( "reflect" "testing" "github.com/221bytes/negroniredis/cachegroup" ) func Test(t *testing.T) { cg0 := cachegroup.CreateCacheGroup("test", "tolo", "yolo") cg1 := cachegroup.CreateCacheGroup("tata", "tolo", "yolo") cg2 := cachegroup.CreateCacheGroup("toto", "tolo", "yolo") cgm :=...
// Template Declare Start // // ${function_name} // @Description:${todo} // @receiver ${receiver} // @param ${params} // @return ${ret_type} // // Template Declare End // Methods Declare // // Method1 // @Description: // func Method1() { } // // Method1_1 // @Description: // @return func(int64) error // func Meth...
package lintcode /** * Definition for a binary tree node. * */ type TreeNode struct { Val int Left *TreeNode Right *TreeNode } /** * @param inorder: A list of integers that inorder traversal of a tree * @param postorder: A list of integers that postorder traversal of a tree * @return: Root of a tree */ f...
package main import ( "net/http" ) type AddHeaderMiddleware struct { key string val string } func (a AddHeaderMiddleware) Process(handler http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set(a.key, a.val) handler(w, r) } } func New(params map[string]inte...
package rstreams import ( "context" "io/ioutil" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/sirupsen/logrus" "github.com/batchcorp/plumber-schemas/build/go/protos/args" "github.com/batchcorp/plumber-schemas/build/go/protos/opts" "github.com/batchcorp/plumber/validate" ) var _ = Describ...
package client type IdleChannel struct { input chan Command output chan Command buffer Command } func NewIdleChannel() *IdleChannel { ch := &IdleChannel{ input: make(chan Command), output: make(chan Command), } go ch.run() return ch } func (ch *IdleChannel) In() chan<- Command { return ch....
package main import "fmt" func main() { x := []string{"Donald", "Duck", "Andeby", "Norge"} y := []string{"Fantomet", "Walker", "Hodeskallegrotten", "Afrika"} fmt.Println(x) fmt.Println(y) x = append(x[:1], x[2:]...) //:1 tar med seg index 0, men dropper index 1. [:1 går til 1 man tar ikke med 1] //,og fortsett...
package main import ( "fmt" "os" "io" "bufio" "bytes" ) func main() { file, err := os.Open("/tmp/aa.txt") if err != nil { fmt.Println(err.Error()) } defer file.Close() br := bufio.NewReader(file) var buf bytes.Buffer for { ba, isPrefix, err := br.ReadLine() if err != nil { if err == io.EOF { ...
package main import ( "fmt" "github.com/AnhNguyenQuoc/go-blog/routes" "log" "net/http" "os" "github.com/AnhNguyenQuoc/go-blog/lib" "github.com/AnhNguyenQuoc/go-blog/migrate" "github.com/jinzhu/gorm" "github.com/joho/godotenv" "github.com/julienschmidt/httprouter" ) var dbConfig migrate.DBConfig var db *gor...
package flatten_test import ( "testing" "github.com/google/go-cmp/cmp" "go.jlucktay.dev/golang-workbench/flatten/pkg/flatten" ) func TestFlatten(t *testing.T) { testCases := map[string]struct { input interface{} expected []int }{ "Hello world - [[1,2,[3]],4] -> [1,2,3,4]": { input: []interface{}{ ...
package cron import ( "encoding/json" "fmt" "log" "os" "strings" "github.com/argoproj/pkg/errors" "github.com/argoproj/pkg/humanize" "github.com/spf13/cobra" "sigs.k8s.io/yaml" "github.com/argoproj/argo/cmd/argo/commands/client" "github.com/argoproj/argo/pkg/apiclient/cronworkflow" wfv1 "github.com/argop...
/* --- Day 3: Spiral Memory --- You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like th...
package alchemyapi import ( "testing" ) func TestEntryPointsHasArrange(t *testing.T) { eps := make(EntryPoints) if got := eps.hasArrange("foo"); got == true { t.Errorf("want %t, but %t", !got, got) } eps["foo"] = make(map[string]string) eps["foo"]["bar"] = "uri" if got := eps.hasArrange("foo"); got == false...
package handler import ( "fmt" "github.com/gin-gonic/gin" "proxy_download/model" ) func NameValidate(context *gin.Context, tableName string) (result bool, err error) { var params = struct { Name string `json:"name"` Id int `json:"id"` UserId int `json:"user_id"` }{} err1 := context.BindJSON(...
package task type DailyTask struct { TaskBase } func NewDailyTask() *DailyTask { dt := &DailyTask{} return dt }
package tyme import ( "fmt" "time" ) // LocalHour represents year, month and daae without Location // e.g) January 2, 2006 type LocalHour struct { date LocalDate hour int } // NewLocalHour returns instance of LocalHour with given year, month and date func NewLocalHour(year int, month time.Month, date int, hour i...
package options import ( "github.com/spf13/pflag" ) type Config struct { ListenAddress string TlsCertFile string TlsPrivateKey string KeystoneUrl string } func NewConfig() *Config { return &Config{} } func (c *Config) AddFlag(fs *pflag.FlagSet) { fs.StringVar(&c.ListenAddress, "listen", "127.0.0.1:8443",...
package main import "fmt" //结构体模拟实现其他语言中的“继承” type animal struct { name string } //给animal实现一个移动的方法 func (a animal) move() { fmt.Printf("%s会动!\n", a.name) } //狗类 type dog struct { feet uint8 animal //animal拥有的方法dog也拥有了(利用匿名结构体的语法糖) } //给dog实现一个汪汪汪的方法 func (d dog) wang() { fmt.Printf("%s:汪汪汪\n", d.name) } ...
/* Copyright 2018 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 kshortestpaths import ( "fmt" "testing" ) func TestGraphCreation(t *testing.T) { g := MakeStationGraph() s1 := MakeStation("BOSSST", 42.361829, -71.05599) s2 := MakeStation("NYCPAS", 40.750315, -73.992865) g.AddEdge(s1, s2) // fmt.Println(g) fmt.Println(g.Distance(s1, s2)) }
// logic-clock project main.go package main import ( "fmt" ) type Processor struct { channel chan Msg timeSys TimeSys } type Msg struct { time TimeMsg data interface{} } func (self *Processor) Send(msg interface{}) { self.channel <- msg } func NewProcessor(n int, timeSys TimeSys) Processor { var ret Pr...
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "github.com/frk/gosql" ) func (q *DeleteWithUsingJoinBlock1Query) Exec(c gosql.Conn) error { const queryString = `DELETE FROM "test_user" AS u USING "test_post" AS p WHERE u."id" = p."user_id" AND p."is_spam" IS TRUE` //...
package filter import ( "time" "github.com/geoirb/rss-aggregator/pkg/models" ) // Filter ... type Filter struct { } // News filtering news func (f *Filter) News(src []models.News, format string, interval time.Duration) (dst []models.News) { dst = make([]models.News, 0, len(src)) for _, news := range src { bor...
package main import "fmt" /* 当函数的连续多个参数是同一类型,则除了最后一个参数需类型声明之外,其他的都可以去省略 */ func add(x, y int) int { return x + y } /* 函数可以返回任意数量的返回值 */ func swap(x, y string) (string, string) { return y, x } func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return } func main() { fmt.Println(add(1, 2)) fmt.Printl...
package intersect // Numbers provides interface for numbers struct type Numbers interface { Intersect() []int } type numbers struct { nums1 []int nums2 []int } // Intersect main algorithm function func (n *numbers) Intersect() []int { m := map[int]int{} for _, el := range n.nums1 { m[el]++ } out := make([]i...
package main import "math/bits" func intMax(x, y int) int { if x > y { return x } return y } func bitsLen(b byte) int { i := uint(b) return bits.Len(i) }
package cursor import "fmt" import "os" const csi = "\033[" func Up(lines int) string { if os.Getenv("TERM") == "" { return "" } else { return fmt.Sprintf("%s%dA", csi, lines) } } func ClearToEndOfLine() string { if os.Getenv("TERM") == "" { return "" } else { return fmt.Sprintf("%s%dK", csi, 0) } } ...
package crawler import ( "go.core/lesson4/pkg/crawler/stub" "testing" ) var s stub.Scanner func TestScan(t *testing.T) { tests := []struct { name string urls []string depth int }{ {"1", []string{"test.com", "test2.com"}, 2}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { document...
package apis import ( "encoding/base64" "fmt" "io/ioutil" "project/utils/config" "strings" "project/app/admin/models" "project/pkg/tools" "project/utils" "project/utils/app" "github.com/gin-gonic/gin" "github.com/google/uuid" ) // UploadFile 文件上传(任意类型文件) // @Summary 文件上传(任意类型文件) // @Description Author:Ji...
/* Copyright 2021 CodeNotary, 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. 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 persistence import ( "context" "github.com/dsukesato/go13/pbl/app1-backend/domain/model" "github.com/dsukesato/go13/pbl/app1-backend/domain/repository" "time" ) type PostsPersistence struct {} func NewPostsPersistence() repository.PostsRepository { return &PostsPersistence{} } //int, int, int, string, ...
package main import ( "bufio" "fmt" "os" "sort" ) func main() { scanner := bufio.NewScanner(os.Stdin) scanner.Split(bufio.ScanLines) printBlank := false for scanner.Scan() { var a int fmt.Sscanf(scanner.Text(), "%d", &a) if a == 0 { break } if printBlank { fmt.Println() } printBlank = ...
/* Copyright 2021 Digitalis.IO. 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 d...
package main import ( "fmt" "io/ioutil" "log" "os" "strconv" "strings" ) const ( numberOfRows = 6 numberOfCols = 25 colorBlack = 0 colorWhite = 1 ) // Layer represents a 2D grid with pixels. type Layer [][]int func main() { if len(os.Args) < 2 { log.Fatal("missing file as input") } line, err := ...
package main import ( "fmt" // Print "os" // Arguments passed to the program "strconv" // Atoi "time" ) var nRect uint32 = 0 var nRutinas uint32 = 0 var anchRect float64 = 0 var areaTotal float64 = 0 func f(x float64) (y float64) { return 4.0 / (1.0 + x*x) } // Tarea que cada goroutine tiene que reali...
package models import ( "reflect" "strings" ) func contains(ss []string, s string) bool { for _, v := range ss { if v == s { return true } } return false } func ParseFields(fields string) ([]string, map[string][]string) { fieldsParse := strings.Split(fields, ",") roop := make([]string, len(fieldsParse)...
package seccomp import ( "fmt" specs "github.com/opencontainers/runtime-spec/specs-go" ) // BruteForceSource represents a system calls source based on a brute force approach. type BruteForceSource struct { options []string runner BruteForceRunner } // BruteForceRunner defines the interface for brute force runn...
// Copyright 2021 Google LLC // // 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 ...
package nettools import ( "fmt" "net" ) func GetIP() (string, error) { addrs, err := net.InterfaceAddrs() if err != nil { return "", fmt.Errorf("failed to get interface addreses: %v", err) } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil...
//+build test // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package azure import ( "fmt" "testing" "time" ) func TestIsClusterExpired(t *testing.T) { cases := []struct { rg ResourceGroup a Account duration string expectedRes...
package pages const Login string = ` <html> <head><title>Sessions Example</title></head> <body> <form action="login" method="post"> <input name="username" /> <input name="password" type="password" /> <input type="Submit" /> </form> </body> </html>` const Home string = ` <html> <head><title>Sessions Example</t...
/* Copyright The Helm 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, software di...
package leetcode func MergeKLists(lists []*ListNode) *ListNode { if len(lists) == 0 { return nil } if len(lists) == 1 { return lists[0] } var m *ListNode for i := 0; i < len(lists); i++ { m = mergeTwoLists(m, lists[i]) } return m } func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { m := &ListNo...
package proxy import ( "github.com/sirupsen/logrus" v1apps "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" ) // BuildDeployment builds kubernetes deployment object to create proxy container of the database func BuildDeployment(proxy Proxy) (*v1apps.Deployment, error) { deploy, err := proxy.buildDeployment() if err ...
/* 命題 与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ. * 英小文字ならば(219 - 文字コード)の文字に置換 * その他の文字はそのまま出力 この関数を用い,英語のメッセージを暗号化・復号化せよ. */ package main import ( "fmt" ) func cipher(str string) string { var encodedStr string for _, v := range str { if v > 'a' && v < 'z' { encodedStr += string(219 - v) } else { encode...
package types import "net/http" // // Route is used to denote a route for all // API routers // type Route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc }
package main import ( "fmt" ) const ( lseed = 516 rseed = 190 lfactor = 16807 rfactor = 48271 divisor = 2147483647 maxvals = 40000000 bitmask = 65535 ) func genNext(val int, factor int) int { return (val * factor) % divisor } func main() { sum := 0 lval := lseed rval := rseed for i := 0; i < maxvals; i...
/* Copyright 2023 The KubeVela 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, so...
package util import ( "bufio" "fmt" "io" "net/http" "os" ) func DownloadImg(imgUrl string) (name string,path string) { imgPath := "/Users/ZhuangXiaoDa/open-work/image/blog/" fileName := CreateRandomString(10) writePath := imgPath + fileName + ".jpg" res, err := http.Get(imgUrl) if err != nil { fmt.Prin...
package linters import ( "github.com/simonjohansson/go-linter/model" "github.com/simonjohansson/go-linter/manifest" ) type Linter interface { Lint() (model.Result, error) LintManifest(manifest model.Manifest) (model.Result, error) } type FullLint struct { Config model.LinterConfig ManifestReader ...
package router import ( "project/app/admin/apis" "project/app/admin/middleware" "project/utils/app" "github.com/gin-gonic/gin" ) func init() { routerNoCheckRole = append(routerNoCheckRole, jobRouter) routerCheckRole = append(routerCheckRole, jobAuthRouter) } // 无需认证的路由代码 func jobRouter(v1 *gin.RouterGroup) { ...
package myTime import ( "fmt" "time" ) func TimeTest(s string) { fmt.Println(s) wipsd, err := time.Parse("2006/01/02 15:04:05", s) if err != nil { fmt.Println(err) } fmt.Println(wipsd.Unix()) t := time.Now() for i := 0; i < 2; i++ { t = t.AddDate(0, 0, -1) fmt.Println(t.Format("2006/01/02 15:04:05")...
package source import ( "errors" "math/rand" ) //默认初始化方法,供别的方法调用 func init() { RegisterBalancer("random", &RandomBalance{}) } //随机调度算法 简单实现 type RandomBalance struct { } func (p *RandomBalance) DoBalance(insts []*Instance, key ...string) (inst *Instance, err error) { if len(insts) == 0 { err = errors.New("in...
// +build linux package volume import "testing" // Tests allocate. func TestFallocate(t *testing.T) { err := Fallocate(0, 0, 0) if err != nil { t.Fatal("Unexpected error in fallocate for length 0:", err) } }
// Copyright 2017 Google 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. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
package triangle import ( "image" "image/color" "image/png" "io" "os" "github.com/fogleman/gg" ) const ( WITHOUT_WIREFRAME = iota WITH_WIREFRAME WIREFRAME_ONLY ) // Processor : type with processing options type Processor struct { BlurRadius int SobelThreshold int PointsThreshold int MaxPoints ...