text
stringlengths
11
4.05M
/* Package v1 contains the API definitions for version v1. */ package v1
package main import ( "net/http" "time" "context" "fmt" "net" "encoding/json" ) type key int const userIPKey key = 0 func getIPFromRequest(r *http.Request) (net.IP, error) { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return nil, err } userIP := net.ParseIP(host) if userIP == ni...
package db import ( "context" "database/sql" "encoding/json" "errors" "time" "github.com/google/uuid" "github.com/jinzhu/gorm" ) type File struct { ID string `json:"id",sql:"type:uuid; primary key"` UserID string `json:"user_id",sql:"type:uuid; foreign key"` CreatedAt *time...
package logger import ( "fmt" "chapter7/logger/logger" ) func createLogger() *Logger { l := NewLogger() cw := newConsoleWriter() l.RegisterWriter(cw) // 创建文件写入器 fw := newFileWriter() // 设置文件名称 if err := fw.SetFile("log.log"); err != nil { fmt.Println(err) } l.RegisterWriter(fw) return l } func main() ...
package orderedmap import ( "strconv" "testing" "github.com/stretchr/testify/require" ) type keyable int func (k keyable) Key() string { return strconv.Itoa(int(k)) } func TestAdd(t *testing.T) { om := New() require.NotNil(t, om) err := om.Add(keyable(1)) require.Nil(t, err) require.Equal(t, om.Len(), 1)...
// This file was generated for SObject CollaborationGroupMemberRequest, API Version v43.0 at 2018-07-30 03:47:37.763690275 -0400 EDT m=+24.107201280 package sobjects import ( "fmt" "strings" ) type CollaborationGroupMemberRequest struct { BaseSObject CollaborationGroupId string `force:",omitempty"` CreatedById ...
package terraform_kintone import ( "reflect" "testing" ) func TestFieldSchemaMapper(t *testing.T) { testCases := []struct { title string fieldMap map[string]interface{} shouldBeError bool }{ { title: "SINGLE_LINE_TEXT", fieldMap: map[string]interface{}{ "type": "SINGLE_LINE_TEXT", ...
package main import ( "errors" "flag" "fmt" logs "github.com/sirupsen/logrus" "github.com/yangqinjiang/mycrontab/master/lib" "os" "runtime" "time" ) var ( help bool quiet bool //日志安静模式,不输出info级别的日志 confFile string //配置文件的路径 version bool ) var version_str string = "1.0" //解析命令行参数 //TODO:在 goland...
// Copyright 2019 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 calcstats import "sync" var Cnt int64 var lock = sync.Mutex{} func Incr() { lock.Lock() Cnt++ lock.Unlock() } var Tpose int64 var tlock = sync.Mutex{} func TposeIncr() { tlock.Lock() Tpose++ tlock.Unlock() } var Dots int64 var dlock = sync.Mutex{} func Dot() { dlock.Lock() Dots++ dlock.Unlock() ...
package exportAsciinemaJson import ( "encoding/json" "github.com/stbuehler/go-termrecording/rawrecording" "io" ) func WriteHTML(writer io.Writer, terminalSize rawrecording.TerminalSize, snapshot *Frame, stdoutLocation string, totalTime float64) error { stdoutLoc, err := json.Marshal(stdoutLocation) if err != nil...
package fmm import ( "strings" ) // A small representation of a mod, with an optional version. type ModIdent struct { Name string Version *Version } // Returns a ModIdent parsed from an input string with the format of 'name', // 'name_version', or 'name_version.zip'. func NewModIdent(input string) ModIdent { ...
package Geek import "math" func maximum(a int, b int) int { highestBit := int(uint(a-b) >> 63) return b*(highestBit) + a*(highestBit^1) } func maximum(a int, b int) int { mid := float64(a+b)/2.0 distanceFromMidToAorB := math.Abs(float64(a)-mid) return int(mid+distanceFromMidToAorB) } /* 题目链接: 1. 这题真Geek。 ...
package main import "fmt" func main() { //integers := []int{} integers := make([]int, 0) for i := 0; i < 11; i++ { integers = append(integers, i) } for _, integer := range integers { checkParity(integer) } } func checkParity(i int) { if i & 1 == 1 { fmt.Println(i, "is odd") ...
package sort import ( "fmt" "testing" ) func TestHeapSort(t *testing.T) { heap := &Heap{data: []int{5, 7, 2, 5, 6, 8, 4, 13, 5, 6, 7}} heap.Sort() fmt.Println(heap.data) }
package main import ( "fmt" "net/http" "os" "github.com/jonagold-lab/go-apptweak/apptweak" ) type input struct { appID int markets []string languages []string devices []string topCompetitorIds []int topKeywords []string topNegativeKeywords []strin...
package mpc /* #cgo LDFLAGS: -lm #include "mpc_interface.h" */ import "C" import ( "errors" "unsafe" ) type Ast *C.mpc_ast_t type Error *C.mpc_err_t type Parser *C.mpc_parser_t func New(name string) Parser { cName := C.CString(name) defer C.free(unsafe.Pointer(cName)) return C.mpc_new(cName) } func Cleanup(p1...
package main import ( "errors" "fmt" "os" "path/filepath" "github.com/google/hilbert" "github.com/gitchander/go-lang/cairo" "github.com/gitchander/go-lang/cairo/color" ) type Size struct { Width, Height int } func HilbertCurve(c *cairo.Canvas, n int, size Size) error { s, err := hilbert.New(n) if err !=...
/* Copyright 2011 The Camlistore 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 stateful import ( "context" "fmt" aliceapi "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/alice/api" "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/errors" "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/model" "github.com/y...
package main import ( "fmt" "net/http" "log" "encoding/json" "structure" "os" "io/ioutil" ) var port = "43000" func main() { fmt.Println("Server starting") http.HandleFunc("/", indexPage) //http.Handle("/", http.FileServer(http.Dir("./public"))) fs := http.StripPrefix("/static/", http.FileServer(http.Dir...
package hlog import ( "net/http" "net/http/httputil" "time" "github.com/go-chi/chi/middleware" "github.com/rs/zerolog" "github.com/rs/zerolog/hlog" ) type Middleware func(http.Handler) http.Handler type ChainHandler struct { Middlewares []Middleware } func Chain(m ...Middleware) ChainHandler { return Chain...
package linkedlist import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestNode_String(t *testing.T) { node := &Node{value: 10} assert.Equal(t, fmt.Sprint(node), "10") } func TestList_Append(t *testing.T) { list := &List{} list.Append(1) assert.Equal(t, list.head, list.tail) assert.Len(t...
package common import "github.com/HNB-ECO/HNB-Blockchain/HNB/common" type NonceSet struct { NI []*NonceItem } type NonceItem struct { Key common.Address Nonce uint64 } type NonceStore interface { GetNonce(address common.Address) (uint64, error) SetNonce(address common.Address, nonce uint64) error }
/* Tencent is pleased to support the open source community by making Basic Service Configuration Platform available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain...
package main import ( "fmt" "image" "image/png" "math" "math/rand" "os" "runtime" "sync" "time" ) const ( WIDTH = 2560 HEIGHT = 2560 ) var SCENE scene type ray struct { origin, direction Vector } type sphere struct { origin Vector radius float64 color color } type scene struct { spheres []sphere...
package main import "fmt" //append() 为切片追加元素 func main() { s1 := []int{1, 2, 3} fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n", s1, len(s1), cap(s1)) //s1[3] = 4 //错误写法, 会导致编译错误:索引越界 //调用append函数必须用原来的切片变量接收返回值 s1 = append(s1, 4) fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n", s1, len(s1), cap(s1)) s2 := []int{5, 6,...
// Copyright 2019 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" ) func main() { x := []int{3, 6, 9, 12, 15, 18} fmt.Println(x[5]) fmt.Println(x) fmt.Println(x[:]) fmt.Println(x[1:]) fmt.Println(x[:5]) fmt.Println(x[3:4]) fmt.Println("Here is for loop") for i, v := range x { fmt.Println(i, v) //Alternative method } fmt.Println("The below...
package user_action import ( "encoding/json" "ibgame/logs" "ibgame/models/user_model" "io/ioutil" "net/http" "strings" ) // Register 注册action func Register(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() data, err := ioutil.ReadAll(r.Body) if err != nil { logs.Error.Println("ioutil.ReadAll ...
package aes import ( "crypto/aes" "crypto/cipher" "crypto/hmac" "errors" "hash" "io" ) func CTRStream(src io.Reader, dst io.Writer, key, iv []byte) error { block, err := aes.NewCipher(key) if err != nil { return err } stream := cipher.NewCTR(block, iv) if _, err = io.CopyBuffer(dst, cipher.StreamReader{S...
package fixtures import "time" var newYork, _ = time.LoadLocation("America/New_York")
package src import ( "github.com/ghodss/yaml" appsv1 "k8s.io/api/apps/v1" "encoding/json" "io/ioutil" "sync" "path" "log" "strings" "time" "fmt" "os" "os/user" "codeci/pkg/k8s" "runtime" "bytes" "errors" "os/exec" "path/filepath" ) //get resource yaml func GetResourceYaml(filePath string) []byte { ...
package loader import ( "io/ioutil" "os" "testing" "github.com/devspace-cloud/devspace/pkg/devspace/config/generated" fakegenerated "github.com/devspace-cloud/devspace/pkg/devspace/config/generated/testing" "github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest" "github.com/devspace-cloud/devs...
package Base58 import ( "testing" ) const ( vv = "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM" ) var ii = []byte("00010966776006953d5567439e5e39f86a0d273beed61967f6") // BenchmarkDecodeBase58 show benchmark test func BenchmarkDecodeBase58(b *testing.B) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { Decod...
package main import "fmt" func testFail() { shouldReturnError := func(v ...interface{}) { fmt.Println(v) } shouldReturnError(1, "v", make(chan interface{})) }
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "os" "strconv" "time" "github.com/aymerick/raymond" "github.com/nektro/go-util/util" discord "github.com/nektro/go.discord" etc "github.com/nektro/go.etc" oauth2 "github.com/nektro/go.oauth2" "github.com/rakyll/statik/fs" "git...
package collectors import ( "encoding/json" "errors" "fmt" "log" "strings" "time" cclog "github.com/ClusterCockpit/cc-metric-collector/pkg/ccLogger" lp "github.com/ClusterCockpit/cc-metric-collector/pkg/ccMetric" "github.com/NVIDIA/go-nvml/pkg/nvml" ) type NvidiaCollectorConfig struct { ExcludeMetrics ...
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package engine import ( "testing" "github.com/Azure/go-autorest/autorest/to" "github.com/google/go-cmp/cmp" "github.com/Azure/aks-engine/pkg/api" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/c...
/* 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 writing, so...
package gcp import ( "testing" "github.com/stretchr/testify/assert" ) func Test_policyMemberToEmail(t *testing.T) { cases := []struct { member string email string }{{ member: "serviceAccount:operator@project", email: "operator@project", }, { member: "deleted:serviceAccount:operator@project", email...
package chain import ( "context" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/core/types" "github.com/google/uuid" "github.com/sanguohot/medichain/contr...
package postgis import ( "errors" "fmt" "strings" "database/sql" gostErrors "github.com/geodan/gost/src/errors" "github.com/geodan/gost/src/sensorthings/entities" "github.com/geodan/gost/src/sensorthings/odata" ) func observationParamFactory(values map[string]interface{}) (entities.Entity, error) { o := &en...
package defaults import ( "github.com/openshift/installer/pkg/types/nutanix" ) // SetPlatformDefaults sets the defaults for the platform. func SetPlatformDefaults(p *nutanix.Platform) {}
package targzhelper import ( "archive/tar" "compress/gzip" "fmt" "io" "os" "path/filepath" "strings" ) func extractFile(header tar.Header, reader io.Reader, path string) (rerr error) { fileName := filepath.Join(path, header.Name) file, ferr := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, header.FileInfo().Mo...
package main import ( "fmt" ) const ( lseed = 516 rseed = 190 lfactor = 16807 rfactor = 48271 divisor = 2147483647 maxvals = 5000000 bitmask = 65535 lmultiple = 4 rmultiple = 8 ) func genNext(val int, factor int, multiple int) int { retVal := (val * factor) % divisor for (retVal % multiple) != 0 { retV...
package main import ( "errors" "flag" "github.com/guoyk93/deployer/pkg/tempfile" "log" "os" "path" "strings" ) var ( opts Options optOnlyBuild bool optOnlyDeploy bool optSkipDeploy bool optKeepGenerated bool ) func sanitize(strs ...*string) { for _, str := range strs { val := strings.ReplaceAll( ...
package factorial import "fmt" func Factorial(n uint) uint { if n == 1 || n == 0 { return 1 } return n * Factorial(n-1) }
package main import ( "bytes" "context" "fmt" "log" "os" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) // CustomEvent for lambda type CustomEvent struct { ID string Name string } var ( awsRegio...
package center import ( "time" "github.com/golang/glog" "github.com/gorilla/websocket" ) // implements Ws type connection struct { *websocket.Conn send chan []byte central Central quit chan struct{} } func NewConn(central Central, ws *websocket.Conn, quit chan struct{}) Ws { return &connection{ Conn...
package pie_test import ( "github.com/elliotchance/pie/v2" "github.com/stretchr/testify/assert" "math/rand" "testing" ) var randomTests = []struct { ss []float64 expected float64 source rand.Source }{ { nil, 0.0, nil, }, { nil, 0.0, rand.NewSource(0), }, { []float64{}, 0.0, rand....
package parser import ( "cpl/variable" "strconv" "strings" "errors" "fmt" "os" "bufio" ) type OpType int const ( NULL OpType = iota + 1 ADD SUB MUL DIV MOD EXP FAC AND OR NOT EQU GT LT GTE LTE NEQ EQU2 GT2 LT2 GTE4 LTE4 ) func AlgebraicParser(expression stri...
package main import ( "fmt" ) // 定义一个用户接口 type IUser interface { // 定义say方法 say() } // 定义一个人接口 type IPersoner interface { // 通过匿名字段方式继承IUser IUser // 定义run方法 run() } // 定义学生结构体 type Student struct { id int name string } // 给学生结构体绑定say方法 func (s *Student) say() { fmt.Printf("Student %s say...\n", s.nam...
package parser type Names struct { nameToID map[string]int names []string } func (n *Names) IDFromName(name string) int { if n.nameToID == nil { n.nameToID = make(map[string]int, 100) } id, ok := n.nameToID[name] if !ok { n.names = append(n.names, name) id = len(n.names) - 1 n.nameToID[name] = id } ...
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-08-16 10:31 * Description: *****************************************************************/ package pdl import ( "github.com/apache/thrift/lib/go/t...
package bit_map import ( "fmt" "math" "strings" ) const BitSize = 8 // 误判率大约在 (万分之5)~(万分之7) type BitMap struct { bitArray []byte Size uint32 } func (bm *BitMap) Init() { if bm.Size > 1<<32-1 { panic("bit map Size over flow") } var r uint32 if bm.Size <= 1 { r = 1 } else { r = uint32(math.Ceil(fl...
package group import ( "github.com/gookit/gcli/v3" "github.com/ovrclk/akash/x/deployment/types" "github.com/ovrclk/akcmd/client" "github.com/ovrclk/akcmd/flags" ) func TxCmd() *gcli.Command { cmd := &gcli.Command{ Name: "group", Desc: "Modify a Deployment's specific Group", Func: func(cmd *gcli.Command, ar...
package query import ( "github.com/garyburd/redigo/redis" "github.com/mezis/klask/index" "github.com/mezis/klask/util/tempkey" ) type Context interface { Conn() redis.Conn Keys() tempkey.Keys Idx() index.Index } type context_t struct { idx index.Index keys tempkey.Keys } func newContext(idx index.Index) *c...
package main import ( "fmt" "log" "net/http" "net/http/httptest" "net/http/httputil" ) func main() { const body = "Go is a general-purpose language designed with systems programming in mind." ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Date", "Wed,...
package models import ( "database/sql" "encoding/json" ) type NullString struct { sql.NullString } func (r NullString) MarshalJSON() ([]byte, error) { if r.Valid { return json.Marshal(r.String) } return json.Marshal(nil) }
package twosum func twoSum(nums []int, target int) []int { mapDiff := make(map[int]int) for i, value := range nums { if j, ok := mapDiff[value]; ok { return []int{j, i} } diff := target - value mapDiff[diff] = i } return nil }
package isogram import ( "strings" ) // IsIsogram takes a string and returns true if there are no duplicated // characters excluding "-" and " ". func IsIsogram(word string) bool { word = strings.ToLower(word) seen := 0 for _, c := range word { switch string(c) { case "-": continue case " ": continue...
package main import ( "fmt" ) // 145. 二叉树的后序遍历 // https://leetcode-cn.com/problems/binary-tree-postorder-traversal/ func main() { tree := &TreeNode{ Val: 1, Right: &TreeNode{ Val: 2, Left: &TreeNode{ Val: 3, }, }, } fmt.Println(postorderTraversal(tree)) fmt.Println(postorderTraversal2(tree)) ...
package main func sortArray(nums []int) []int { quickSort(0, len(nums)-1, nums) return nums } func partition(i, j int, nums []int) int { key := nums[i] left := i for i < j { for i < j && nums[j] > key { j-- } for i < j && nums[i] <= key { i++ } if i < j { nums[i], nums[j] = nums[j], nums[i] ...
package main import "fmt" func main() { name := "Eko" switch name { case "Eko": fmt.Println("Hello Eko") case "Joko": fmt.Println("Hello Joko") default: fmt.Println("Salam kenal") } // switch short statement switch length := len(name); length > 5 { case true: fmt.Println("Nama terlalu panjang") ca...
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package dcp // Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. // For example, the input [3, 4, -1, 1] should give 2. ...
package rest import ( "errors" "net/http" jwt "github.com/dgrijalva/jwt-go" r "github.com/jinmukeji/jiujiantang-services/pkg/rest" jwtmiddleware "github.com/jinmukeji/jiujiantang-services/pkg/rest/jwt" "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/context" ) // NewApp 创建一个实现了 http.Handler 接口的应用程序...
package controller import ( "fmt" ) type IndexController struct { } func (i *IndexController) Welcome() { view = "auth_view" fmt.Println("欢迎来到sixedu") } func (i *IndexController) Index() { view = "auth_view" fmt.Println("进入到首页") }
// 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 exasol import ( "github.com/stretchr/testify/suite" "testing" ) type WebsocketTestSuite struct { suite.Suite } func TestWebsocketSuite(t *testing.T) { suite.Run(t, new(WebsocketTestSuite)) } func (suite *WebsocketTestSuite) TestSingleHostResolve() { config := config{Host: "localhost"} connection := co...
package upload import ( "MI/pkg/setting" "context" "github.com/qiniu/go-sdk/v7/auth/qbox" "github.com/qiniu/go-sdk/v7/storage" "mime/multipart" ) func UploadFile(file multipart.File,fileSize int64,fileName string)(string,error){ putPolicy := storage.PutPolicy{ Scope: setting.QiNiuYunConf.Bucket, } mac := qb...
package logger import ( "log" "os" "github.com/etf1/kafka-transformer/pkg/logger" ) // Stdout system out implementation of Logger.Log interface type Stdout struct { out *log.Logger err *log.Logger } // StdoutLogger is the default implementation of Log stdout/stderr func StdoutLogger() logger.Log { return Stdo...
package golibs const R_OK int = 1 const R_ERR int = 0
package main import ( "flag" "fmt" "image" "image/color" "image/gif" "log" "math" "os" ) var ( frames = flag.Int("frames", 120, "number of frames") width = flag.Int("width", 512, "window width") height = flag.Int("height", 512, "window height") delay = flag.Int("delay", 10, "delay between frames in 10ms...
package httpclient import ( "fmt" "reflect" "strings" "github.com/nelsam/requests/options" ) var ( registeredOptions = map[string]InputOptionFunc{ "required": InputOptionFunc(options.Required), "default": InputOptionFunc(options.Default), "immutable": InputOptionFunc(options.Immutable), } optionDefa...
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applica...
package crypto import "testing" func TestMd5File(t *testing.T) { md5 := Md5String([]byte("aaa")) if len(md5) != 32 { t.Error(md5) } t.Log(md5) } func TestMd5FileByPath(t *testing.T) { md5, err := Md5FileByPath("./md5") if err != nil { t.Error(err) } t.Log(md5) }
package main import ( "fmt" "strconv" ) func longDiv(a int, b int, max int) (string,int) { remMap := make(map[int]int) resStr := "" hasDot := false p := 0 for x := 0; x <= max; x++ { first := true for ; b > a ; a = a * 10 { if !hasDot { hasDot = true if ...
package rating // GetRequest request for getting a rating type GetRequest struct { ID string } // GetResponse response after getting a rating type GetResponse struct { ID string `json:"id,omitempty"` Stars string `json:"stars,omitempty"` } // // httpRequester makes it possible to mock or intercept http request...
// 8. Detect AES in ECB mode package main import ( "bufio" "crypto/aes" "encoding/hex" "fmt" "io" "os" ) func main() { files := os.Args[1:] if len(files) == 0 { if err := detect(os.Stdin); err != nil { fmt.Fprintln(os.Stderr, err) } return } for _, file := range files { f, err := os.Open(file) ...
package main import ( "archive/tar" "bufio" "bytes" "encoding/json" "fmt" "io" "io/ioutil" "log" "net" "net/http" "os" "os/exec" "path/filepath" "regexp" "strings" "time" "github.com/boot2docker/boot2docker-cli/driver" ) // Try if addr tcp://addr is readable for n times at wait interval. func read(a...
package main import ( "encoding/json" "fmt" "github/gorilla/mux" "io/ioutil" "log" "net/http" "time" ) const month = time.Hour * 24 * 30 var topLangs map[string][]string func home(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, topLangs) } func getRepos() error { topLangs = make(map[string][]str...
package main import "fmt" //先定义接口 一般以er结尾 根据接口实现功能 type Humaner2 interface { //子集 //方法 方法的声明 sayhi() } type Personer interface { //超集 Humaner2 //继承sayhi() sing(string) } type student13 struct { name string age int score int } func (s *student13)sayhi() { fmt.Printf("大家好,我是%s,今年%d岁,我的成绩%d分\n",...
package seev import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document03800204 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.038.002.04 Document"` Message *CorporateActionNarrative002V04 `xml:"CorpActnNrrtv"` } func (d *Document0...
package basicarray import "fmt" func init() { fmt.Println("package basicarray init()") } /* /* function prints incoming slice */ func PrintSlice(slice []string, suffix string) { for i := range slice { slice[i] = slice[i] + suffix } fmt.Println(slice) } /* /* function prints length and capacity of incoming arr...
package tasks import ( "fmt" "strconv" ) type TaskToggler interface { ToggleTask(int, bool) error } // ToggleTasks sets one or several task to the value passed as done func ToggleTasks(store TaskToggler, args []string, done bool) { for _, arg := range args { id, err := strconv.Atoi(arg) if err != nil { fm...
package httpclient import ( "fmt" "strings" ) // UnusedFields is an error type for input values that were not used // in a request. type UnusedFields struct { params map[string]interface{} matched set missing []string } // HasMissing returns whether or not this error knows about any input // values that were n...
/* For license and copyright information please see LEGAL file in repository */ package approuter // AuthorizeWhich will authorize by ConnectionData.AccessControl.Which func (sd *StreamData) AuthorizeWhich() { // Check requested user have enough access var notAuthorize bool for _, service := range sd.ConnectionDat...
package leetcode import "sort" func FourSum(nums []int, target int) [][]int { var fourSum [][]int sort.Ints(nums) var len = len(nums) if len <= 3 { return nil } for i := 0; i < len; i++ { if i > 0 && nums[i] == nums[i-1] { continue } var target1 = target - nums[i] for j := i + 1; j < len; j++ { ...
package _ import ( "bufio" "flag" "io/ioutil" "log" "os" ) func main() { // THE FLAGS FOR CRACKING var intervalFlag = flag.Int("i", 1, "the inteval to go at") var offsetFlag = flag.Int("o", 1024, "the offset to go at") var wrapperFlag = flag.String("w", "", "the wrapper to read from") var modeFlag = flag.S...
package acrel import ( "fmt" "testing" ) func TestFrame_Copy(t *testing.T) { a := &Frame{ Function: 0x84, Data: nil, } fmt.Println(a) b := a.Copy() fmt.Println(b) b.Function = 0x94 // a、b是独立的两块内存 fmt.Println(b) fmt.Println(a) }
package cache const ( /* *岗位 */ KeyUserJob = "job::user:" /* *角色 */ KeyUserRole = "role::user:" /* *菜单 */ KeyUserMenu = "menu::user:" /* *部门 */ KeyUserDept = "dept::user:" /* *数据 */ KeyUserDataScope = "data::user:" )
package main import ( "fmt" ) // https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/ // 230. 二叉搜索树中第K小的元素 | Kth Smallest Element in a BST //------------------------------------------------------------------------------ func kthSmallest(root *TreeNode, k int) int { if root == nil { return 0 } res :=...
package optionsgen_test import ( "testing" "time" testcase "github.com/kazhuravlev/options-gen/options-gen/testdata/case-12-defaults-tag-02" "github.com/stretchr/testify/assert" ) func TestDefaultValues(t *testing.T) { cases := []struct { opts testcase.Options wantError bool }{ { opts: testc...
package ratelimiter import ( "errors" "sync" "time" "code.cloudfoundry.org/lager" "github.com/juju/ratelimit" ) type Store interface { Increment(string) (int, error) Stats() map[string]int } type InMemoryStore struct { bucketCapacity int maxAmount int validDuration time.Duration expi...
package loaders import ( "context" "time" "github.com/syncromatics/kafmesh/internal/graph/loaders/generated" "github.com/syncromatics/kafmesh/internal/graph/model" "github.com/syncromatics/kafmesh/internal/graph/resolvers" "github.com/pkg/errors" ) //go:generate mockgen -source=./processorInputs.go -destinati...
package types /* Data Structure key : address value: map[time.Time]Data */ type Data struct { raw_data []byte meta []byte }
package channels import ( "math/rand" "time" ) func ping(pings chan<- int) { for { pings <- rand.Int() time.Sleep(1 * time.Second) } } func pong(pings <-chan int) { for { msg := <-pings time.Sleep(1 * time.Second) println(msg) } } func TestChannels() { pings := make(chan int, 1) go ping(pings) ...
package cain import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01300101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:cain.013.001.01 Document"` Message *AcquirerRejection `xml:"AcqrrRjctn"` } func (d *Document01300101) AddMessage() *Acquir...