text
stringlengths
11
4.05M
package main import ( "bufio" "fmt" "io/ioutil" "os" "strings" ) type Question struct { question string answer string } func main() { var score int = 0 questions := getFileDetials() for i := 0; i < len(questions); i++ { fmt.Print("\n", questions[i].question) ans := string(questions[i].answer) ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/5/31 7:19 下午 # @File : decode_string.go # @Description : # @Attention : */ package v2 import ( "strconv" "strings" ) func decodeString(s string) string { if len(s) == 0 { return "" } stack := make([]byte, 0) for index, _ := range s { if s[index] !=...
package goSolution func isTargetValid(target []int) int { for _, v := range target { if v < 1 { return -1 } if v != 1 { return 1 } } return 0 } func isPossible(target []int) bool { n := len(target) if n == 0 { return false } var t int for t = isTargetValid(target); t > 0; t = isTargetValid...
package options import "testing" func Test_RepoOverride(t *testing.T) { opts := GlobalOptions{ owner: "heaths", repo: "gh-label", } if owner, repo := opts.Repo(); owner != "heaths" || repo != "gh-label" { t.Errorf(`RepoOverride() = (%s, %s); want: ("heaths", "gh-label")`, owner, repo) } } func Test_parse...
package envoyconfig import ( "context" "encoding/base64" "os" "path/filepath" "testing" "time" envoy_config_cluster_v3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/volatiletech/null/v9" "google.golang...
package message import ( "bytes" "github.com/stretchr/testify/assert" "testing" ) func Test_Checksum(t *testing.T) { r := bytes.NewBufferString("foobar") c, err := CalculateChecksums(r) assert.NoError(t, err) assert.Equal(t, "a06e327ea7388c18e4740e350ed4e60f2e04fc41", c["ripemd160"]) assert.Equal(t, "c3ab8ff...
package main import ( . "codewizards" ) type MyStrategy struct{} func New() Strategy { return &MyStrategy{} } func (s *MyStrategy) Move(me *Wizard, world *World, game *Game, move *Move) { // put your code here }
package main import ( "fmt" "sync" ) func main() { rw := sync.RWMutex{} rw.RLock() rw.RLock() rw.RUnlock() rw.Lock() fmt.Println(2222) }
/* Inspired by this video by Ben Eater. This challenge forms a pair with Decode USB packets. The USB 2.0 protocol uses, at a low level, a line code called non-return-to-zero encoding (specifically, a variant called NRZI), in which a stream of bits is encoded into a stream of two electrical level states J and K. Encod...
package embedded import ( "context" "crypto/tls" "crypto/x509" "fmt" "io" "io/ioutil" "net/http" "os" "strings" "time" "github.com/coreos/etcd/etcdmain" "github.com/pkg/errors" "github.com/rancher/rancher/pkg/hyperkube" "github.com/rancher/rancher/pkg/k8scheck" "github.com/rancher/rancher/pkg/librke" ...
/* Copyright © 2019 Cabins <kong_lingcun@163.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 w...
package protocol import () type ServerRestartPacket struct { Tid uint64 Serial uint16 } func (p *ServerRestartPacket) Serialize() []byte { return nil } func ParseServerRestart(buffer []byte) *ServerRestartPacket { _, _, _, tid, serial := ParseHeader(buffer) return &ServerRestartPacket{ Tid: tid, Ser...
package main import "fmt" func main() { class := map[int][]string{ 10: {"abc", "xyz", "qwer"}, } fmt.Println(class[10]) }
package msp import ( "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp" "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/secp256k1" "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/sha3" "github.com/HNB-ECO/HNB-Blockchain/HNB/bccsp/sw" "github.com/HNB-ECO/HNB-Blockchain/HNB/common" "crypto/ecdsa" "crypto/elliptic" "encodin...
package main import ( "net" "fmt" "encoding/gob" ) func main() { go server() go client() var ip int fmt.Scanln(&ip) } func server(){ l,err :=net.Listen("tcp",":9999") //listen on port if err != nil{ fmt.Println(err) return } for{ c,err :=l.Accept() if err!= nil{ fmt.Println(err) continue...
package main import ( "github.com/micro/go-micro" "github.com/micro/go-plugins/registry/etcdv3" "github.com/odom11/playground_micro/api" "github.com/odom11/playground_micro/toc" ) func main() { registry := etcdv3.NewRegistry() service := micro.NewService( micro.Name("tic"), micro.Version("latest"), micro...
package global import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/jackc/pgx/v4/pgxpool" "log" "os" ) var Dbpool *pgxpool.Pool var Sess *session.Session var Uploader *s3manager.Uploader var ( InfoLogger *log.Logger WarningLogger *log.Logger ErrorLo...
//divide-and-conquer 利用分治法查找最大,最小值 package main import "fmt" func GetMaxAndMin(arr []int) (max,min int) { if arr == nil { return 0,0 } len := len(arr) max = arr[0] min = arr[0] for i:=0;i<len-1;i=i+2 { if arr[i] > arr[i+1] { tmp := arr[i] arr[i] = arr[i+1] arr[i+1] = tmp } } for i:=2; i<len ...
// Copyright (c) 2020 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package wallet import ( "testing" "github.com/btcsuite/btcd/btcutil" "github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcwallet...
package logic import ( "unsafe" "hub000.xindong.com/rookie/rookie-framework/log" ) //TODO:This is just a demo, need to be modified in the future. //LogicMemoryDecorator is one decorator that can log the size of the input. type MemoryWrapper struct { block LogicBlock } //NewLogicMemoryDecorator will create a new ...
package server type CreateProductFormRequest struct { Name string `json:"name"` Price int `json:"price"` ImageURL string `json:"imageurl"` } func (r CreateProductFormRequest) Validate() map[string]interface{} { errs := make(map[string]interface{}) nameErrs := []string{} if r.Name == "" { nameErrs =...
package bridge import ( "errors" "flag" "fmt" log "github.com/sirupsen/logrus" "net/http" "net/http/httputil" "net/url" "os" "time" "github.com/elazarl/go-bindata-assetfs" "github.com/facebookgo/inject" "github.com/stellar/gateway/bridge/config" "github.com/stellar/gateway/bridge/gui" "github.com/stella...
package core import ( "context" "reflect" ) func (s *WSServer) Handle(name string, handler interface{}) { t := reflect.TypeOf(handler) if t.Kind() != reflect.Func { panic("error: " + name + " method type not func.") } if t.NumIn() != 2 || t.NumOut() != 2 { panic("error: handler wants 2 input and 2 output p...
/* Copyright 2022 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,...
package Logger import ( "fmt" "os" "time" ) // Info appends provided log line to a txt file func Info(line string) { var time string = time.Now().Format(time.RFC850) var formattedLine string = "[" + time + "] " + line fmt.Println(formattedLine) appendToFile(formattedLine) } // appendToFile appends provided l...
/* Copyright 2019 The MayaData 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, s...
/* 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, ...
// Copyright (C) 2013-2018 by Maxim Bublis <b@codemonkey.ru> // // 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...
package dir import ( "fmt" "strings" "time" . "github.com/Pyorot/streams/src/utils" "github.com/bwmarrin/discordgo" ) var managed bool // manage dir (vs treating it as read-only) var gameName string // (if managed) param for onUpdate var serverID string ...
package parser import ( "testing" ) func Test_ParseMysqlUrl(t *testing.T) { mysqlUrl := "mysql://b08738ff9fff5e:e79a1d81@us-cdbr-iron-east-01.cleardb.net/heroku_e16926abf051efd?reconnect=true" if r, e := ParseMysqlUrl(mysqlUrl); e != nil { t.Error(e) } else { t.Log("first test passed") t.Log(r) } }
package main import ( "fmt" "net/http" "io/ioutil" "strings" "github.com/Shopify/sarama" "log" ) func handler(writer http.ResponseWriter, request *http.Request) { tenant := tenant(&request.Header) path := strings.Split(request.URL.Path, "/") defer request.Body.Close() body, _ := ioutil.ReadAll(request.Bod...
package payments import ( "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "github.com/gorilla/mux" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/loubard/sfapi/models" "github.com/loubard/sfapi/sql" "github.com/stretchr/testify/assert" ) fun...
package myheap type MaxHeap struct { data []int // 数组存储堆 count int // 当前堆容量 capacity int //初始化容量 } // 构造函数, 构造一个空堆, 可容纳capacity个元素 func NewMaxHeap(cap int) *MaxHeap { heap := new(MaxHeap) heap.data = make([]int, cap+1) //跳过0从1开始 heap.count = 0 heap.capacity = cap return heap } // Heapify:给定一个数组排列成...
// Copyright 2020-2021 Buf Technologies, 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...
package main import ( "fmt" "sync" ) //How to use Mutex var counter int = 0 func add(a, b int, lock *sync.RWMutex) { c := a + b lock.Lock() counter ++ fmt.Printf("%d : %d + %d = %d\n", counter, a, b, c) lock.Unlock() } func main() { lock := &sync.RWMutex{} for i:=0; i<10; i++ { go add(1,i,lock) } for ...
package main import ( "github.com/jpillora/opts" "github.com/wxio/tron-go/cmd" "github.com/wxio/tron-go/tools" ) var ( Version string Date string Commit string ) type root struct{} type build struct{} type adl struct{} func main() { r := root{} opts.New(&r).Name("tron-go"). EmbedGlobalFlagSet(). Com...
package git import ( "errors" "io" "path" "reflect" "strings" "testing" "github.com/google/go-cmp/cmp" ) func TestCopyService(t *testing.T) { s := &mockSource{localPath: "/tmp/testing"} files := []string{"service-a/my-system/my-file.yaml", "service-a/my-system/this-file.yaml"} for _, f := range files { s...
package rest import ( "github.com/golang/protobuf/ptypes" "github.com/jinmukeji/jiujiantang-services/pkg/rest" analysispb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/analysis/v1" "github.com/kataras/iris/v12" ) func (h *v2Handler) GetV2AnalyzeReportByRecordID(ctx iris.Context) { recordID, _ := ctx....
package socketio import ( "sync" ) // "log" // "runtime/debug" // BroadcastAdaptor is the adaptor to handle broadcasts. type BroadcastAdaptor interface { // Join causes the socket to join a room. Join(room string, socket Socket) error // Leave causes the socket to leave a room. Leave(room string, socket Socke...
package main import ( "fmt" ) /* Notes on Interfaces: type bot interface { // ^interface name getGreeting (string, int) (string, error) // ^function name ^list of args ^list of return types } */ type bot interface { getGreeting() string } // englishBot and spanishBot got the bot interace implic...
package gocpy //go:generate go run script/variadic.go /* #include <stdio.h> #include "Python.h"*/ import "C" //togo converts a *C.PyObject to a *PyObject func togo(cobject *C.PyObject) *PyObject { return (*PyObject)(cobject) } func toc(object *PyObject) *C.PyObject { return (*C.PyObject)(object) } /*Use this fo...
package graphql_test import ( "testing" "github.com/graphql-go/graphql" "github.com/graphql-go/graphql/gqlerrors" "github.com/graphql-go/graphql/testutil" ) func TestValidate_NoCircularFragmentSpreads_SingleReferenceIsValid(t *testing.T) { testutil.ExpectPassesRule(t, graphql.NoFragmentCyclesRule, ` fragm...
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later package controller import ( "fmt" "log" "time" "github.com/swinslow/peridot-core/internal/jobcontroller" "github.com/swinslow/peridot-core/pkg/agent" pbs "github.com/swinslow/peridot-core/pkg/status" ) // runScheduler is the main "decider" within the ...
package urlshort import ( "net/http" "gopkg.in/yaml.v2" ) type option struct { Path string URL string } type Options []option func YAMLHandler(yml []byte, fallback http.Handler) (http.HandlerFunc, error) { options := Options{} err := yaml.Unmarshal(yml, &options) if err != nil { return fallback.ServeHTT...
package main import ( "fmt" "reflect" ) func main() { var stu Student ref := reflect.ValueOf(stu) f := ref.MethodByName("SayHello") f.Call([]reflect.Value{}) } type Student struct { } func (stu Student) SayHello() { fmt.Println("hello workd") }
package main import ( "encoding/json" "io" "errors" "fmt" ) type whData struct { data map[string]*json.RawMessage } type label struct { Id int `json:"id,int"` Title string `json:"title"` // ProjectId int `json:"project_id,int"` // Description string `json:"description"` // Type string `json:"type"` // can b...
package 二叉树 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func buildTree(preorder []int, inorder []int) *TreeNode { // 1. 空返回。 if len(preorder) == 0 { return nil } // 2. 获取根节点在中序遍历序列的 index。 rootNum := preorder[0] rootIndexInInorderSeq := 0 for index, num := range inorder { if num ...
package model import ( "posthis/database" ) type LikeModel struct { Model } func (LikeModel) GetLikes(id uint) ([]*Like, error) { post := &Post{} if err := database.DB.Preload("Likes").First(&post, id).Error; err != nil { return nil, err } return post.Likes, nil } func (lm LikeModel) CreateLike(userId, p...
package main import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/lcd" _ "github.com/cosmos/cosmos-sdk/client/lcd/statik" "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/doc...
package pubsub import ( "context" "fmt" "math/rand" "time" pb "gx/ipfs/QmWL6MKfes1HuSiRUNzGmwy9YyQDwcZF9V1NaA2keYKhtE/go-libp2p-pubsub/pb" peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer" protocol "gx/ipfs/QmZNkThpqfVXs9GNbexPrfBbXSLNYeKrE7jwFM2oqHbyqN/go-libp2p-protocol" host "gx...
package realm import ( "encoding/json" "fmt" "net/http" "strings" "github.com/10gen/realm-cli/internal/utils/api" "github.com/10gen/realm-cli/internal/utils/flags" "go.mongodb.org/mongo-driver/bson/primitive" ) const ( apiKeysPathPattern = appPathPattern + "/api_keys" pendingUsersPathPattern = appPath...
package main import "fmt" // 198. 打家劫舍 // 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 // 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 // 提示: // 0 <= nums.length <= 100 // 0 <= nums[i] <= 400 // https://leetcode-cn.com/problems/house-robber/ func main(...
package main import "fmt" func main() { //一变量的声明 // 1. 声明var 变量名 类型 变量声明之后,必须使用 // 2. 只是声明变量没有初始化,默认为0 // 3. 在同一个{}里,声明变量是唯一的 var a int a = 10 //变量的赋值 先声明 再赋值 fmt.Println(a) //4.可以同时声明多个变量 //var b, c int // //b,c = 20,30 //fmt.Println(b,c) //二变量初始化 声明变量的同时进行赋值 var b int = 20 //初始化 b =...
// Copyright 2019 Radiation Detection and Imaging (RDI), LLC // Use of this source code is governed by the BSD 3-clause // license that can be found in the LICENSE file. package data import ( "github.com/proio-org/go-proio" ) type EventProcessor func(*proio.Event) type EventOp struct { Description string Even...
package monitor import ( "context" "os" "path/filepath" "time" "github.com/containerd/containerd" "github.com/containerd/containerd/cio" "github.com/containerd/typeurl" "github.com/crosbymichael/boss/config" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) type change interface { apply(context.Conte...
/* Copyright 2016 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 knowledge import ( "testing" "github.com/clems4ever/go-graphkb/internal/schema" "github.com/stretchr/testify/assert" ) func TestShouldRelateAssets(t *testing.T) { g := NewGraph() binder := NewGraphBinder(g) relation := schema.RelationType{ FromType: "from_type", ToType: "to_type", Type: "...
package astutils import ( "fmt" "github.com/kyleconroy/sqlc/internal/sql/ast" "github.com/kyleconroy/sqlc/internal/sql/ast/pg" ) type Visitor interface { Visit(ast.Node) Visitor } type VisitorFunc func(ast.Node) func (vf VisitorFunc) Visit(node ast.Node) Visitor { vf(node) return vf } func Walk(f Visitor, n...
/* Go Language Raspberry Pi Interface (c) Copyright David Thorpe 2016-2018 All Rights Reserved Documentation http://djthorpe.github.io/gopi/ For Licensing and Usage information, please see LICENSE.md */ package sensors import ( // Frameworks "github.com/djthorpe/gopi" ) ///////////////////////////////////...
package file import ( "fmt" . "github.com/rainmyy/easyDB/library/common" . "github.com/rainmyy/easyDB/library/strategy" ) /** *parser ini conf file *desc: *[test] * [..params] * name:name1 * key:value * [...params] * name:name2 * key:value */ func ParserIniContent(data []byte) (...
package main import ( "fmt" "net" "log" "io" "strconv" "bufio" "strings" ) type Client struct { Id string Conn net.Conn MessageChan chan Message } type Message struct { From string To string Body string } type Hub struct { Clients map[string]Client JoinChan ...
package models // PaperList is the result of PaperList() function. type PaperList struct { Count int64 `json:"count"` Next *string `json:"next"` Previous *string `json:"previous"` Results []Paper `json:"results"` } type Paper struct { ID string `json:"id"` ArxivID *strin...
package server import ( "fmt" "net/http" "path/filepath" "strconv" "github.com/dimfeld/httptreemux" "github.com/rkuris/journey/database" "github.com/rkuris/journey/filenames" "github.com/rkuris/journey/structure/methods" "github.com/rkuris/journey/templates" ) func indexHandler(w http.ResponseWriter, r *htt...
package xattrsyscall import ( "syscall" "unsafe" ) // Taken from https://golang.org/src/syscall/zsyscall_linux_amd64.go var _zero uintptr // Do the interface allocations only once for common // Errno values. var ( errEAGAIN error = syscall.EAGAIN errEINVAL error = syscall.EINVAL errENOENT error ...
package responses import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestDecodeAccountsBalancesResponse(t *testing.T) { encoded := "{\"balances\" : {\"nano_3t6k35gi95xu6tergt6p69ck76ogmitsa8mnijtpxm9fkcm736xtoncuohr3\": {\"balance\": \"325586539664609129644855132177\",\"pending\": \"2...
package usecases_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" usecases "github.com/vmware-tanzu-labs/git-story/usecases" ) var _ = Describe("Story Sweeper use case", func() { It("should delete all branches that correspond to accepted stories", func() { mockGitRepo := &MockGitRepository{b...
package cmd import( "fmt" "github.com/spf13/cobra" "os" // "strings" ) var rootCmd = &cobra.Command { Use: "LearningGo ", Short: "My first go project", Long: `Just a small CLI application. Read Atom feeds`, } var cmdLs = &cobra.Command { Use: "ls", Short: "List news", Long: `List first 5 news`, Run: func ...
package main import ( "fmt" "github.com/spf13/cobra" cmder "github.com/yaegashi/cobra-cmder" ) type AppSPJobDelete struct { *AppSPJob Scope string } func (app *AppSPJob) AppSPJobDeleteComder() cmder.Cmder { return &AppSPJobDelete{AppSPJob: app} } func (app *AppSPJobDelete) Cmd() *cobra.Command { cmd := &cob...
package models import ( "time" ) // Profile - type Profile struct { UserID int `json:"user_id"` ProfileImage string `json:"profile_image"` Bio string `json:"bio"` TeamID int `json:"team_id"` Settings string `json:"settings"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` Dele...
package security import ( "fmt" "html/template" "net/http" "net/url" "strings" ) func ExternalSystemCreatePage(t *template.Template, am AccessManager) func(w http.ResponseWriter, r *http.Request) { type Page struct { Session Session Title []string SystemType string Uuid st...
package controller import ( "encoding/json" "fmt" "regexp" "sort" "strings" "time" wfv1 "github.com/argoproj/argo/api/workflow/v1alpha1" "github.com/argoproj/argo/errors" workflowclient "github.com/argoproj/argo/workflow/client" "github.com/argoproj/argo/workflow/common" log "github.com/sirupsen/logrus" "...
package models import ( "github.com/jinzhu/gorm" ) // Review model type Review struct { gorm.Model Comment string Role string // Either Employer or Employee FromUserID uint ToUserID uint ReputationData ReputationData }
package main import ( "encoding/json" "fmt" ) type Monster struct { Name string Age int Skill string } //加tag,返回小写 type Hero struct { Name string `json:"name"` Age int `json:"age"` Skill string `json:"skill"` } func main() { monster := Monster{ Name: "monster", Age: 12, Skill: "kill", } ...
package operatorlister import ( "fmt" "sync" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/types" corev1 "k8s.io/client-go/listers/core/v1" ) type UnionPodLister struct { podListers map[string]corev1.PodLister podLock sync....
func isValid(s string) bool { stack := make([]byte, len(s)) cmap := map[byte]byte{ ')': '(', '}': '{', ']': '[', } height := 0 for idx := 0; idx < len(s); idx += 1{ ch := s[idx] if ch == '[' || ch == '(' || ch == '{' { stack = append(stack, ch) ...
package xpen import ( "encoding/json" //log "github.com/cihub/seelog" ) // 用户信息 type User struct { Nick string Email string } // 消息 type Message struct { Content string Time string User User } // 消息列表 type Msg struct { // 命令 login 登录, chat 聊天, users 用户列表, init 获取聊天记录, logout 登出 Command string // 消息...
package service import ( "github.com/keybase/client/go/libkb" "github.com/keybase/go-framed-msgpack-rpc/rpc" "golang.org/x/net/context" ) func CancellingProtocol(g *libkb.GlobalContext, prot rpc.Protocol) (res rpc.Protocol) { res.Name = prot.Name res.WrapError = prot.WrapError res.Methods = make(map[string]rpc....
package main import ( "fmt" "log" "net/rpc" "os" ) type Args struct { A, B int } type Math int type Quotient struct { Quo, Remem int } func main() { if len(os.Args) != 2 { fmt.Println("Usage:", os.Args[0], "server") } serverAddr := os.Args[1] // client, err := rpc.DialHTTP("tcp", serverAddr+":8080") cl...
package x // GENERATED BY XO. DO NOT EDIT. import ( "errors" "strings" //"time" "ms/sun/shared/helper" "strconv" "github.com/jmoiron/sqlx" ) // (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// GroupOrderdUser represents a row from 'sun_cha...
package Problem0093 import ( "fmt" ) func restoreIpAddresses(s string) []string { n := len(s) if n < 4 || n > 12 { return []string{} } res := []string{} combination := make([]string, 4) var dfs func(int, int) dfs = func(idx, begin int) { if idx == 3 { temp := s[begin:] if isOK(temp) { combinat...
package calendar import ( "strconv" "time" "github.com/kudrykv/latex-yearly-planner/app/components/hyper" ) type DayTime struct { time.Time } func (d DayTime) AddDate(years, months, days int) DayTime { return DayTime{Time: d.Time.AddDate(years, months, days)} } func (d DayTime) Link() string { return hyper.L...
package main import ( "encoding/json" "fmt" ) // 结构体标签 // 定义一个Student体,使用结构体标签 type Student2 struct { Id string `json:"id"` // 通过指定tag实现json序列化该字段的key Gender string `json:"gender"` Name string `json:"name"` Sno string `json:"sno"` } func main() { var s1 = Student2{ Id: "12", Gender: "男", Name: "李四", S...
package board import ( "image" "strings" "testing" "testutil" ) func TestDirectionNames(t *testing.T) { testCases := map[Direction]string{ None: "None", S: "S", N | W: "NW", N | E | S | W: "NESW", Direction(dir...
package twch import ( "fmt" ) type Blocks struct { client *Client } type listBlocks struct { Blocks []Block `json:"blocks"` listLinks } type Block struct { ID *int `json:"_id"` UpdatedAt *string `json:"updated_at"` User *User `json:"user"` } func (b *Blocks) ListBlocks(login string, opts *L...
package main import ( "fmt" ) func printDeezerPlaylists() { playlists, err := d.Client.GetCurrentUserPlaylists() if err != nil { fmt.Println(err) return } for _, playlist := range playlists { fmt.Println(playlist.Title) } } func printDeezerLovedTracks() { playlists, err := d.Client.GetCurrentUserPlayl...
// interfaces package main import "fmt" // declarar una interfaz llamada speaker con un método speak type speaker interface { speak() } // declarar un struct llamada ingles que representa a una persona que hable inglés type ingles struct { } // declarar un struct llamada spanish que representa a una persona que ...
/* 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, softw...
package main import ( "fmt" "path/filepath" "os" ) func main() { fmt.Printf("hello, world\n") p, e := filepath.Abs("") fmt.Printf("%v\n", p) fmt.Printf("%v\n", e) stat, _ := os.Stat("parent") if stat != nil { fmt.Printf("Stat name: %s", stat.Name()) fmt.Printf("Stat isdir: %v", stat.IsDir()) } }
package main import ( "fmt" "math" ) func main() { a := 3 b := 2 fmt.Println("Sum = ", a+b) fmt.Println("Sub = ", a-b) fmt.Println("Div = ", a/b) fmt.Println("Mul = ", a*b) fmt.Println("Mod = ", a%b) fmt.Println("AND => ", a&b) fmt.Println("OR => ", a|b) c := 3.0 d := 2.0 fmt.Println("Bigger =>", ma...
package authenticate import ( "testing" "github.com/pomerium/pomerium/config" ) func newTestOptions(t *testing.T) *config.Options { opts := config.NewDefaultOptions() opts.AuthenticateURLString = "https://authenticate.example" opts.AuthorizeURLString = "https://authorize.example" opts.InsecureServer = true op...
package main import ( adventutilities "AdventOfCode/utils" "log" "strconv" "strings" ) func splitStringIntoJuicyBits(passwAndPolicy string) (minOcc int, maxOcc int, charToMatch string, password string) { // trekk ut policy policy := strings.Split(passwAndPolicy, " ")[0] minOcc, err := strconv.Atoi(strings.Spli...
package main import ( "fmt" "runtime" "sync" "time" ) const limit = 1e6 func main() { t1 := time.Now() sum1 := loopSum() fmt.Println("sum1 is: ", sum1) fmt.Printf("cost time %d ns\n", time.Now().Sub(t1)) t2 := time.Now() sum2 := ConcurrentSum() fmt.Println("sum2 is: ", sum2) fmt.Printf("cost time %d ns\...
/* * Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://...
package handlers import ( "fama/core" "fama/numbers/ports" "github.com/gin-gonic/gin" "net/http" ) func init() { err := core.Injector.Provide(newNumbersHandler) core.CheckInjection(err, "newNumbersHandler") } type NumbersHandler struct { manager ports.NumbersManager } func newNumbersHandler(manager ports.Num...
package main import ( "fmt" "sort" ) // https://leetcode-cn.com/problems/reverse-pairs/ // 493. 翻转对 | Reverse Pairs //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Solution // // 离散化 + 树状数组 // // 这里...
package GC import ( "bytes" "encoding/binary" cmp "github.com/mortim-portim/GraphEng/compression" ) // //.d8888. db db d8b db .o88b. db db .d8b. d8888b. //88' YP `8b d8' 888o 88 d8P Y8 88 88 d8' `8b 88 `8D //`8bo. `8bd8' 88V8o 88 8P Y8 8P 88ooo88 88oobY' // `Y8b. 88 88 V8o88 ...
// Copyright © 2020 Attestant Limited. // 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 ...
package opp import "testing" func TestMemProFile(t*testing.T){ MemProFile() }
package solver import ( "context" "math/rand" "strconv" "testing" ) var BenchmarkInput = func() []Variable { const ( length = 256 seed = 9 pMandatory = .1 pDependency = .15 nDependency = 6 pConflict = .05 nConflict = 3 ) rnd := rand.New(rand.NewSource(seed)) id := func(i int) ...
/* Given num as input, return an array with all primes up to num included. Alternative Text Examples eratosthenes(1) ➞ [] eratosthenes(10) ➞ [2, 3, 5, 7] eratosthenes(20) ➞ [2, 3, 5, 7, 11, 13, 17, 19] eratosthenes(0) ➞ [] Notes Check the Resources tab for info on the meaning of "Eratosthenes". Try sol...