text
stringlengths
11
4.05M
package main import ( "fmt" "os" ) func first() { fmt.Println("1st") } func second() { fmt.Println("2nd") } func main() { /* defer จะใช้กำหนดฟังก์ชันที่ถูกเรียกใช้งาน เมื่อฟังก์ชันหลักที่ครอบ defer อยู่ทำงานเสร็จ*/ // ผลลัพธ์จะได้ 1st ตามด้วย 2nd defer second() first() // run function testDefer() } // def...
package dbsrv import ( "github.com/empirefox/esecend/front" "github.com/empirefox/reform" "github.com/mcuadros/go-defaults" "gopkg.in/doug-martin/goqu.v3" ) func (s *DbService) SaveProfile(p *front.Profile) error { p.ID = 1 if err := s.GetDB().Update(p); err != nil { if err != reform.ErrNoRows { return err...
package main import "log" import zmq "github.com/pebbe/zmq3" import "fmt" import "time" import "sync" //create router socket and just print received messages func rrecv(socket *zmq.Socket) { log.Println("hooking up router...") socket.SetIdentity("router") socket.Bind("tcp://127.0.0.1:9999") for ...
package msaevents import ( "encoding/json" "fmt" ) type EventType string const ( EventTypeCreatedUser EventType = "CREATED_USER" EventTypeUpdatedUser EventType = "UPDATED_USER" EventTypeCreatedPasswordLost EventType = "CREATED_PASSWORD_LOST" EventTypeCreatedWall EventTyp...
package db import ( "strconv" "time" "cloud.google.com/go/datastore" "github.com/steam-authority/steam-authority/helpers" ) type Change struct { CreatedAt time.Time `datastore:"created_at,noindex"` ChangeID int `datastore:"change_id"` Apps []ChangeItem `datastore:"apps,noindex"` Packages [...
package main import ( "os" ) func dirExists(path string) bool { stat, err := os.Stat(path) if err != nil { return false } if stat.IsDir() == false { return false } return true } func fileExists(path string) bool { stat, err := os.Stat(path) if err != nil { return false } if stat.IsDir() == true { ...
package main import ( "context" "google.golang.org/protobuf/encoding/protojson" "log" "net" "net/http" "strconv" tdlpb "github.com/FunnyDevP/example-grpc-gateway/api/proto/todolist" td "github.com/FunnyDevP/example-grpc-gateway/internal/todolist" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.g...
package database import ( "context" "fmt" "github.com/jackc/pgconn" "github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4/log/logrusadapter" "github.com/jackc/pgx/v4/pgxpool" _ "github.com/lib/pq" "github.com/shysa/TP_proxy/config" "github.com/sirupsen/logrus" "os" ) type DB struct { dbPool *pgxpool.Pool con...
package models import ( "strings" "time" ) // IntellectualObject in the format that Pharos accepts for // POST/create. type IntellectualObjectForPharos struct { Identifier string `json:"identifier"` BagName string `json:"bag_name"` BagGroupIdentifier string `json:"bag_group_identif...
package routes import ( "fmt" // "reflect" dg "github.com/bwmarrin/discordgo" "joebot/tools" "strings" ) /* cID = current channel ID cmdResList = map of commands and the corresponding responses */ var ( cmdResList map[string]string BotID string err error ) func SendMessage(s *dg.Session, cID st...
package main import "fmt" func main() { //1.使用冒泡排序进行分析和处理76,58,67,18,0,9, var array = [6]int{76, 58, 67, 18, 0, 9} bubbleSort(&array) fmt.Println("array", array) //2.顺序查找 name := [4]string{"迪迦奥特曼", "赛罗奥特曼", "古加奥特曼"} var yourinput string fmt.Println("请输入要查找的光之子:") fmt.Scanln(&yourinput) // for i := 0; i < l...
package handlers import ( "encoding/json" "github.com/Hoovs/OpenLibraryClient/server/db" "github.com/gorilla/mux" "io/ioutil" "net/http" "strconv" "go.uber.org/zap" ) type WishListHandler struct { Logger *zap.Logger Db *db.DB } func (wh *WishListHandler) PostWishListHandler(w http.ResponseWriter, r *ht...
package handlers import ( "github.com/labstack/echo" "github.com/stretchr/testify/assert" "io/ioutil" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) func TestHandler_ReportObjectDist(t *testing.T) { q := make(url.Values) endpoint := "/report/object-dist" h := &Handler{DB: &mockStore{}} e ...
package main import ( "crypto/tls" "encoding/json" //"fmt" "github.com/emicklei/forest" "net/http" "testing" ) var shw *forest.APITesting var testPassID string var testCompletePassID string var testMutateList []interface{} func init() { cfg := &tls.Config{ InsecureSkipVerify: true, } tr := &http.Transp...
package reporting type Report interface { Encode() ([]byte, error) Description() string }
package status import ( "bytes" "fmt" "github.com/gookit/color" ) type ChangeType string const ( UnModified ChangeType = "unmodified" Modified ChangeType = "modified:" Created ChangeType = "new file:" Deleted ChangeType = "deleted: " ) type Changes struct { Head ChangeType Worktree ChangeType ...
package resource import ( "fmt" "strings" ) // Type is a type of resource. type Type int // Page types. const ( TypeDrive Type = 0 TypeFile Type = 1 ) // String returns a string representation of t. func (t Type) String() string { switch t { case TypeDrive: return "drive#teamDrive" case TypeFile: return...
package web_test import ( "encoding/json" "net/http" "strings" "testing" "github.com/gofiber/session" "github.com/stretchr/testify/assert" "github.com/hi019/fiber-boilerplate/ent" "github.com/hi019/fiber-boilerplate/ent/enttest" "github.com/go-playground/validator" "github.com/gofiber/fiber" "github.com/...
package autocert import ( "context" "os" "runtime" "testing" "time" "github.com/caddyserver/certmagic" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/pomerium/pomerium/internal/testutil" ) func TestGCSStorage(t *testing.T) { t.Skip("fakeserver doesn't support multip...
package main import ( "encoding/binary" "fmt" "net" "time" ) func main(){ var number uint64 var buf = make([]byte, 16) // ----------------------- SETT OPP UDP-KOBLING ----------------------- // Creat Server Address, ServerAddr, err := net.ResolveUDPAddr("udp", "10.100.23.233:10001") if err != nil...
package yadisk import ( "bytes" "context" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" ) // httpClient for send request to Yandex.Disk API type client struct { httpClient *http.Client token *Token baseURL *url.URL ctx context.Context } // Construct httpClient func newClient(...
package list import ( "crypto/tls" "encoding/json" "fmt" "log" "time" "github.com/mickep76/auth/jwt" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/mickep76/grpc-exec-example/conf" pb_info "github.com/mickep76/grpc-exec-example/info" "github.com/micke...
package main import ( "regexp" "strconv" "strings" ) func zhunbeishuchu(class Class)NewClass{ day, _ := strconv.Atoi(class.Day) theday := "一二三四五六七"[(day-1)*3:day*3] lesson := strings.Split(class.Lesson, "-") lesson1,_ := strconv.Atoi(lesson[0]) lesson2,_ := strconv.Atoi(lesson[1]) var thelesson string for ...
package main import ( "net/http" "github.com/dxvgef/tsing" ) func main() { engine := tsing.New(&tsing.Config{}) engine.GET("/", func(context *tsing.Context) error { context.ResponseWriter.Write([]byte("hello world")) return nil }) http.ListenAndServe(":5656", engine) }
package main import ( "log" "github.com/BurntSushi/toml" ) type AppConfig struct { Magento *MagentoConfig Hpfeeds *HpfeedsConfig PublicIP *PublicIPConfig `toml:"fetch_public_ip"` } // MagentoConfig provides configuration for how to host the Magento web app // portion of the honeypot. // [magento] type Magent...
package outline type StyleType string const Dotted StyleType = "dotted" const Dashed StyleType = "dashed" const Solid StyleType = "solid" const Double StyleType = "double" const Groove StyleType = "groove" const Ridge StyleType = "ridge" const Inset StyleType = "inset" const Outset StyleType = "outset"
package mws import ( "fmt" "github.com/databrickslabs/databricks-terraform/common" ) // NewMWSCustomerManagedKeysAPI creates MWSCustomerManagedKeysAPI instance from provider meta func NewMWSCustomerManagedKeysAPI(m interface{}) MWSCustomerManagedKeysAPI { return MWSCustomerManagedKeysAPI{client: m.(*common.Databr...
package api import ( "fmt" "sharemusic/models/util" ) func SongUrl(query map[string]interface{}) map[string]interface{} { ids := "[" + query["id"].(string) + "]" fmt.Println(query["id"]) data := map[string]interface{}{ "ids": ids, "br": query["br"], } if data["br"] == nil { data["br"] = 999000 } optio...
package tbf import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "strings" "testing" "time" "github.com/golang/protobuf/proto" "go.mercari.io/datastore" "go.mercari.io/datastore/testsuite" netcontext "golang.org/x/net/context" "google.golang.org/appengine" ) // TestSuite contains all the test ca...
/* Copyright 2019 BlackRock, 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 in writing, software di...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03000101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.030.001.01 Document"` Message *AgentCADeactivationStatusAdviceV01 `xml:"AgtCADeactvtnStsAdvc"` } fun...
// 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 commands import ( "fmt" "os" "regexp" "github.com/qubitz/lawyer/laws" "github.com/qubitz/lawyer/trial" "github.com/TwinProduction/go-color" ) type indictCommand struct { paths []string lawPath string } func (indictment *indictCommand) Execute() error { law, err := laws.RetrieveFrom(indictment.law...
package main import ( //_ "image/gif" //_ "image/jpeg" _ "image/png" "github.com/360EntSecGroup-Skylar/excelize" ) func main() { f := excelize.NewFile() // Insert a picture. if err := f.AddPicture("Sheet1", "A2", "mypng.png", ""); err != nil { println(err.Error()) } // Insert a picture...
package update import "core" // CheckAndUpdate is a stub implementation that does nothing. func CheckAndUpdate(config *core.Configuration, updatesEnabled, updateCommand, forceUpdate, verify bool) { } // DownloadPyPy is also a stub that does nothing. func DownloadPyPy(config *core.Configuration) bool { return false ...
package main import ( "fmt" "io/ioutil" "strings" ) func part1() { // Assumes current working directory is `day-02/`! fileContent, err := ioutil.ReadFile("puzzle-input.txt") if err != nil { fmt.Println(err) } listOfIDs := strings.Split(string(fileContent), "\n") repeatCount := make(map[int]int) for _, b...
// +build linux /* Copyright (c) 2018 GigaSpaces Technologies Ltd. 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 requir...
package sum import "testing" func TestSum(t *testing.T) { result := Sum(1,1) if result != 2 { t.Errorf("%d does not equal 2", result) } }
/* nightHawkAPI.main; */ package main import ( "flag" "fmt" "log" "net/http" "nighthawk" api "nighthawkapi/api/core" routes "nighthawkapi/api/routes" "os" ) type RuntimeOptions struct { Debug, Help bool Server string Port int Version bool } func fUsage() { fmt.Printf("\tnightHawkAPI v%...
// Copyright (c) 2016 Readium Foundation // // 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 conditions and the following...
package pathrename import ( index "github.com/begopher/index/v2" ) type Config interface { Flag() Flag // flag determine whether reniming aogothitem apply on a file or dir DirIndexes(string) (start int, end int) // rename start at index FileIndexes(string) (start int, end int) // ren...
package main import ( "bytes" "encoding/json" "flag" "fmt" "io" "io/ioutil" "os" "os/exec" "regexp" "sort" "strings" ) type PType struct { Name string Help string Type string Counters []PCounter } type PCounter struct { Labels string Value uint64 } type VCounter struct { Description s...
package mqtt const ( QOS_0 = iota QOS_1 QOS_2 )
package observe import ( "fmt" "github.com/nokamoto/grpc-proxy/yaml" "github.com/prometheus/client_golang/prometheus/promhttp" "google.golang.org/grpc/codes" "io/ioutil" "net/http" "strings" "testing" "time" ) func TestProm_NewProm(t *testing.T) { yml, err := yaml.NewYaml("../testdata/yaml/prom_new.yaml") ...
package generator import ( "testing" "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/format" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/pomerium/pomerium/pkg/policy/parser" ) func Test(t *testing.T) { g := New(WithCriterion(func(g *Generato...
package p_test import ( "testing" "github.com/Kretech/xgo/encoding" "github.com/Kretech/xgo/p" ) type _S struct { } func (this *_S) a() string { return `_s.a` } func (this *_S) b(t string) string { return `_s.b(` + t + `)` } func TestDump(t *testing.T) { aInt := 1 bStr := `sf` cMap := map[string]interfac...
package main import ( "github.com/freignat91/mlearning/api" "github.com/spf13/cobra" ) type displayOptions struct { coef bool } var ( displayOpts = displayOptions{} ) //DisplayCmd . var DisplayCmd = &cobra.Command{ Use: "display", Short: "display network", Run: func(cmd *cobra.Command, args []string) { i...
package client import ( "bytes" "context" "encoding/hex" "fmt" "net/http" "time" "github.com/drand/drand/chain" "github.com/drand/drand/log" json "github.com/nikkolasg/hexjson" ) // HTTPGetter is an interface for the exercised methods of an `http.Client`, // or equivalent alternative. type HTTPGetter inter...
package gin import ( "github.com/game-explorer/animal-chess-server/internal/pkg/gin" "github.com/game-explorer/animal-chess-server/service/gin/handler" ) func New(debug bool) *gin.Engine { e := gin.NewGin(debug) handler.Ws(e) handler.Login(e) return e }
// 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 bench import ( "database/sql" "fmt" "log" "math" "math/rand" "time" sqlite "github.com/mattn/go-sqlite3" ) // Computes x^y func pow(x, y int64) int64 { return int64(math.Pow(float64(x), float64(y))) } //computes the percentage func targetPerc(current, target int64) float64 { return 100.0 * (float64...
package 位运算 func singleNumber(nums []int) int { number := 0 for i:=0;i<len(nums);i++{ number^=nums[i] } return number } /* 题目链接: https://leetcode-cn.com/problems/single-number/ */
package main // type SYSHEADStruct struct { // ServiceCode ServiceCodeStruct // ServiceScene ServiceSceneStruct // ConsumerID ConsumerIDStruct // TranDate TranDateStruct // TranTimeStammp TranTimeStammpStruct // } // type AppHeadStruct struct { // BussSeqNo BussSeqNoStruct // } // type BodyStruc...
package config import ( "gorm.io/driver/postgres" "gorm.io/gorm" ) func SetupDB() *gorm.DB { // refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details dsn := "host=localhost user=vianto password=Vianto1125 dbname=db_golang port=5432 sslmode=disable TimeZone=Asia/Shanghai" db, err := gor...
package flagset import ( "github.com/micro/cli/v2" "github.com/owncloud/ocis-hello/pkg/config" "github.com/owncloud/ocis/v2/ocis-pkg/flags" ) // RootWithConfig applies cfg to the root flagset func RootWithConfig(cfg *config.Config) []cli.Flag { return []cli.Flag{ &cli.StringFlag{ Name: "config-file", ...
package utilsauthentication import ( jwt "github.com/dgrijalva/jwt-go" ) // Auth - это базовая структура type Auth struct { Options Options } // Options - ... type Options struct { SigningKey string TokenKey string } // New - создает новый экземпляр ... func New() *Auth { var opts Options opts.SigningKey =...
package winkeys import ( "golang.org/x/sys/windows" "syscall" "time" "unsafe" ) const ( keyDown = 0 KeyExtend = 0x0001 keyUp = 0x0002 keyUnicode = 0x0004 ) /* 参考: https://docs.microsoft.com/ja-jp/windows/win32/inputdev/virtual-key-codes?redirectedfrom=MSDN */ const ( VkReturn = 13 VkA = 0...
package adaboost import ( "math" "github.com/gonum/matrix/mat64" ) type AdaBoostClassifier struct { nEstimators int nSamples int nFeatures int clfs []*baseLearner } type baseLearner struct { classifier *DecisionStump weight float64 } func NewAdaBoostClassifier(nEstimators int) *AdaBoostClas...
package context import ( "context" "os" "github.com/apex/log" "github.com/apex/log/handlers/text" ) // Initialize calls 3 functions to set up, then // logs before terminating func Initialize() { // set basic log up log.SetHandler(text.New(os.Stdout)) // initialize our context ctx := context.Background() // ...
package api_test import ( "context" "errors" "fmt" "net/http" "net/http/httptest" "testing" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/odpf/stencil/models" stencilv1 "github.com/odpf/stencil/server/odpf/stencil/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock"...
/* Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front; */ package main import ( "fmt" ) func front_times(s string, n int) string { if n <= 0 { return "" } var l int = 3 if ...
package status import ( "context" "io" "syscall" "github.com/projecteru2/cli/cmd/utils" corepb "github.com/projecteru2/core/rpc/gen" coreutils "github.com/projecteru2/core/utils" "github.com/sethvargo/go-signalcontext" "github.com/sirupsen/logrus" "github.com/urfave/cli/v2" ) type statusOptions struct { c...
package main import ( "flag" "fmt" "io" "net/http" "net/url" "strings" "github.com/juangm/go-exercises/go-htmlParser/link" ) func main() { urlFlag := flag.String("url", "https://gophercises.com", "the url that you want to build a sitemap for.") flag.Parse() pages := get(*urlFlag) for _, page := range pag...
package leetcode import ( "sort" ) type ByX [][]int type ByY [][]int func (ary ByX) Len() int { return len(ary) } func (ary ByY) Len() int { return len(ary) } func (ary ByX) Less(i, j int) bool { if ary[i][0] == ary[j][0] { return ary[i][1] < ary[j][1] } return ary[i][0] < ary[j][0] } func (ary ByY) Less(...
// Copyright (c) 2013-2017 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package main import ( "encoding/hex" "fmt" "net" "os" "os/user" "path/filepath" "runtime" "sort" "strings" "time" "github.com/btcsuite/btcd/btcutil" "githu...
// 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 model import ( "fmt" "gorm.io/gorm" "time" ) const PlatformBankCardTableName = "platform_bank_card" const ( //状态:1-启用, 2-禁用 PlatformBankCardEnable = 1 PlatformBankCardDisable = 2 ) type PlatformBankCard struct { Id int64 `gorm:"id"` // id BankName string `gorm:"bank_nam...
package listing import "errors" // ErrNotFound is used when a post could not be found. var ErrNotFound = errors.New("Post not found") // Repository provides access to the post storage. type Repository interface { // GetPost returns the post with given ID. GetPost(string) (Post, error) // GetAllPosts returns all p...
// Copyright 2019 The OpenSDS 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 agre...
package routeshandlers import ( "net/http" "github.com/gin-gonic/gin" ) // GetAllNoDataJSON simple no data handler func GetAllNoDataJSON(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{"msg": "No data"}) } // Saved Simple saved status func Saved(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"msg": "Saved"})...
package main func countPrimes(n int) int { // 筛法求质数 a := make([]bool, n) cnt := 0 for i := 2; i < n; i++ { if a[i] { continue } for j := i * i; j < n; j += i { a[j] = true } cnt++ } return cnt }
package main import ( "bufio" "fmt" "math" "os" "strconv" ) func main() { scan := func() func() int { scan := bufio.NewScanner(os.Stdin) scan.Split(bufio.ScanWords) return func() int { scan.Scan() i, _ := strconv.Atoi(scan.Text()) return i } }() n := scan() sticks := make([]int, n) for ...
package group import ( "Open_IM/internal/push/content_struct" "Open_IM/internal/push/logic" "Open_IM/pkg/common/config" "Open_IM/pkg/common/constant" "Open_IM/pkg/common/db" "Open_IM/pkg/common/db/mysql_model/im_mysql_model" "Open_IM/pkg/common/log" "Open_IM/pkg/grpc-etcdv3/getcdv3" pbChat "Open_IM/pkg/proto/...
package main import "bufio" import "fmt" import "os" import "sort" import "strconv" type input struct { arr []int } func main() { i := getInput() maxSetSize := 0 for x := 0; x < len(i.arr)-1; x++ { currentSetSize := 1 for y := x + 1; y < len(i.arr); y++ { if i.arr[y]-i.arr[x] <= 1 { currentSetSize++ ...
/** * Copyright (c) 2018 ZTE Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v10.html ...
package gogen import ( "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // Please note that this test suite refers to the // test_fixtures/simple.go test file. type ParseBaseTypeSuite struct { suite.Suite build *Build file *File complexBuild ...
package multierr import ( "fmt" "testing" "github.com/stretchr/testify/require" ) func TestFormatterList(t *testing.T) { newErrors := func(length int) []error { errs := make([]error, 0, length) for i := 0; i < length; i++ { errs = append(errs, fmt.Errorf("error-%d", i+1)) } return errs } t.Run("len:...
package cache import ( "github.com/ben-han-cn/g53" "github.com/ben-han-cn/vanguard/config" "github.com/ben-han-cn/vanguard/core" "github.com/ben-han-cn/vanguard/httpcmd" "github.com/ben-han-cn/vanguard/metrics" view "github.com/ben-han-cn/vanguard/viewselector" ) type Cache struct { core.DefaultHandler cache ...
package strregex_test import ( "testing" "github.com/nandarimansyah/gobasicbenchmark/strregex" ) func BenchmarkMatchString(b *testing.B) { for n := 0; n < b.N; n++ { strregex.IsMatchUsingMatchString("nanda@gmail.com") } } func BenchmarkMatchStringCompiled(b *testing.B) { for n := 0; n < b.N; n++ { strregex...
package main import ( "bytes" "encoding/json" "fmt" "github.com/Shopify/sarama" ) func main() { var msg = "Hello, I'm a message!" produceMsg(msg) } var ( producer sarama.SyncProducer brokers = []string{"127.0.0.1:9092", "127.0.0.1:9192"} topic = "saku" ) func init() { config := sarama.NewConfig() co...
/* Copyright 2020 Humio https://humio.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
package instance_test import ( "errors" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" fakesys "github.com/cloudfoundry/bosh-agent/system/fakes" fakebmagentclient "github.com/cloudfoundry/bosh-micro-cli/deployer/agentclient/fakes" fakebmas "github.com/cloudfoundry/bosh-micro-cli/deployer/applyspec/fakes...
package main import ( "log" "encoding/json" "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "JEEELOOOU") } func main() { http.HandleFunc("/", handler) http.HandleFunc("/planet/yavin", planets) log.Fatal(http.ListenAndServe(":8080", nil)) } typ...
package main func main() { } func findPeakElement(nums []int) int { left, right := 0, len(nums)-1 for left < right { mid := (left + right) >> 1 if nums[mid] < nums[mid+1] { left = mid + 1 } else { right = mid } } return left } func findPeakElement2(nums []int) int { if len(nums) == 1 { return...
package main import ( "bytes" "encoding/json" "fmt" "github.com/pkg/errors" "io/ioutil" "mime/multipart" "strconv" "time" ) var ( logger Logger cfg Config ) func findServer(app string, server string) (int, error) { logger.Infof("\n【获取服务列表】") b := []byte("") query := fmt.Sprintf(`tree_node_id=1%s.5%s`...
package es import ( "syscall" ) // EVERYTHINGUSERAPI BOOL EVERYTHINGAPI Everything_GetMatchPath(void); var dllEverythingGetMatchPath *syscall.LazyProc func EverythingGetMatchPath() (bool, error) { r1, _, err := dllEverythingGetMatchPath.Call() return r1 == 1, checkErr(1, err) } // EVERYTHINGUSERAPI BOOL EVERYTHI...
package mira import "net/http" // Init is used // when we initialize the Reddit instance, // automatically start a goroutine that will // update the token every 45 minutes. The // auto_refresh should not be accessible to // the end user as it is an internal method func Init(c Credentials) (*Reddit, error) { auth, er...
package controllers import ( "database/sql" r "github.com/dancewing/revel" "github.com/dancewing/revel/orm" "github.com/dancewing/yysrevel/app/models" ) type GorpController struct { *r.Controller Txn *orm.Transaction } func (c *GorpController) Begin() r.Result { txn, err := orm.Database().Get().Begin() if e...
package main import ( "fmt" "unicode" "github.com/jnewmano/advent2020/input" "github.com/jnewmano/advent2020/output" ) func main() { sum := parta() fmt.Println(sum) } func parta() interface{} { //input.SetRaw(raw) // var things = input.Load() // var things = input.LoadSliceSliceString("") var things = in...
package series import "strings" func All(n int, s string) []string { if n > len(s) { return nil } if n == 1 { return strings.Split(s,"") } output := []string{} for i := 0 ; i <= len(s)-n; i++ { output = append(output, s[i:i+n]) } return output } func UnsafeFirst(n int, s string) string { return s[:...
package main import ( "fmt" "time" ) func cronjob() { ticker := time.Tick(1 * time.Second) for { select { case <-ticker: totalRead++ if totalRead > 10 { return } fmt.Println("run 1s cronjob:", totalRead) } } }
// Package page has a function to return a list of all butler gen.Pages. package page import ( "path/filepath" "github.com/jwowillo/butler/recipe" "github.com/jwowillo/gen" ) // List of all butler gen.Pages with static files in the web directory and // recipe.Recipes rs to be injected into the static files. // //...
package method_interface import ( "errors" "fmt" "strconv" "time" ) // 通常函数会返回一个error值,调用此函数的代码应该判断error值是否为nil来进行错误处理 func ErrorDemo() { s, error := strconv.Atoi("abc") if error == nil { fmt.Println(s) } else { fmt.Printf("convert error, %v\n", error) } } func Devide(i1, i2 int64) (int64, error) { if i...
package users_test import ( "bytes" "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "testing" "time" . "cinemo.com/shoping-cart/internal/users" mocks "cinemo.com/shoping-cart/mocks/users" "cinemo.com/shoping-cart/pkg/pointer" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/mock" ) ...
package main import ( "fmt" "net/http" "persons.com/api/infrastructure/server" ) func main() { errs := make(chan error, 2) go func() { fmt.Println("Listening on port :5000") errs <- http.ListenAndServe(server.HttpPort(), server.StartRouter()) }() <-errs } //app flow: Domain -> Service -> useCases -> R...
package main func getPivot(slice []int) int { pivot := slice[0] return pivot } func quickSort(slice []int, getPivot int) { if len(slice) < 2 { return } left, right := 0, len(slice)-1 pivot := getPivot slice[pivot], slice[right] = slice[right], slice[pivot] for i := range slice { if slice[i] < slice[righ...
package models //轮播图 type Carousel struct { Id uint `json:"id" gorm:"primaryKey;not null;autoIncrement;comment:'主键'"` Pid uint `json:"pid" gorm:"bigint(20);not null;comment:'商品id'" ` ImgUrl string `json:"img_url" gorm:"type:varchar(200);not null;comment:'图片地址'"` IsPlay bool `json:"is_play" gorm:"type:tinyint(4);d...
package dp type EmployeeSummaryStatus string const ( EmployeeSummaryStatusEmpty EmployeeSummaryStatus = "empty" )
package main import ( "fmt" "strconv" "github.com/freignat91/mlearning/api" "github.com/spf13/cobra" ) // PropagateCmd . var PropagateCmd = &cobra.Command{ Use: "propagate", Short: "push value to input layer value1, value2, ...", Run: func(cmd *cobra.Command, args []string) { if err := mlCli.propagate(cmd...
// ˅ package main // ˄ type IDisplay interface { GetColumns() int GetRows() int GetLineText(row int) string // ˅ // ˄ } // ˅ // ˄