text
stringlengths
11
4.05M
package main import ( "lesson/lesson13-ready-spider/engine" "lesson/lesson13-ready-spider/zhenai/parser" "lesson/lesson13-ready-spider/scheduler" ) // 获取并打印 城市第一页的用户信息 // 入口函数 func main() { url := "http://www.zhenai.com/zhenghun" e := engine.ConcurrentEngine{ Scheduler: &scheduler.SimpleScheduler{}, WorkerCo...
package dushengchen /** Submission: https://leetcode.com/submissions/detail/740781943/ Runtime: 6 ms, faster than 67.71% of Go online submissions for Diameter of Binary Tree. Memory Usage: 4.7 MB, less than 5.00% of Go online submissions for Diameter of Binary Tree. */ func maximalSquare(matrix [][]byte) int { m...
package cmd import ( "encoding/json" "fmt" "github.com/bitmaelum/bitmaelum-suite/internal/container" "github.com/bitmaelum/bitmaelum-suite/internal/parse" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/spf13/cobra" "time" ) type jsonOut map[string]interface{} // inviteCmd represents the invite...
package main type Node struct{ Val int Left *Node Right *Node Height int Size int } func AvlInsert(root *Node, val int) *Node { if root == nil { node := Node{Val: val, Height: 0, Size: 1} return &node } if val < root.Val { root.Left = AvlInsert(root.Left, val) ...
package xmbs type Rule struct { Process string `yaml:"process,omitempty"` Resource string `yaml:"resource,omitempty"` Amount string `yaml:"amount,omitempty"` When string `yaml:"when,omitempty"` } type Config struct { Rules []Rule `yaml:"rules"` }
package example import ( "github.com/Hexilee/gotten" "net/http" "time" ) type ( SimpleParams struct { Id int Page int } Item struct { TypeId int IId int Name string Description string } ExpectResult []*Item ObjectNotFound struct { Key string Reason strin...
package messages type postRequestModel struct { Content string `json:"content"` UserID string `json:"user_id"` }
package dictd /* Server encapsulation. * * This contains a bundle of useful helpers, as well as a few data structures * to handle registered Databases and Commands. */ type Server struct { Name string Info string commands map[string]func(*Session, Command) } /* GetHandler returns a Command handler for t...
package sse import ( "fmt" "net/http" "strings" ) type Event struct { Id *int Name string Data string } func (e Event) Marshal() []byte { m := "" if e.Id != nil { m += "id:" + fmt.Sprint(*e.Id) + "\n" } m += "event:" + e.Name + "\n" for _, line := range strings.Split(e.Data, "\n") { m += "data:" + l...
/* * Copyright 2017 StreamSets 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...
// Licensed to Apache Software Foundation (ASF) under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Apache Software Foundation (ASF) licenses this file to you under // the Apache License, Version 2.0 (the "Li...
// testjson2 project doc.go /* testjson2 document */ package main
package bridge import ( "fmt" "testing" ) //func TestBridge(t *testing.T) { // sa := SoftwareA{Software{"a"}} // sb := SoftwareB{Software{"b"}} // // pa := NewPhoneA("pa") // pb := NewPhoneB("pb") // // pa.setSoft(&sa) // pa.Run() // // pb.setSoft(&sb) // pb.Run() // // fmt.Println() // p := TSoftware{&sb} // p.Run...
// Copyright © 2018 Inanc Gumus // Learn Go Programming Course // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // // For more tutorials : https://learngoprogramming.com // In-person training : https://www.linkedin.com/in/inancgumus/ // Follow me on twitter: https://twitter.com/inancgumus package main ...
package user import "fmt" type UseCase interface { ValidateUser(email, password string) error } type Service struct{} func NewService() *Service { return &Service{} } func (s *Service) ValidateUser(email, password string) error { //@TODO create validation rules, using databases or something else if email == "em...
package pkg_test import ( "fmt" "reflect" "sync" "testing" "unsafe" ) func StringToByteUnsafe(s string) []byte { strh := (*reflect.StringHeader)(unsafe.Pointer(&s)) var sh reflect.SliceHeader sh.Data = strh.Data sh.Len = strh.Len sh.Cap = strh.Len return *(*[]byte)(unsafe.Pointer(&sh)) } func Convert(s []...
package mssql import ( "database/sql" ) // Repository is sql server implementation of repository type Repository struct { Connection *sql.DB }
package main //import "fmt" type Broadcaster struct { Registered []chan int Sender chan int } func NewBroadcaster() *Broadcaster { b := new(Broadcaster) b.Registered = make([]chan int, 0) b.Sender = make(chan int) go func() { for { value := <-b.Sender for _, ch := range b.Registered...
package main import ( "fmt" "time" tm "github.com/buger/goterm" "github.com/goburrow/modbus" "github.com/influxdata/influxdb/client/v2" log "github.com/sirupsen/logrus" ) const ( tsdb = "powermeterdb" tsuser = "poweruser" tspassword = "P@ssw0rd" ) var normal chan bool type EnergyMeter struct { ...
// 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 upload import ( "github.com/xeha-gmbh/homelab/proxmox/upload/api" "github.com/xeha-gmbh/homelab/shared" "github.com/spf13/cobra" flag "github.com/spf13/pflag" "os" "os/exec" ) var ( output shared.MessagePrinter ) func NewProxmoxUploadCommand() *cobra.Command { payload := &ProxmoxUploadRequest{} cmd...
/* * @lc app=leetcode.cn id=46 lang=golang * * [46] 全排列 */ package main import ( "fmt" ) // @lc code=start func backtracking(nums, res []int, ans *[][]int, used *[]bool) { numsLen := len(nums) if len(res) == numsLen { *ans = append(*ans, append([]int{}, res...)) } for i := 0; i < numsLen; i++ { if !(*use...
package envoy import ( core "github.com/envoyproxy/go-control-plane/envoy/api/v2/core" "github.com/golang/protobuf/ptypes/wrappers" ) func headersToAdd(headers map[string]string) []*core.HeaderValueOption { var res []*core.HeaderValueOption for headerName, headerVal := range headers { header := &core.HeaderVal...
package config // package provides global config parameters in case I ever want to change them const TileSize = 40
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00100103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.001.001.03 Document"` Message *AcceptorAuthorisationRequestV03 `xml:"AccptrAuthstnReq"` } func (d *Docu...
// Copyright (c) 2019 Zededa, Inc. // SPDX-License-Identifier: Apache-2.0 package types import ( "github.com/satori/go.uuid" "github.com/stretchr/testify/assert" "testing" "time" ) var underlayUUID = uuid.UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8} var ov...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //105. Construct Binary Tree from Preorder and Inorder Traversal //Given preorder and inorder traversal of a tree, construct the binary tree. //Note: /...
package controllers import ( "encoding/json" "fmt" "net/http" "../models" "github.com/gorilla/mux" ) func CreateIngredient(w http.ResponseWriter, r *http.Request) { ingredient := &models.Ingredient{} json.NewDecoder(r.Body).Decode(ingredient) createdIngredient := db.Create(ingredient) var errMessage = cre...
package main import "fmt" func main0101() { //数组 是指一系列同一类型数据的集合 //数组定义 //var 数组名 [长度]类型 var a [10]int //fmt.Println(len(a)) fmt.Println(a) //注意以下方式 //报错err //var arr int = 10 //var a [n]int //数组赋值 //a[0] = 1 //a[1] = 2 //a[2] = 3 //a[3] = 4 //fmt.Println(a) //fmt.Println(a[0]) //fmt.Println(a[1]...
/* Copyright 2016 Stanislav Liberman 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 ...
package ydySqlParser import ( "fmt" "github.com/youtube/vitess/go/vt/sqlparser" "strings" ) func BuildNewSql(sql string) string { stmt, err := sqlparser.Parse(sql) if err != nil { fmt.Println(err) return sql } switch v := stmt.(type) { case *sqlparser.Select: new_subquery := &sqlparser.Subquery{Sel...
// gofun.go package main // int a; // typedef void (*cb)(char* data); // extern void callCb(cb callback, char* extra, char* arg); import "C" // C是一个虚包, 上面的注释是c代码, 可以在golang中加 `C.` 前缀访问, 具体参考上面给出的文档 import "time" //export hello func hello(arg *C.char) *C.char { //name := gjson.Get(arg, "name") //return "hello...
package middlewares import ( "regexp" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/authelia/authelia/v4/internal/configuration/schema" ) func TestNewPasswordPolicyProvider(t *testing.T) { testCases := []struct { desc string have schema.PasswordPo...
package gobot func doTest() { site := Site{BaseUrl: "http://golang.org"} urls := []string{site.BaseUrl} site.BreadthFirst(Crawl, urls) }
package sheets import ( "bufio" "os" "fmt" "io" "strings" retry "github.com/avast/retry-go" "github.com/pkg/errors" "google.golang.org/api/googleapi" sheets "google.golang.org/api/sheets/v4" ) type Spreadsheet struct { Client *Client *sheets.Spreadsheet } type Sheet struct { *sheets.Sheet Spreadsheet ...
package main import ( bit "math/bits" f "fmt" ) func main() { var a uint=31 f.Printf("bits.Len(%d)=%d\n",a,bit.Len(a)) a++ f.Printf("bits.Len(%d)=%d\n",a,bit.Len(a)) }
package sol import ( "reflect" "testing" ) func TestSol(t *testing.T) { testcases := []struct { input []int want []int }{ { input: []int{1, 2, 3, 4}, want: []int{24, 12, 8, 6}, }, { input: []int{-1, 1, 0, -3, 3}, want: []int{0, 0, 9, 0, 0}, }, { input: []int{1, 1}, want: []int...
package agency // UserAgent represents the results from a call to Scan(). type UserAgent struct { Browser struct { Type string Name string } Device struct { Type string } OS struct { Name string Version string } }
package rank import ( "time" "Barracks/data" "container/heap" ) type RankInfo struct { RankData *rankData RankHeap *rankHeap Problems []data.Problem } func newUserRow (user *data.User, problems *[]data.Problem) (u userRow) { u = userRow{ Rank: 1, StrId: (*user).StrId, ID: (*user).ID, Pr...
package light import ( "net/http" "sync" "reflect" "strings" "errors" "encoding/json" "fmt" ) var handlerMap map[string]reflect.Value = make(map[string]reflect.Value) var lock sync.Mutex type Light struct { response http.ResponseWriter request *http.Request Parm string } func (this *Light)ServeHTTP(w htt...
package integers // Add adds two integers returning the result func Add(a, b int) int { return a + b }
/* Copyright 2021 RadonDB. 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 distri...
package metadata import ( "incognito-chain/common" ) type IssuingEVMResponse struct { MetadataBase RequestedTxID common.Hash `json:"RequestedTxID"` UniqTx []byte `json:"UniqETHTx"` ExternalTokenID []byte `json:"ExternalTokenID"` SharedRandom []byte `json:"SharedRandom,omitempty"` } func...
package main import ( "encoding/json" "flag" "fmt" "github.com/songgao/water" "golang.org/x/net/ipv4" "log" "net" "os" "os/exec" ) const ( // BUFFERSIZE represents a size of read buffer. BUFFERSIZE = 1500 // MTU represents a maximum transmission unit. MTU = "1300" ) func runIP(args ...string) { ...
/* * Copyright © 2019-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 db import ( "regexp" "sync" ) // DatabaseIndex is the in memory index of a collection of conversations, and their tags. // Exported functions are goroutine safe while un-exported functions assume the caller will use the appropriate locks type DatabaseIndex struct { // in memory metadata index, built on loa...
package repository import ( "context" "log" "math/rand" "strconv" "cloud.google.com/go/firestore" firebase "firebase.google.com/go" "github.com/b1g2h3/todoapp/entity" "google.golang.org/api/iterator" "google.golang.org/api/option" ) // TodoRepository interface type TodoRepository interface { GetLists(list ...
package main import "fmt" func main() { var ruby bool var java int var golang string fmt.Println(golang, ruby, java) }
package cmd import ( "github.com/spf13/cobra" ) func init() { RootCmd.AddCommand(uninstallCommand) } var uninstallCommand = &cobra.Command{ Use: "uninstall", Short: "Uninstall a node", Run: func(cmd *cobra.Command, args []string) {}, }
package cfile import ( "io" "os" ) // Writer returns f.WriteAt(-1). func (f *File) Writer() *Writer { return f.WriterAt(-1) } // WriterAt acquires a write-lock, seeks to the given offset and returns a writer. // if off is < 0, it seeks to the end of the file, otherwise it seeks to the off value. func (f *File) Wr...
package main import ( "fmt" "github.com/jackytck/projecteuler/tools" ) func isBouncy(n int) bool { ds := tools.Digits(n) var up, down bool for i := 1; i < len(ds); i++ { if ds[i] > ds[i-1] { up = true } else if ds[i] < ds[i-1] { down = true } if up && down { break } } return up && down } f...
package main import ( "fmt" "os" "os/signal" "syscall" "github.com/anihouse/bot" "github.com/anihouse/bot/app" "github.com/anihouse/bot/config" "github.com/anihouse/bot/db" "github.com/anihouse/bot/tpl" "github.com/urfave/cli" ) func run(c *cli.Context) error { fmt.Println("Bot is running. Press Ctrl + C ...
package main import ( "database/sql" "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" "time" ) // 自动迁移和迁移接口的方法 // 模型定义 type Student struct { ID uint Name string Age uint Email string CreatedAt time.Time UpdatedAt time.Time DeletedAt time.Time } var ( sqlDB *sql.DB gormDB *gorm.DB ) ...
package fileutil import ( "io/ioutil" "os" "github.com/pkg/errors" ) // Utility constants for managing files const ( DefaultFilePerm = 0644 DefaultDirPerm = 0755 ) // Copy copies a file from a source to a destination func Copy(source string, destination string) error { content, err := ioutil.ReadFile(source)...
package backup_test /* import ( "bytes" "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/messagedb/messagedb" "github.com/messagedb/messagedb/cmd/influxd" ) // Ensure the backup can download from the server and save to disk. func TestBackupCommand(t *testing.T) { // Mock the backup endpoi...
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func kthSmallest(root *TreeNode, k int) int { _, res := r(root, 0, k) return res } func r(node *TreeNode, c, k int) (int, int) { cc := c res := 0 if node.Left != ...
package isset import ( "fmt" ) type Bool struct { value bool valid bool } // IsValid returns whether a value has been set func (b *Bool) IsValid() bool { return b.valid } // Set a value. func (b *Bool) Set(nb bool) { b.valid = true b.value = nb } // Unset the variable, like setting it to nil func (b *Bool) U...
package led import ( "fmt" "log" "strconv" "time" "github.com/water78813/iot/manager" "gobot.io/x/gobot/platforms/firmata" ) type ledModule struct { ledState int pin string ip string interval string funcState string stopCh chan struct{} } // func LedAccessor(m map[string]string) error...
package smaller import ( "testing" "github.com/google/go-cmp/cmp" ) func TestCountSmaller(t *testing.T) { testCases := map[string]struct { input []int expectedOutput []int }{ "Example 1": { input: []int{5, 2, 6, 1}, expectedOutput: []int{2, 1, 1, 0}, // Explanation: // To the ...
/* A biquadratic number is a number that is the fourth power of another integer, for example: 3^4 = 3*3*3*3 = 81 Given an integer as input, output the closest biquadratic number. Here are the first 15 double-squares: 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 14641, 20736, 28561, 38416, 50625 This is code-...
package git /* #include <git2.h> extern void _go_git_populate_stash_apply_callbacks(git_stash_apply_options *opts); extern int _go_git_stash_foreach(git_repository *repo, void *payload); */ import "C" import ( "runtime" "unsafe" ) // StashFlag are flags that affect the stash save operation. type StashFlag int con...
package nutanix import ( "encoding/json" "github.com/pkg/errors" machinev1 "github.com/openshift/api/machine/v1" nutanixtypes "github.com/openshift/installer/pkg/types/nutanix" ) type config struct { PrismCentralAddress string `json:"nutanix_prism_central_address"` Port ...
package dp import ( "github.com/numacci/go-algorithm/stl/function" ) // KnapsackDP は,以下のような問題を解くときに利用される動的計画法である. // 重さと価値が定義されたN個の品物の中から重さの総和がWを超えないように // いくつか品物を選ぶとき,価値の総和の最大値はいくらになるか. // 重さの状態を保持しておく必要があるので,DPは以下のように定義する. // dp[i+1][j]: i番目までの品物から,重さの総和がjを超えないように // 品物を選んだ場合の価値の総和の最大値 // 品物を選べ...
package usecases import ( "time" "github.com/michaldziurowski/tech-challenge-time/server/timetracking/domain" ) type EventStore interface { AddEvent(event domain.SessionEvent) error GetEventsByRange(userId string, from time.Time, to time.Time) ([]domain.SessionEvent, error) } type Repository interface { AddSes...
/* Copyright 2019 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 main import "fmt" func main() { a := "192304" b := "92304" fmt.Println(multiply(a, b)) } func multiply(num1 string, num2 string) string { if len(num1) == 1 && num1[0] == '0' || len(num2) == 1 && num2[0] == '0' { return "0" } a := []byte(num1) b := []byte(num2) reverse(a) reverse(b) res := []byte{}...
package main import ( "github.com/therecipe/qt/widgets" ) func itemWidgets() { //List Widget listWidget := widgets.NewQListWidget(nil) listWidget.SetWindowTitle("List Widget") list := []string{"This", "Is", "A", "List", "View"} listWidget.AddItems(list) addWidget(listWidget) //Tree Widget...
package main import ( "errors" "net/http" "time" health "github.com/docker/go-healthcheck" "github.com/gorilla/mux" ) func main() { health.RegisterPeriodicThresholdFunc("postgresql", time.Second*5, 3, postgresqlCheck) health.RegisterPeriodicThresholdFunc("gateway", time.Second*5, 3, gateWayCheck) r := mux....
package raftkv import "labrpc" import "crypto/rand" import "math/big" import "sync" type Clerk struct { mu sync.Mutex servers []*labrpc.ClientEnd clientId int64 nextRequestId int64 } func nrand() int64 { max := big.NewInt(int64(1) << 62) bigx, _ := rand.Int(rand.Reader, max) x := bigx.In...
/* ==================what are go routines ? A goroutine is a lightweight thread managed by the Go runtime. using go routines we can make our sequential program into concurrent program =====================================goroutines vs threads ? GOROUTINE THREAD 1...
/* Copyright (c) 2014-2015 Jason Ish * All rights reserved. * * 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 condi...
package charts import ( "github.com/go-echarts/go-echarts/v2/opts" "github.com/go-echarts/go-echarts/v2/render" "github.com/go-echarts/go-echarts/v2/types" ) // Graph represents a graph chart. type Graph struct { BaseConfiguration BaseActions } // Type returns the chart type. func (*Graph) Type() string { retur...
package rados import ( "bytes" "fmt" "io" "os" "testing" "time" ) func errorOnError(t *testing.T, e error, message string, parameters ...interface{}) { if e != nil { t.Errorf("%v : %v", e, fmt.Sprintf(message, parameters...)) } } func fatalOnError(t *testing.T, e error, messag...
// Copyright 2014 The Sporting Exchange Limited. All rights reserved. // Use of this source code is governed by a free license that can be // found in the LICENSE file. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris /* Package pprof configures export of runtime/pprof data. Usage: import _ ...
// 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 plot import ( "math" "strconv" "gonum.org/v1/plot" ) type FuncScale struct { Func func(float64) float64 } func (s *FuncScale) Normali...
package repositories import ( "database/sql" "fmt" "sync" _ "github.com/lib/pq" ) var ( db *sql.DB errDB error once sync.Once ) const ( host = "172.18.0.2" port = 5432 user = "postgres" password = "postgres" dbname = "postgres" ) func GetInstanceDB() (*sql.DB, ...
package db import ( "strings" "testing" s "github.com/thedevelopnik/netplan/pkg/models" ) func TestCreateSubnet(t *testing.T) { sn := s.Subnet{ Name: "create-test-subnet", Access: "public", Location: "us-east4", Provider: "GCP", Env: "dev", CidrBlock: "192.168.0.0/16", VPCID: 1,...
package main import ( "github.com/Skactor/bypass-detection/config" "github.com/Skactor/bypass-detection/logger" "github.com/Skactor/bypass-detection/server" ) func main() { err := logger.InitLogger() if err != nil { logger.Logger.Fatalf("Failed to init logger: %s", err.Error()) } cfg, err := config.Parse("./...
package view import ( "net/http" "go.sancus.dev/cms" "go.sancus.dev/web/errors" ) type View struct { config cms.ViewConfig server cms.Directory } func NewView(s cms.Directory, cfg cms.ViewConfig) (cms.View, error) { v := &View{ config: cfg, server: s, } if err := v.SetDefaults(); err != nil { return ...
package cacheutil import ( "balansir/internal/logutil" "encoding/gob" "fmt" "os" "sync/atomic" "time" ) const ( snapshotPath = ".snapshot.gob" actionsThreshold1m = 100 actionsThreshold15m = 1 ) //BackupManager ... type BackupManager struct { ActionsCount int64 } //Snapshot ... type Snapshot struct...
package main import ( "./solutions" "fmt" ) /* * @problem: https://leetcode.com/problems/longest-substring-without-repeating-characters/ * */ func main() { testStr := "pwwkew" result := solutions.LongestSubString(testStr) fmt.Println(result) }
// 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 dialer import ( "k0s.io/k0s/pkg/agent" ) var ( _ agent.Dialer = (*dialr)(nil) ) func New(c agent.Config) agent.Dialer { return &dialr{ c: c, } } type dialr struct { c agent.Config }
package terminal_test import ( "bytes" "io" "github.com/docker/docker/pkg/term" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/cloudfoundry-incubator/ltc/terminal" "github.com/cloudfoundry-incubator/ltc/terminal/mocks" ) type fakeStdin struct { io.Reader } func (s *fakeStdin) Fd() uintpt...
package main import ( "fmt" "math" "math/rand" b2d "github.com/neguse/go-box2d-lite/box2dlite" "github.com/tanema/amore" "github.com/tanema/amore/gfx" "github.com/tanema/amore/keyboard" "github.com/tanema/amore/timer" ) const timeStep = 1.0 / 60 var ( gravity = b2d.Vec2{0.0, -10.0} iterations = 10 wor...
package sql_test import ( "errors" "reflect" "testing" sql "github.com/ndilsou/go-rdbms-playground" ) func TestPlanner_Plan(t *testing.T) { tests := []struct { name string stmt sql.Stmt want sql.PlanNode wantErr bool }{ { name: "no relation", stmt: &sql.SelectStmt{ Fields: []sql.Id...
package controllers import ( "github.com/astaxie/beego/logs" "net/url" "strconv" "time" "github.com/canghai908/zbxtable/models" ) // ExpController operations for Group type ExpController struct { BaseController } // ExpRes is used //var GroupRes models.GroupList //var ExpRes list var ExpRes models.ExpList //...
package memrepo import ( "github.com/scjalliance/drivestream/commit" "github.com/scjalliance/drivestream/resource" ) var _ commit.Sequence = (*Commits)(nil) // Commits accesses a sequence of commits in an in-memory repository. type Commits struct { repo *Repository drive resource.ID } // Next returns the seque...
package middleware import ( "encoding/json" "fmt" "io" ) type Usuario struct { ID int `json:"id"` Login string `json:"login"` Senha string `json:"senha"` Email string `json:"email"` DataCriacao string `json:"dataCriacao"` IDGrupoUsuario int `json:"idGrupoUsuari...
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { var part int // part is defined as cmd argument if len(os.Args) > 1 && os.Args[1] == "part2" { part = 2 } else { //run part 1 as default part = 1 } inFile, _ := os.Open("input.txt") defer inFile.Close() scanner := bufio.Ne...
package protocol import ( "bytes" "strings" ) type OpQuery struct { *Op Flags int32 FullCollectionName string NumberToSkip int32 NumberToReturn int32 Query Document ReturnFieldsSelector Document } func (p *OpQuery) TableName() (*TableName, bool) { sp := strings...
// +build !what,!whathappens package what func Happens(fmt string, args ...interface{}) {} func If(bool, string, ...interface{}) {}
/* Return the number of times that the string "hi" appears anywhere in the given string. */ package main import ( "fmt" ) func count_hi(s string) int { var n int = 0 for i := 0; i < len(s)-1; i++ { if s[i:i+2] == "hi" { n++ } } return n } func main(){ var status int = 0 if count_hi("abc hi ho") == 1 { sta...
func solveNQueens(n int) [][]string { res:=[][]string{} post := make([]int, n) for i := 0; i < n; i++ { post[i] = -1 } dfs(post, 0, &res) return res } func dfs(pos []int, row int, res *[][]string) { n := len(pos) if row == n { out:=make([]string,n) for j,v:=range pos{ a...
package graphs import ( "bufio" "bytes" "image/color" "time" "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/vg" "github.com/gonum/plot/vg/draw" "github.com/gonum/plot/vg/vgsvg" "github.com/spazbite187/sensornet" ) const ( xSize = 7 ySize = 3 ) // GetTempGraph ... func Get...
package server // Notification is a JSONRPC notification type Notification struct { Method string `json:"method"` Params interface{} `json:"params"` } // Subscribable describes a type which can send notifications type Subscribable interface { Subscribe(id uint64) chan Notification Unsubscribe(id uint64) }
package kvstore import ( "errors" "testing" "github.com/stretchr/testify/assert" ) var ( store Store ) func init() { store = Initialize() } func TestGet(t *testing.T) { store.Set("xx", "yy") expectedValue := "yy" actualValue, actualError := store.Get("xx") assert.Nil(t, actualError) assert.Equal(t, exp...
package models import ( "encoding/json" "errors" "fmt" "github.com/gomodule/redigo/redis" ) const ( sqlForCreateLawsuit = "INSERT INTO lawsuits(id,company_id,points,name,type,date) VALUES(?,?,?,?,?,?);" ) type Lawsuit struct { ID int `orm:"column(id)"` CompanyID int `orm:"column(company_id)"` P...
package config //MYSQL配置 const ( //mysql 连接cdn地址 MYSQL_DATA_SOURCE_NAME = "root:nihaoma123?@tcp(192.168.3.235:3306)/blog?charset=utf8&parseTime=true" //连接池最大链接数 MYSQL_SET_MAX_OPEN_CONNS = 400 //最大闲置链接数 MYSQL_SET_MAX_IDLE_CONNS = 200 //数据表前缀 MYSQL_TABLE_PREFIX = "b_" //关闭表名复数例如"type table struct"表名为 "tables" 关...
package main // import ( // "encoding/json" // "fmt" // "io/ioutil" // "os" // "strings" // "github.com/evanxg852000/eserveless/internal/data" // "github.com/evanxg852000/eserveless/internal/helpers" // "github.com/gofrs/uuid" // ) // func main() { // projectDir, err := ioutil.TempDir("", "repos-") // if e...