text
stringlengths
11
4.05M
package main import ( "fmt" "log" "net/http" "time" ) func main() { http.HandleFunc("/", httpHandler) log.Println("Server started on port 8080") log.Fatal(http.ListenAndServe(":8080", nil)) } func httpHandler(res http.ResponseWriter, req *http.Request) { log.Println("Handler started") defer log.Println("Han...
package main import "fmt" func main() { a := 5 // Type inference fmt.Println(a) var str = "My String" fmt.Println(str) var b int b = 2 fmt.Println(b) var c, d = 3, 4 fmt.Printf("%d, %d\n", c, d) var e int fmt.Println(e) slice := []int { // Variable size 'slice' placed on heap. Size can be modified ...
package shared import ( "testing" "github.com/containers/libpod/pkg/util" "github.com/stretchr/testify/assert" ) var ( name = "foo" imageName = "bar" ) func TestGenerateRunEnvironment(t *testing.T) { opts := make(map[string]string) opts["opt1"] = "one" opts["opt2"] = "two" opts["opt3"] = "three" envs...
package server import ( "github.com/siddontang/ledisdb/client/go/ledis" "testing" ) func TestKV(t *testing.T) { c := getTestConn() defer c.Close() if ok, err := ledis.String(c.Do("set", "a", "1234")); err != nil { t.Fatal(err) } else if ok != OK { t.Fatal(ok) } if n, err := ledis.Int(c.Do("setnx", "a", ...
package main import ( "josiah.top/go_lagou/ch22/server" "log" "net" "net/rpc" ) /* rpc 远程服务 c/s 客户端(Client)调用客户端存根(Client Stub),同时把参数传给客户端存根; 客户端存根将参数打包编码,并通过系统调用发送到服务端; 客户端本地系统发送信息到服务器; 服务器系统将信息发送到服务端存根(Server Stub); 服务端存根解析信息,也就是解码; 服务端存根调用真正的服务端程序(Sever); 服务端(Server)处理后,通过同样的方式,把结果再返回给客户端(Client)。 */ func ...
package main import ( "fmt" "strings" "strconv" "time" ) func main() { fmt.Println("Strings operation") stringOperation() timeOperation() } func stringOperation() { str := "I'm a confident boy" //前后缀 strings.HasPrefix | strings.HasSuffix fmt.Printf("does str has perfix is %s? %t\n", "Im",strings.HasPrefix...
package main import "github.com/gin-gonic/gin" // GetLoggedInUser gets the logged in user from gin context func GetLoggedInUser(c *gin.Context) *User { u, exists := c.Get("user") user, ok := u.(*User) if !exists || !ok || user == nil { return nil } return user } // IsLoggedIn returns true if the user is logg...
//Utils is the tools lib package setting import ( "fmt" "io" "os" "strings" "sync" "time" "github.com/lunny/log" ) //Seelogger is a logger instance; type Seelogger struct { *log.Logger } type seelogwriter struct { *sync.Mutex currentFileName string fd *os.File } var ( //Seelog can be used ...
package main import ( "flag" "io/fs" "log" "os" "path/filepath" "time" ) var flagPath string var flagDuration string var flagDryRun bool var flagLogPath string var duration time.Duration var logFile *os.File func init() { log.Print("initializing") flag.StringVar(&flagPath, "path", "", "the path of the direc...
package commands import ( "os" "github.com/BurntSushi/toml" "github.com/cpuguy83/strongerrors" "github.com/pkg/errors" ) // UserConfig represents the user configuration read from a config file type UserConfig struct { Subscription string Location string Profile struct { Kubernetes struct { Version ...
// Copyright 2019, OpenTelemetry 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 ag...
package rtrserver import ( "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/xormdb" ) func getMaxSerialNumberDb() (serialNumber uint32, err error) { sql := `select serialNumber from lab_rpki_rtr_serial_number order by id desc limit 1` has, err := xormdb.XormEngine.SQL(sql).Get(&serialNumber) if err ...
/* * @lc app=leetcode.cn id=141 lang=golang * * [141] 环形链表 */ // @lc code=start /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ package main import "fmt" type ListNode struct { Val int Next *ListNode } func hasCycle(head *ListNode) bool { p1...
package main import ( "fmt" "os" "unicode" ) func main() { lista := os.Args[0:] for i := 0; i < len(lista); i++ { fmt.Print(TrasformaParola(lista[i], i), " ") } } func TrasformaParola(parola string, posizione int) (parolaTrasformata string) { parolaE := []rune(parola) var ptr []rune if posizione%2 == 0 { ...
package crawler import ( "errors" "fmt" "log" "net/http" "path/filepath" "github.com/PuerkitoBio/goquery" ) // FindForGate . func FindForGate(url string) (title string, text string, err error) { // Request the HTML page. res, err := http.Get(url) if err != nil { log.Println(err) return } defer res.Bod...
// Copyright 2015 Google Inc. 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...
package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "os" "testing" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" "github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface" ) type mockVerify struct { cognitoident...
package main import ( "fmt" "sync" ) var wg sync.WaitGroup func main() { //testAnonymousStructs() // i := 1 // defer logNum(i) // deferred function call: logNum(1) // fmt.Println("First main statement") // i++ // defer logNum(i) // deferred function call: logNum(2) // defer logNum(i * i) // deferred fu...
package main import ( "fmt" "os" ) func some() { defer fmt.Println("Hello World") // after completed this func, deal this defer fmt.Println("Hello Go") } // deferはファイルをopen, closeするときなどに便利下記のように使う func filehandler() { file, _ := os.Open("./main.go") defer file.Close() data := make([]byte, 100) file.Read(data...
package cmd import ( "fmt" "github.com/andytom/tmpltr/template" "github.com/spf13/cobra" ) func init() { RootCmd.AddCommand(installCmd) installCmd.Flags().BoolVarP(&force, "force", "f", false, "Force the installation of a template") } var force bool var installCmd = &cobra.Command{ Use: "install NAME DIR"...
package local import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/ubclaunchpad/inertia/cfg" ) func TestInitializeInertiaProjetFail(t *testing.T) { err := InitializeInertiaProject("", "", "") assert.NotNil(t, err) } func TestGetConfigFail(t *testing.T) { _, _, err := GetProjectConfigFromD...
/* Task: Given an integer input, figure out whether or not it is a Cyclops Number. What is a Cyclops number, you may ask? Well, it's a number whose binary representation only has one 0 in the center! Test Cases: Input | Output | Binary | Explanation -------------------------------------- 0 | truthy | 0 ...
package memphis import ( "context" "fmt" "github.com/memphisdev/memphis.go" "github.com/pkg/errors" "github.com/batchcorp/plumber-schemas/build/go/protos/opts" "github.com/batchcorp/plumber-schemas/build/go/protos/records" "github.com/batchcorp/plumber/util" "github.com/batchcorp/plumber/validate" ) func (m...
// Copyright 2021 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package definition import ( "fmt" "strings" "testing" "github.com/franela/goblin" ) // TestUnitPrometheus test cases func TestUnitPrometheus(t *testing.T) { g := g...
package main import ( "fmt" "reflect" ) func main() { a1 := [3]int{1, 2, 3} // array s1 := []int{1, 2, 3} // slice fmt.Println(a1, s1) fmt.Println(reflect.TypeOf(a1), reflect.TypeOf(s1)) a2 := [5]int{1, 2, 3, 4, 5} // Slice não é um array! Slide define um pedaço de um array. s2 := a2[1:3] fmt.Println(a2,...
// Package baremetal provides a cluster-destroyer for bare metal clusters. package baremetal
/* This blog post about generating random CSS color codes in JavaScript have multiple solutions for generating a random color in JavaScript. The shortest I can find is this: '#'+(Math.random()*0xffffff).toString(16).slice(-6) If you are not familiar with CSS color code read documentations here. Can we do better? Wh...
package postgres import ( "github.com/frk/gosql/internal/analysis" "github.com/frk/gosql/internal/postgres/oid" ) type compkey struct { oid oid.OID typmod1 bool } type compentry struct { valuer string scanner string } type comptable struct { literal2oid map[analysis.LiteralType]map[compkey]compentry oi...
package mysqladapter import "github.com/AlejandroWaiz/novels-box/internal/domain/structs" func (db *MySqlAdapter) GetAllNovelsInDB() (novels []structs.Novel, err error) { q := "SELECT * FROM `allnovels`" query, err := db.dbconn.Query(q) if err != nil { return nil, err } for query.Next() { var novel st...
/* * 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 common import "time" func GetNow() time.Time { return time.Now() } func GetTomorrow() time.Time { return time.Now().Add(time.Hour * 24) } func BeginingOfDay() time.Time { today := time.Now() year, month, day := today.Date() return time.Date(year, month, day, 0, 0, 0, 0, today.Location()) } func EndOfD...
package repository import ( "context" "fmt" "strings" "github.com/TodoApp2021/gorestreact/pkg/models" "github.com/jackc/pgx/v4/pgxpool" ) type TodoListPostgres struct { pool *pgxpool.Pool } func NewTodoListPostgres(pool *pgxpool.Pool) *TodoListPostgres { return &TodoListPostgres{pool: pool} } func (t *TodoL...
package main import ( "flag" "fmt" "github.com/randall77/hprof/read" ) func main() { flag.Parse() args := flag.Args() var d *read.Dump if len(args) == 2 { d = read.Read(args[0], args[1]) } else { d = read.Read(args[0], "") } // eliminate unreachable objects // TODO: have reader do this? reachable := ...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //789. Escape The Ghosts //You are playing a simplified Pacman game. You start at the point (0, 0), and your destination is (target[0], target[1]). The...
package leetcode func rotateString(A string, B string) bool { lA, lB := len(A), len(B) if lA != lB { return false } if lA == 0 { return true } for i := 0; i < lA; i++ { if A[i:] == B[:lA-i] && A[:i] == B[lA-i:] { return true } } return false }
package models import ( "errors" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "log" "strconv" "strings" ) type UPS struct { ID string Manufacturer string Model string Description string InWork bool Barcode string CurrentLocation string HistoryLocations [...
package frame import ( "fmt" "sync" "github.com/google/uuid" ) type PositionPolicy int const ( FloatFree PositionPolicy = iota // allowed to go anyway, even off the screen FloatForward // similar to free, except once it hits the bottom, it does not go off the screen (it makes more real...
package kdtree import ( "github.com/sephriot/kdtree/point2" "testing" ) func testTree() *KDTree { tree := New() tree.Add(point2.Point2{}) tree.Add(point2.Point2{X: 1}) tree.Add(point2.Point2{X: -1}) tree.Add(point2.Point2{Y: 2}) tree.Add(point2.Point2{Y: -2}) tree.Add(point2.Point2{X: -1, Y: -1}) tree.Add(p...
package realm_test import ( "testing" "github.com/10gen/realm-cli/internal/cli/user" "github.com/10gen/realm-cli/internal/cloud/realm" u "github.com/10gen/realm-cli/internal/utils/test" "github.com/10gen/realm-cli/internal/utils/test/assert" "github.com/10gen/realm-cli/internal/utils/test/mock" ) func TestReal...
package main import ( "awesomeProject/calculator/calculatorpb" "context" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "io" "log" ) func main() { fmt.Println("Calculator Client") cc, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) if err != nil { l...
package task8 import ( "io" ) type Rot13Reader struct { R io.Reader } func (r Rot13Reader) Read(p []byte) (n int, err error) { n, err = r.R.Read(p) for i := range p { switch { case p[i] >= 'A' && p[i] < 'N': fallthrough case p[i] >= 'a' && p[i] < 'n': p[i] += 13 case p[i] > 'M' && p[i] <= 'Z': ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-03-26 13:31 # @File : main.go # @Description : # @Attention : */ package main import ( "examples/blockchain/config" "fmt" "os" "os/signal" "syscall" ) func main() { yamlPath := "/Users/joker/go/src/examples/blockchain/raftorder_example/application-d...
package usermodel //User is represent the struct of the user in user collection type User struct { UID string `json:"uid"` //User id Nick string `json:"nickname"` //Nick name wich will display(for example in posts) Name string `json:"name"` //Actual Name Surname string `json:"surname"` //Ac...
package main import ( "fmt" "sort" "github.com/shirou/gopsutil/process" "github.com/shirou/gopsutil/cpu" ) type Process struct { pid int32 ppid int32 name string cmdline string status string createTime int64 cpuPercent float64 memPercent float32 numThreads int32 }...
package main import ( "fmt" "net" "strings" "time" "github.com/hashicorp/yamux" "github.com/payfazz/go-errors" "github.com/payfazz/go-errors/errhandler" "github.com/payfazz/stdlog" ) func runServer(addr string) { leftAddr := strings.SplitN(addr, ":", 2) if len(leftAddr) != 2 { showUsage() } leftListen...
// Copyright 2017 Vlad Didenko. All rights reserved. // See the included LICENSE.md file for licensing information package slops // import "go.didenko.com/slops" import ( "reflect" "testing" ) type uniqueUseCase struct { in []string expect []string } var uniqueTestScript = []uniqueUseCase{ {nil, []string{}...
package domain import "oneday-infrastructure/tools" type TenantRepo interface { InsertTenant(tenant Tenant) FindByName(tenantName string) (tenant Tenant, exist bool) GetByCode(tenantCode string) (tenant Tenant) InsertUser(user User) } type TenantService struct { TenantRepo } func InitTenantService(tenantRepo T...
package gherkin import ( re "regexp" "io" "reflect" "strconv" ) type stepdef struct { r *re.Regexp f interface{} } func (s stepdef) call(w *World) { t := reflect.TypeOf(s.f) in := make([]reflect.Value, t.NumIn()) in[0] = reflect.ValueOf(w) if len(in) != len(w.regexParams) + 1 ...
package main import ( "net/http" "html/template" "errors" "log" ) // check if the user is currently logged in func isLoggedIn(writer http.ResponseWriter, request *http.Request)(authenticated bool){ cookie, err := request.Cookie("chitchat_cookie") if err == http.ErrNoCookie { http.Redirect(writer, requ...
package component // Position component. type Position struct { X, Y float64 } // NewPosition position constructor. func NewPosition(x, y float64) *Position { return &Position{x, y} } // Name component implementation. func (c *Position) Name() string { return "position" }
package gox import ( "encoding/json" "io/ioutil" "os" ) type KeyValueStoreFile struct { Values map[string]string Path string } func NewDiskCache(filename string) (*KeyValueStoreFile, error) { cache := new(KeyValueStoreFile) cache.Path = filename err := cache.Load() if err != nil { return nil, err } ...
package operator import ( "testing" ) func TestForStatement(t *testing.T) { number := []int{11, 12, 13, 14, 15, 16} for i := range number { if i == 3 { number[i] |= i } t.Log(i) } t.Log(number) } // range表达式只会在for语句开始执行时被求值一次,无论后边会有多少次迭代; // range表达式的求值结果会被复制,也就是说,被迭代的对象是range表达式结果值的副...
// Copyright 2016 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 limitutil import ( "balansir/internal/configutil" "sync" "time" "golang.org/x/time/rate" ) type visitor struct { limiter *rate.Limiter lastSeen time.Time } //Limiter ... type Limiter struct { mux sync.RWMutex list map[string]*visitor } var limiter *Limiter var once sync.Once //GetLimiter ... fun...
package main import ( "bufio" "fmt" "math/rand" "os" "time" ) type World struct { Cells []int Width int } func NeweWorld(width int, density float64) *World { cells := make([]int, width) for i, _ := range cells { if rand.Float64() < density { cells[i] = rand.Intn(19) - 9 } } return &World{ Cells...
package _230_Kth_Smallest_Element_in_a_BST /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func kthSmallest(root *TreeNode, k int) int { var ( s = []*TreeNode{} node = root count int ) for node != nil || len(s) > 0 {...
package service import ( "time" "github.com/pkg/errors" "github.com/shharn/blog/logger" "github.com/shharn/blog/model" "github.com/shharn/blog/repository" "github.com/shharn/blog/session" ) var ( InvalidEmailOrPasswordError = errors.New("Invalid email or password") SessionCreationFailureError = errors.New("F...
package main import ( "errors" "time" sj "github.com/bitly/go-simplejson" "github.com/donnie4w/go-logger/logger" "job" ) type Workshop struct { sub string // 业务的名字,打日志时有用 ctx *sj.Json sleepWhenNeed bool // 当机器不健康时消极怠工 ctrlChan chan int // [0] unis -> channel -> control reportChan cha...
package main import ( "fmt" "os" "bufio" "strings" "strconv" ) const filePath = "input.txt" const length = 85 func main(){ firewall := parseInput() i := 0 //loop forever until an attempt with delay i gets through for ; attemptRun(firewall,i); i++ { } fmt.Println(i) } func attemptRun(fw [][]int, delay int...
package dtx import ( "fmt" "strings" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/pkg/errors" ) func TestRunInTransactionSucceed(t *testing.T) { if err := setup(); err != nil { t.Fatalf("%v", err) } key := newKey(integHashTableName) item := ma...
// Package sqlfly can make writing sql fast flying package sqlfly
package model type TODOListID string type ListItemID string type TODOList struct { ID TODOListID Owner UserID Items []*ListItem } type ListItem struct { ID ListItemID Text string } type UserID string type User struct { ID UserID Name string YandexAvatarID string } type AccessMode...
package test import ( "common/tbhandler" "crypto/md5" "encoding/hex" "fmt" "reflect" "regexp" "strconv" "strings" "time" _ "github.com/go-sql-driver/mysql" //驱动包 "github.com/kdada/tinygo" "github.com/narrowizard/tinysql" ) type Result struct { Info reflect.Value less func(x, y reflect.Value) bool Co...
package run import floc "gopkg.in/workanator/go-floc.v1" func getCounter(state floc.State) int { data, locker := state.DataWithReadLocker() counter := data.(*int) locker.Lock() defer locker.Unlock() return *counter } func updateCounter(flow floc.Flow, state floc.State, key string, value interface{}) { data, ...
package user import ( "github.com/globalsign/mgo/bson" ) func (userModel *UserModel) UnSubUser(uid bson.ObjectId, unSubUid bson.ObjectId) (err error) { c := userModel.GetC() defer c.Database.Session.Close() err = userModel.removeAttention(uid, unSubUid) if err != nil { return } return userModel.removeFans(...
package main import "fmt" func reverse(s []int) { for i, j := 0, len(s)-1; i<j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func rotate(s []int, i int) { reverse(s[:i]) reverse(s[i:]) reverse(s) } func rotation(s []int, i int) { /* write a version of roate that operaties in one pass */ ...
// Copyright Fuzamei Corp. 2018 All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "fmt" "os" "path/filepath" "github.com/33cn/chain33/types" _ "github.com/GM-Publicchain/gm/plugin/crypto/init" "github.com/GM-Public...
package main import ( "fmt" "net" "github.com/zc409/gostudy/day8/solve_stickybag/protocol" ) func main() { con, err := net.Dial("tcp", "127.0.0.1:30000") if err != nil { fmt.Printf("connect to server wrong,err:%v\n", err) return } mes := "this is test!" mess, err := protocol.Encode(mes) //调用自定义protocol包编...
package main import "fmt" func main() { var value = (((6+2)%3)*4 - 2) / 3 var isEqual = (value == 2) fmt.Printf("result %d (%t) \n", value, isEqual) }
/* Left in sandbox for at least 3 days. I want to verify if this inequality is true: for n≥4, if a1,a2,a3,…,an∈R+∪{0} and ∑ni=1ai=1, then a1a2+a2a3+a3a4+⋯+an−1an+ana1≤1/4. Challenge Write a piece of program which takes an integer n as input. It does the following: Generate a random array a which consists of n ...
package main import ( "fmt" "os" ) func main() { // 获取命令行参数 args := os.Args for i, item := range args { fmt.Printf("args[%d] = %s\n", i, item) } // 首先build文件,使其构建成可执行文件,即: // go build command_args.go // 然后执行并输入参数,即: // command_args.exe 10 20 // 结果为: // args[0] = command_args.exe // args[1] = 10 //...
package fmm import ( "encoding/json" "errors" "fmt" "strconv" "strings" ) type Version [4]uint16 type VersionCmpRes uint8 const ( VersionAny VersionCmpRes = iota // 000 VersionEq // 001 VersionGt // 010 VersionGtEq // 011 VersionLt ...
package main import ( "fmt" "reflect" ) // type save like interface type Doctor struct { number int actorName string companions []string } type Animal struct { Name string Origin string } type Bird struct { Animal SpeedKPH float32 Canfly bool } type BirdDescription struct { Name string `requi...
package pathfileops import ( "errors" "fmt" "strings" ) // FileOpsCollection - A collection of files and file operations which are designed // to perform specific actions on disk files. // type FileOpsCollection struct { fileOps []FileOps } // AddByFileOps - Adds a FileOps object to the existing collection /...
package list import ( "fmt" "testing" "github.com/influxdata/influxdb/pkg/testing/assert" ) var testNormalArray = []interface{}{1, 2, 3, 4, 5, 6, 7, 8} var testEmptyArray = []interface{}{} var testSingleValueArray = []interface{}{0} func insertNodes(arr []interface{}) *CircularList { circularList := &CircularLi...
package coordinator import "sync" type BackItem struct { value interface{} switch_value string } type BackQueue struct { sync.RWMutex items []*BackItem elemsCount int } func newBackItem(value interface{}, switch_value string) *BackItem { return &BackItem{ value: value, switch_value: swi...
package dao import "fmt" func Mysqltest() { fmt.Println("ggg") }
package main import ( "flag" "log" "os" "github.com/thefirstofthe300/ekg/dns" "github.com/thefirstofthe300/ekg/fmt" "github.com/thefirstofthe300/ekg/processes" "github.com/thefirstofthe300/ekg/route" ) func main() { outptr := os.Stdout help := flag.Bool("help", false, "Display this help dialog and exit.")...
package session import ( "context" "errors" ) var sessionKey = struct { value string }{"sessionKey"} type Session struct { ID int `json:"id"` Email string `json:"email"` } func (s *Session) Set(ctx context.Context) context.Context { return context.WithValue(ctx, sessionKey, s) } func (s *Session) HasPe...
package enter import ( "strings" "time" "github.com/devspace-cloud/devspace/cmd" "github.com/devspace-cloud/devspace/cmd/flags" "github.com/devspace-cloud/devspace/e2e/utils" "github.com/devspace-cloud/devspace/pkg/util/log" "github.com/pkg/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) //1. enter -...
package api import ( "net/http" "github.com/Zenika/marcel/api/auth" "github.com/Zenika/marcel/api/commons" ) func validateHandler(w http.ResponseWriter, r *http.Request) { if auth := auth.GetAuth(r); auth == nil { commons.WriteResponse(w, http.StatusForbidden, "") } } func validateAdminHandler(w http.Respons...
package content import ( "errors" ) // Errors var ( ErrDatastoreDoneContentID = errors.New("Datastore done at PageContent") ErrDatastoreDoneContent = errors.New("Can't find any content for given content " + "id.") ) // en-us, en-au, en-ca, tr... type Language struct { ID string `datastore:"-"`...
package main import ( "fmt" "log" "net/http" "github.com/aiden0z/go-jwt-middleware" "github.com/dgrijalva/jwt-go" "github.com/facebookgo/inject" "github.com/gorilla/mux" "github.com/jessevdk/go-flags" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/hirondelle-app/api/api"...
/* * * Copyright 2015 gRPC 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 agree...
// Copyright 2015 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...
/* I am interested in seeing programs which don't ask for any input, print a googol copies of some nonempty string, no less, no more, and then stop. A googol is defined as 10100, i.e., 1 followed by a hundred 0's in decimal. Example output: 111111111111111111111111111111111111111111111111111111111111111111111111... ...
package main import ( "fmt" "time" ) var ch1 chan int = make(chan int, 3) func task1() { var x int = 0 fmt.Println("call task1") for { time.Sleep(1000 * time.Millisecond) fmt.Printf("task1 send message:%d\r\n", x) ch1 <- (x) ch1 <- (x + 1) ch1 <- (x + 2) x += 3 } } func task2() { var x int for {...
package file_producer_controller import ( "github.com/gin-gonic/gin" "github.com/google/uuid" log "github.com/sirupsen/logrus" "github.com/yjagdale/siem-data-producer/models/file_producer_model" "github.com/yjagdale/siem-data-producer/models/logs_model" "github.com/yjagdale/siem-data-producer/services/file_produ...
package web import ( "fmt" "io/ioutil" "net/http" "database/sql" "github.com/gorilla/mux" ) // HTTPRouter is a structure used for all incoming and outgoing HTTP // requests/calls in the services type HTTPRouter struct { router *mux.Router pathPrefix string } // NewHTTPRouter construc...
package main import ( "bytes" "net/http" "net/http/httptest" "testing" zsweb "github.com/zerostick/zerostick/daemon/web" //_ "github.com/zerostick/zerostick/daemon" ) func TestPushoverGetEmptyWeb(t *testing.T) { req, err := http.NewRequest("GET", "/notifications/provider/pushover", nil) if err != nil { t.F...
// 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. // collect-statse implements continuous statistical aggregation of cluster event metrics. package main import ( "log" "opentsp.org/cmd/collect-sta...
package main import ( "fmt" ) func main() { for i := 0; i <= 12; i++ { for j := 0; j <= 12; j++ { fmt.Printf("%d x %d = %d\n", i, j, i * j) } } }
package main import ( "fmt" "os" "github.com/Cloud-Foundations/Dominator/imagebuilder/client" "github.com/Cloud-Foundations/Dominator/lib/json" "github.com/Cloud-Foundations/Dominator/lib/log" proto "github.com/Cloud-Foundations/Dominator/proto/imaginator" ) func getDependenciesSubcommand(args []string, logger...
package config const apiAddr = "http://backend-api:8080/api" const execAddr = "http://backend-exec:8090/exec" func GetAPIAddr() string { return apiAddr } func GetExecAddr() string { return execAddr }
package models import ( "encoding/json" "fmt" ) // Endpoint : model SslResponse type Endpoint struct { Address string `json:"ipAddress"` Grade string `json:"grade"` Country string `json:"country"` Owner string `json:"owner"` } // Endpoints : model SslResponse type Endpoints struct { Endpoints []Endpoint `...
package strategy import "math/rand" func randomLevel() int { level := 1 for rand.Float32() < p && level < maxLevel { level++ } return level }
package kbucket import ( "container/list" "sort" peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer" ) // A helper struct to sort peers by their distance to the local node type peerDistance struct { p peer.ID distance ID } // peerSorterArr implements sort.Interface to sort peers...
/* * AppManager API * * HTTP REST API to connect to the AppManager * * API version: 1.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package appManagerApiClient type DeploymentSpec struct { State string `json:"state"` Up...
// This file was generated for SObject EventBusSubscriber, API Version v43.0 at 2018-07-30 03:47:55.497737848 -0400 EDT m=+41.841914304 package sobjects import ( "fmt" "strings" ) type EventBusSubscriber struct { BaseSObject ExternalId string `force:",omitempty"` Id string `force:",omitempty"` LastErro...
package utils import ( "fmt" "runtime" ) func FileLine(errors ...error) string { _, file, line, ok := runtime.Caller(1) if ok { return fmt.Sprintf("[%s:%d]% v", file, line, errors) } else { return "unknown" } }