text
stringlengths
11
4.05M
package kafka import ( "KServer/library/kiface/ikafka" "github.com/Shopify/sarama" ) type Consumer struct { sarama.Consumer sarama.ConsumerGroup } func NewIConsumer() ikafka.IConsumer { return &Consumer{} } func (c *Consumer) NewConsumer(addr []string, offset int64) error { config := sarama.NewConfig() conf...
// 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 todo import ( "bufio" "bytes" "fmt" "io/ioutil" "os" "path/filepath" "strconv" ) // List todo file func List() error { fs, err := ioutil.ReadDir(".") if err != nil { return err } for _, f := range fs { if !f.IsDir() && filepath.Ext(f.Name()) == ".td" { fmt.Println(f.Name()) } } return ni...
/* Write a program that can validate a PNG file. Your program should follow the PNG spec and must validate the PNG signature and the 4 critical chunks: IHDR, IDAT, PLTE and IEND. Your program must not validate the contents of ancillary chunks, except for their CRC checksums. Your program must validate the presence of...
package oidc_test import ( "net/url" "sort" "testing" "time" "github.com/ory/fosite" "github.com/ory/fosite/handler/openid" fjwt "github.com/ory/fosite/token/jwt" "github.com/stretchr/testify/assert" "golang.org/x/text/language" "gopkg.in/square/go-jose.v2" "github.com/authelia/authelia/v4/internal/oidc" ...
package retry import "errors" var errMaxRetriesReached = errors.New("maximum retries reached") // MaxRetries is the maximum number of times to retry before stopping. var MaxRetries = 10 // This keeps invoking the function until the first return argument return // false, or no error is returned. func This(fn func(in...
// Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the Lice...
/* Copyright (c) 2014 Ashley Jeffs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, su...
package parser import ( "bufio" "fmt" "io" "unicode" ) type Scanner struct { r *bufio.Reader err error pos int peeked []*Token } func NewScanner(r *bufio.Reader) *Scanner { return &Scanner{r: r} } func (s *Scanner) Read() (rune, bool) { ch, _, err := s.r.ReadRune() if err == io.EOF { return '...
package msaevents import ( "time" ) const ( fallbackLanguage = "EN" ) type EventCreatedUser struct { Event Data CreatedUser `json:"data"` } type CreatedUser struct { AccountEnabled bool `json:"account_enabled"` AccountExpired bool `json:"account_expired"` Authorities []string `json:"authorities"` ...
package problem0230 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func kthSmallest(root *TreeNode, k int) int { //if root == nil || k == 0 { // return -1 //} //var counter int //var stack []*TreeNode //cur := root // return -1 }
package aiven import ( "github.com/aiven/aiven-go-client" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) func datasourceKafkaSchemaConfiguration() *schema.Resource { return &schema.Resource{ Read: datasourceKafkaSchemasConfigurationRead, Schema: resourceSchemaAsDatasourceSchema(aivenKafkaSchemaS...
package object import ( "bytes" "fmt" "hash/fnv" "strings" "github.com/BOBO1997/monkey/ast" ) // ObjectType type represents type of Object type ObjectType string // object name const ( INTEGER_OBJ = "INTEGER" BOOLEAN_OBJ = "BOOLEAN" NULL_OBJ = "NULL" RETURN_VALUE_OBJ = "RETURN_VALUE" ERR...
package pingpong import ( "coms4113/hw5/pkg/base" ) type Server struct { base.CoreNode ServerAttribute } func NewServer(unstable, crazy bool) *Server { return &Server{ ServerAttribute: ServerAttribute{ counter: 0, unstable: unstable, crazy: crazy, }, } } type ServerAttribute struct { counter ...
// Copyright (c) 2016 The Hay Programming Language Authors. // // This project is licensed under the MIT License, // see https://github.com/haylang/hayc/blob/master/LICENSE. // // This script generates the Unicode Character Database header // of the hay_unicode library in lib/unicode. // Usage: go run ucdgen.go $DIR /...
package domain import "os" func getSecretKey() string { secret := os.Getenv("ACCESS_SECRET") if secret == "" { secret = "SECRET_KEY" } return secret }
package game import ( "reflect" "testing" ) func TestRemovePlayer(t *testing.T) { type args struct { players []Player t Player } type testcase struct { name string args args want []Player } var tests []testcase var player1 Player player1.id = 1 player1.role.Name = "villager" var player2 ...
package loader import ( "encoding/json" "errors" "os" "github.com/envkey/go-envkeyfetch/fetch" "github.com/joho/godotenv" ) func Load(shouldCache bool) { godotenv.Load() envkey := os.Getenv("ENVKEY") if envkey == "" { panic(errors.New("missing ENVKEY")) } res, err := fetch.Fetch(envkey, fetch.FetchOpti...
package valid /** * @author 16计算机 Moriaty * @version 1.0 * @copyright :Moriaty 版权所有 © 2020 * @date 2020/4/6 13:12 * @Description TODO * valid 中使用的参数实体 */ type Method uint8 const ( NOTNULL Method = iota EMAIL NUMBER PHONE FILE ) type Param struct { Name string Methods []Method }
package dataloaders import ( "time" ) func newUserByIDs(rep repos) *UserLoader { return NewUserLoader(UserLoaderConfig{ MaxBatch: 100, Wait: 5 * time.Millisecond, Fetch: rep.GetUsersByIDs, }) }
/* * Copyright (c) 2019. Alexey Shtepa <as.shtepa@gmail.com> LICENSE MIT * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. */ package curs import ( "github.com/c2nc/gosys/encodings/ansi" ) func Up(n int) string { return ansi.Co...
package main import ( "fmt" "sync" ) func main() { n := 0 wg := sync.WaitGroup{} num := 3000 wg.Add(num) m := sync.Mutex{} for i := 0; i < num; i++ { go func() { m.Lock() n++ m.Unlock() wg.Done() }() } wg.Wait() fmt.Println(n) }
package ykoath import ( "fmt" ) // Name encapsulates the result of the "LIST" instruction type Name struct { Algorithm Algorithm Type Type Name string } // String returns a string representation of the algorithm func (n *Name) String() string { return fmt.Sprintf("%s (%s %s)", n.Name, n.Algorithm.Stri...
package httputil import ( "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestGetClientIPAddress(t *testing.T) { r1, err := http.NewRequest(http.MethodGet, "https://example.com", nil) require.NoError(t, err) assert.Equal(t, "127.0.0.1", GetClientIPAddress...
package main type command interface { execute(argv []string) error }
package datastore import ( "github.com/jinzhu/gorm" "github.com/taniwhy/mochi-match-rest/domain/models" "github.com/taniwhy/mochi-match-rest/domain/repository" ) type userDatastore struct { db *gorm.DB } // NewUserDatastore : UserPersistenseを生成. func NewUserDatastore(db *gorm.DB) repository.UserRepository { ret...
package main import "fmt" func newPoint(width, height int) point { return point{line: height, col: width} } func (p point) String() string { return fmt.Sprintf("[line: %v / col: %v]", p.line, p.col) }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //452. Minimum Number of Arrows to Burst Balloons //There are a number of spherical balloons spread in two-dimensional space. For each balloon, provide...
package main import ( "fmt" "net/http" "encoding/json" ) type SampleJSONResponse struct { Message string Path string } func getHelloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!, call to endpoint %s!", r.URL.Path[1:]) } func healthCheck(w http.ResponseWriter, r *http.Request)...
package day16 import ( "testing" "github.com/stretchr/testify/require" ) func TestRuleParser(t *testing.T) { input := []string{ "class: 1-3 or 5-7", "row: 6-11 or 33-44", "seat: 13-40 or 45-50", } rules, err := ParseRules(input) require.NoError(t, err) require.Equal(t, []Rule{ {"class", []Range{{1, 3...
package main import ( "fmt" "math/rand" "time" ) func main() { targetNum := 435 s := GetRandomSlice(100000, 10000, targetNum) ch := GetTeacherInstance().StartTask(s, NewGroupLeader(), NewStudent(targetNum), 8, 5.0) fmt.Println(<-ch) } func GetRandomSlice(sliceLen int, randNum int, targetNum int) []int{ tmp :...
package main import "github.com/gin-gonic/gin" func main() { var router = gin.Default() // Akses di localhost:8080/hello router.GET("/hello", func(context *gin.Context) { var fullName string = "Salman" var helloMessage string = "Good morning" context.JSON(200, gin.H{ "result": gin.H{ "fullName": ...
package network import ( "time" ) type TCPOptions struct { TCPAddr string MaxConnNum int PendingWriteNum int32 } type TCPClientOptions struct { ServerAddr string ConnNum int ConnectInterval time.Duration PendingWriteNum int32 AutoReconnect bool }
package controllers import ( "context" "encoding/json" "fmt" "github.com/gorilla/mux" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "net/http" "os" "server/src/dto" "server/src/services/interfaces" "strings" "time" ) const ( contextKeyId = "userId" ) var ( googleOauthConfig = &oauth2.Config{ Red...
package main import "fmt" type ICallService interface { Call() } type IChildCallService interface { doCall() } func (this *abstractCallService) Call() { fmt.Println("parent call this func") this.doCall() } // 抽象类 type abstractCallService struct { IChildCallService } // 具体子类 type ConcreteCallServiceImpl struct...
// Package message contains the structure for basic messages that // are allowed to be sent through the RX and TX channels. package message // Basic implements the message structure that is added to the inbox and // sent to the plugins type Basic struct { ID int `json:"id"` Text string `json:"text"` Fi...
package user import ( "context" "encoding/json" "rest_server/pkg/database" ) type service interface { Get(ctx context.Context, userID int64) (*serviceUser, error) Insert(ctx context.Context, usr *serviceUser) (int64, error) } type Service struct { db database.DataStore } type serviceUser struct { ID in...
/* 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 main import ( "errors" "fmt" "io/ioutil" "reflect" "strconv" "strings" ) type MysqlConfig struct { Address string `ini:"address"` Port int `ini:"address"` Username string `ini:"username"` Password string `ini:"password"` } type RedisConfig struct { host string `ini:"host"` Port in...
package main ///this is a pretext to prac13 where we will use maps import "fmt" func main() { //this is a map without any values. go by default gives maps just as a reference // grades1:= map[string]float32 //this is a map with values. Use keyword make to initialise maps grades := make(map[string]float32) gr...
package customer import ( "github.com/dogmatiq/dogma" "github.com/koden-km/dogma-app-setup/messages/commands" "github.com/koden-km/dogma-app-setup/messages/events" ) // customer is an aggregate root for a customer. type customer struct { // Nickname is the current customer nickname. Nickname string } func (c *c...
package egressipam import ( "context" "errors" "reflect" "strings" "github.com/go-logr/logr" multierror "github.com/hashicorp/go-multierror" ocpnetv1 "github.com/openshift/api/network/v1" "github.com/redhat-cop/egressip-ipam-operator/controllers/egressipam/reconcilecontext" corev1 "k8s.io/api/core/v1" "k8s....
package models type Yaowen struct { Website string `bson:"website"` Title string `bson:"title"` Timer string `bson:"timerid"` ImgShow string `bson:"imgshow"` Contents []string `bson:"contents"` Edit string `bson:"edit"` }
package slack import ( "encoding/json" "net/http" "reflect" "testing" ) func TestRotateTokens(t *testing.T) { http.HandleFunc("/tooling.tokens.rotate", handleRotateToken) expected := getTestTokenResponse() once.Do(startServer) api := New("testing-token", OptionAPIURL("http://"+serverAddr+"/")) tok, err := ...
package main import ( "flag" "fmt" "log" "os" "os/exec" "strings" "time" ) var ( version = 1 color = 0 ) var colors = [...]string{"blue", "green", "pink", "yellow"} func main() { /* This tool needs to be run from the sample-app folder, because that's where the git repo lives. */ branch := "" ...
package rest import ( "net/http" "todo-lists/pkg/common" "github.com/gin-gonic/gin" ) type healthCtrl struct{} func NewHealthCtrl() *healthCtrl { return &healthCtrl{} } func (h healthCtrl) Ping(ctx *gin.Context) { ctx.JSON(http.StatusOK, common.ResponseSuccess("health check")) }
/** * Created with IntelliJ IDEA. * User: jaakkolukkari * Date: 4/5/13 * Time: 2:16 AM * To change this template use File | Settings | File Templates. */ package connection import ( "code.google.com/p/go.net/websocket" "encoding/json" ) type ClientConnection struct { Ws *websocket.Conn Send chan str...
/* Copyright 2019 Dmitry Kolesnikov, 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 l...
package processer import ( "fmt" "github.com/superboy724/wechatmessage/utils" "sort" "strings" ) type RegisterProcesser struct { } func (t *RegisterProcesser) GetRequest(values map[string]string) string { var signature, timestamp, nonce, echostr string if _, ok := values["signature"]; !ok { fmt.Println("erro...
package models // TranslationWelcome struct with basic API informatoin type TranslationWelcome struct { Welcome string `json:"welcome"` Routes map[string]string `json:"routes"` }
package dbConn import ( slog "github.com/DynamoGraph/syslog" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" ) const ( logid = "DBconnect: " ) func logerr(e error, panic_ ...bool) { if len(panic_) > 0 && panic_[0] { slog.Log(logid, e.Err...
// Copyright Amazon.com Inc. or its affiliates. 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://aws.amazon.com/apache2.0/ // // or in the "license" file ...
package main // User represent a user model type User struct { UserID string `gorm:"PRIMARY_KEY" json:"userId"` FirstName string `gorm:"not null" json:"firstName" valid:"required~First Name is required"` LastName string `gorm:"not null" json:"lastName" valid:"required~Last Name is required"` Email string `...
package models import ( "errors" "time" "github.com/lib/pq" ) var ( ErrRsvpClosed = errors.New("RSVPs closed") ErrRsvpMaxAdditionalGuests = errors.New("Additional guest counts is more then allowed") RsvpResponse = map[string]string{"yes": "yes", "no": "no"} RsvpCancelledBy = map[string]string...
package controllers import ( "ibgamemanage/models" "github.com/astaxie/beego" "github.com/spf13/cast" ) type ViewController struct { beego.Controller } func (this *ViewController) Get() { id := cast.ToInt64(this.Ctx.Input.Params()[":PlayerId"]) this.Data["info"] = models.GetPlayerInfo(id) if user, ok := this...
package main import ( "fmt" "github.com/feng/future/design/bridge/bridge" ) func main() { bridge.TestBridge() game := bridge.HandsetGame{} book := bridge.HandsetAddrList{} m := &bridge.HandsetBrandM{} n := &bridge.HandsetBrandN{} f(game, m) f(game, n) f(book, m) f(book, n) fmt.Println("****************...
// Copyright (c) 2021 Alexey Khan // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
package iwebsocket /* 消息管理抽象层 */ type IMsgHandle interface { DoMsgHandler(request IRequest) //马上以非阻塞方式处理消息 AddCustomHandle(handle IHandle) AddHandle(id uint32, handle IHandle) //为消息添加具体的处理逻辑 StartWorkerPool() //启动worker工作池 SendMsgToTaskQueue(request IRequest) //将消息交给TaskQueue,由worker进行处理 }
package launchpad //ColorS represents a color for the "Launchpad S" type ColorS struct { //Red part of color. It can be from 0 to 3! Red int //Green part of color. It can be from 0 to 3! Green int } func (c ColorS) AsBytes() []byte { return []byte{byte(16*c.Green + c.Red + 8 + 4)} } func (l *LaunchpadS) Light(...
package endpoints import ( "encoding/json" "fmt" // "fmt" "net/http" adm "github.com/ebikode/eLearning-core/domain/admin" md "github.com/ebikode/eLearning-core/model" tr "github.com/ebikode/eLearning-core/translation" ut "github.com/ebikode/eLearning-core/utils" ) // CreateAdminEndpoint ... func CreateAdmin...
package cfrida func Frida_file_monitor_new(path string)uintptr{ r,_,_:=frida_file_monitor_new.Call(GoStrToCStr(path)) return r } func Frida_file_monitor_enable_sync(obj uintptr,cancellable uintptr)error{ gerr:=MakeGError() frida_file_monitor_enable_sync.Call(obj,cancellable,gerr.Input()) return gerr.ToError() } ...
package main import ( "fmt" "strings" ) func AboveBelow(nums []int, target int) { above := 0 below := 0 for _, value := range nums { if value > target { above++ }else if value < target{ below++ } } fmt.Printf("Above: %d\nBelow: %d\n",above, below) } func RotateString(s string, rotation int) strin...
package githuberrordialog import ( "fmt" "github.com/gotk3/gotk3/gtk" ) //ShowErrorDialog shows an error dialog to the user, offering him to report the issue on Github. //The error messages will contain information about the users runtime and the error message. func ShowErrorDialog(err error) { ShowErrorDialogWit...
package frida_go import ( "github.com/a97077088/frida-go/cfrida" jsoniter "github.com/json-iterator/go" "reflect" "sync" ) type ScriptOnMessageEventFunc func(sjson jsoniter.Any, data []byte) type ScriptOnDestroyedEventFunc func() type ScriptSignalConnect struct { onMessageSigs sync.Map onDestroyedSigs sync.Map ...
package main import ( "github.com/gin-gonic/gin" "goTodo/controller" "goTodo/initialization" ) func main() { r := gin.Default() controller.LoadRouters(r) ip := initialization.Configuration.Setting.Ip port := initialization.Configuration.Setting.Port if ip == "" { ip = "127.0.0.1" } if port == "" { port ...
// Post build status results to Slack. package main import ( "context" "flag" "log" "github.com/GoogleCloudPlatform/cloud-builders-community/slackbot/slackbot" ) var ( buildId = flag.String("build", "", "Id of monitored Build") webhook = flag.String("webhook", "", "Slack webhook URL") project = f...
package main import ( "bytes" "testing" ) func TestHelp(t *testing.T) { cli := cli{outStream: bytes.NewBufferString(""), errStream: bytes.NewBufferString("")} status := cli.run([]string{"slack-thread-webhook", "--help"}) if status != 0 { t.Errorf("expected: 0, got: %d\n", status) } } func TestVersion(t *test...
package sese import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02000104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.020.001.04 Document"` Message *SecuritiesTransactionCancellationRequestV04 `xml:"SctiesTxCxl...
package calc import "testing" func TestFibonacci(t *testing.T) { exp := []int{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89} seq := Fibonacci(12) for i, sum := range seq { if exp[i] != sum { t.Error("Expected", exp[i], "got", sum) } } }
package main import ( "bishe/spider/config" "bishe/spider/zhipin" "bishe/spider/engine" "strconv" ) // https://www.zhipin.com/c101010100/?query=golang&page=3 // https://www.zhipin.com/c101010100/?query=web&page=1 // https://www.zhipin.com/c101010100 // 输入城市url,职位,生成task列表 func generateTask(cityList []config.CityU...
package main import ( "fmt" "image" "image/color" "io/ioutil" "math" "os" "github.com/faiface/pixel" "github.com/faiface/pixel/text" "github.com/golang/freetype/truetype" ) var ( WinWidth, WinHeight float64 = 768, 384 // WinWidth, WinHeight float64 = 896, 512 // WinWidth, WinHeight float64 = 1536, 768 ...
package main import ( "log" "oliujunk/server/apiserver" "oliujunk/server/commandserver" _ "oliujunk/server/config" _ "oliujunk/server/database" ) func init() { // 日志信息添加文件名行号 log.SetFlags(log.Lshortfile | log.LstdFlags) } func main() { go apiserver.Start() go commandserver.Start() //go communication.Sta...
// Package cache implements middleware for response caching. Request's component used as a key. package cache import ( "bufio" "bytes" "crypto/sha256" "fmt" "io" "io/ioutil" "net/http" "net/http/httputil" "sort" "strings" "github.com/go-pkgz/requester/middleware" ) // Middleware for caching responses. The...
package session import ( "testing" ) func TestJWT(t *testing.T) { jwt := NewJWTManager([]byte("mysecret")) token, err := jwt.Add("myusername") if err != nil { t.Error(err) } username, err := jwt.Get(token) if err != nil { t.Error(err) } if username != "myusername" { t.Error("expected m...
package main import ( "fmt" "github.com/nuczzz/fcache" ) func main() { memCache := fcache.NewMemCache(10, false) memCache.Set("key1", []byte("123456789")) memCache.Set("key2", []byte("0")) memCache.Set("key3", []byte("1")) fmt.Println(memCache.Get("key3")) fmt.Println(memCache.Get("key1")) hit, total := mem...
package main import ( "context" "crypto/tls" "crypto/x509" "flag" "fmt" "io/ioutil" "log" "net" "net/http" "net/http/httputil" "strings" ) func main() { var ( caCertFile, resolve string dumpHeaders bool ) flag.BoolVar(&dumpHeaders, "i", false, "print headers") flag.StringVar(&caCertFile, ...
package fslm import ( "bufio" "reflect" "strings" "testing" ) func Test_lineSplit(t *testing.T) { for _, i := range []struct { Data string Lines []string }{ {"a\nb\n", []string{"a", "b"}}, {"ab\ncd", []string{"ab", "cd"}}, {" \tab\ncd \n", []string{"ab", "cd"}}, {"\nab\n\ncd\n\n", []string{"ab", "c...
package mongodb import ( "context" "log" "time" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) const ( // Timeout operations after N seconds connectTimeout = 5 connectionURI = "mongodb://127.0.0.1:27017" ) // GetConnection returns a mongo connection func GetConnection() (...
package medium import ( "fmt" "testing" ) func Test22(t *testing.T) { n:=3 res:=make([]string,0) fuck22(&res,"",n,n) fmt.Println(res) } func fuck22(res *[]string, tmp string, left,right int) { if left==0&&right==0{ *res = append(*res, tmp) return } if left>0{ tmp = tmp + "(" fuck22(res,tmp,left-1,ri...
package main import ( "gober/gbnet" ) func main(){ s := gbnet.NewServer("caomao") s.Server() }
package http import ( "testing" "github.com/zenazn/goji/web" "net/http/httptest" "net/http" "io/ioutil" ) func ParseResponse(res *http.Response) (string, int) { defer res.Body.Close() contents, err := ioutil.ReadAll(res.Body) if err != nil { panic(err) } return string(c...
package api import ( "context" "errors" "testing" "time" "github.com/brigadecore/brigade/v2/apiserver/internal/meta" "github.com/stretchr/testify/require" "go.mongodb.org/mongo-driver/bson" ) func TestNewjobsService(t *testing.T) { projectsStore := &mockProjectsStore{} eventsStore := &mockEventsStore{} job...
package main import "fmt" type Integer int func (a Integer) Equal(i Integer) bool { return a == i } //func (a *Integer) Equal(i Integer) bool { // return (*a).Equal(i) //} func (a Integer) LessThan(i Integer) bool { return a < i } func (a Integer) MoreThan(i Integer) bool { return a > i } func (a *Integer) In...
package 排序 import "sort" func heightChecker(heights []int) int { sortedHeights := NewSlice(heights) sort.Ints(sortedHeights) countOfMustMovePerson := 0 for i := 0; i < len(heights); i++ { if heights[i] != sortedHeights[i] { countOfMustMovePerson++ } } return countOfMustMovePerson } func NewSlice(oldSlic...
package server import ( "fmt" _ "github.com/gin-contrib/pprof" "github.com/gin-gonic/gin" "github.com/shysa/TP_proxy/app/database" "github.com/shysa/TP_proxy/config" "github.com/shysa/TP_proxy/internal/api" "github.com/shysa/TP_proxy/internal/proxy" "net/http" _ "net/http/pprof" ) func New(cfg *config.Config...
package restapi import ( "encoding/json" "fmt" "net/http" "strconv" "time" "github.com/etf1/kafka-message-scheduler-admin/server/db" "github.com/etf1/kafka-message-scheduler-admin/server/resolver/schedulers" "github.com/etf1/kafka-message-scheduler-admin/server/sort" "github.com/gorilla/mux" "github.com/rs/...
package utils import ( "time" ) // 是否同一天 func SameDay(time1, time2 time.Time) bool { _, offset1 := time1.Zone() _, offset2 := time2.Zone() if offset1 != offset2 { // 必须同时区 return false } if time1.Format("20060102") != time2.Format("20060102") { return false } return true } // 截取日期到天 func Trunc2Date(ts t...
package internal import ( "crypto/sha256" "encoding/binary" "encoding/hex" "fmt" "log" "syscall" "unsafe" "golang.org/x/crypto/ssh" ) type ChannelHandler func(sshConn ssh.Conn, newChannel ssh.NewChannel) type ChannelOpenDirectMsg struct { Raddr string Rport uint32 Laddr string Lport uint32 } func Finge...
package main const FROM_NAME = "crazyoptimist" const FROM_EMAIL = "hey@crazyoptimist.net" const EMAIL_SUBJECT = "Sending with Sendgrid is fun" const EMAIL_TEXT = `Hi, Sending email with Sendgrid is fun, Even in Go`
// 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 main import ( "bufio" "fmt" "math/big" "os" ) //****************************************************************************** // DID NOT SOLVE THIS PROBLEM //****************************************************************************** var MOD = big.NewInt(10e9 + 7) func main() { var r = bufio.NewRea...
package DbBase import ( "xwork/Extend/DB" _ "xwork/Extend/DB/Mysql" "os" "github.com/sirupsen/logrus" ) // 初始化数据库 func InitDb() { //初始化主库 orm := DB.NewOrm("default") if orm == nil { logrus.Error("db: server connection fail name default") os.Exit(0) } } //关闭数据库 func CloseDB() { //关闭主库 DB.CloseDB("defau...
/* Maya numeral system was vigesimal (base 20) and positional: units, tens, hundreds (and so on) were read as descendant progressive powers of 20, instead of 10 like we do with our decimal system. Some examples: - 39 => (1 x 20¹) + (19 x 20º) - 815 => (2 x 20²) + (0 x 20¹) + (15 x 20º) - 16125 => (2 x 20³) + (0 x 20²...
package publisher import ( "context" "github.com/dev4fun007/autobot-common" "github.com/rs/zerolog/log" "strconv" ) const ( QueueBufferSize = 8 DataPublisherTag = "TickerDataPublisher" ) type TickerDataPublisher struct { registry common.WorkerRegistryService // get all active worker data channel to se...
package models import ( "strconv" "time" ) // PlayList -- var ( PlayList map[string]*Track ) func init() { PlayList = make(map[string]*Track) // u := User{"user_11111", "astaxie", "11111", Profile{"male", 20, "Singapore", "astaxie@gmail.com"}} // UserList["user_11111"] = &u } type PL struct { Tracks []string...
package num import ( "fmt" "log" "math/big" "math/rand" "strconv" "strings" "time" ) const DEBUG bool = false //===================================================================================== //===================================================================================== func randBinString(leng...
package logger import ( "fmt" ) // New returns a logger bound to the given name. func New(name string) *Logger { return &Logger{ Name: name, } } // Logger is the unit of the logger package, a smart, pretty-printing gate between // the program and the output stream. type Logger struct { // Name by which the log...
package entity import ( "time" "encoding/json" ) const ( RESOURCE = 0X0001 ) type Log struct { UUID string `json:"agent"` Type int `json:"type"` Message string `json:"message"` Time time.Time `json:"time"` } func NewLog(uuid string, typ int, msg interface{}) Log { bytes, _ := json.Marsh...
package version import ( "fmt" "github.com/spf13/cobra" "runtime" ) var ( AppVersion = "" GitCommit = "" BuildDate = "" GoVersion = "" GoArch = "" ) func init() { if len(AppVersion) == 0 { AppVersion = "dev" } GoVersion = runtime.Version() GoArch = runtime.GOARCH } func NewVersionCommand() *cob...
package main import ( "algorithm/4.敏感词/sensitive" ) func main() { dict := []string{"傻逼", "我们", "我们遇到"} sensitive.Init() for _, v := range dict { sensitive.AppendWord(v, v) } //fmt.Println(sensitive.Sensitive.Root.Node[37027].Node[20123]) content := "那些年我们遇到了好多傻逼." sensitive.Search(content) }