text
stringlengths
11
4.05M
// Package logr defines abstract interfaces for logging. Packages can depend on // these interfaces and callers can implement logging in whatever way is // appropriate. // // This design derives from Dave Cheney's blog: // http://dave.cheney.net/2015/11/05/lets-talk-about-logging // // This is a BETA grade API. U...
package transfer import ( "context" "errors" "github.com/juntaki/transparent" "github.com/juntaki/transparent/simple" pb "github.com/juntaki/transparent/transfer/pb" "google.golang.org/grpc" ) type transmitter struct { converter client pb.TransferClient serverAddr string conn *grpc.ClientConn } ...
// 18 august 2014 package ui type windowDialog interface { openFile(f func(filename string)) } // OpenFile opens a dialog box that asks the user to choose a file. // The dialog box is modal to win, which mut not be nil. // Some time after the dialog box is closed, OpenFile runs f on the main thread, passing filenam...
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" ) // PotentialGuest is a struct to capture a guest from request before he added to guest list type PotentialGuest struct { Table int `json:"table"` AccompaniyingGuests int `json:"accompanyin...
package proc import ( "context" "encoding/json" "github.com/aberic/gnomon" "github.com/aberic/gnomon/log" "github.com/aberic/proc/protos" "google.golang.org/grpc" "io/ioutil" "time" ) var ( proc *Proc host string scheduled *time.Timer // 超时检查对象 delay time.Duration stop chan struct{} //...
package main import ( "sync" "time" ) const ( CHECK_FAIL = 0 CHECK_OK ) type CheckResult int type HealthCheck struct { LastCheck time.Time LastCheckResult CheckResult } type EndpointEntry struct { Host string `json:"hostname"` Port int `json:"port"` Url string `json:"ur...
package utils type SliceConstraint interface { int | int64 | string } type R[T SliceConstraint] []T // slice去除重复数据 func RemoveRespSlice[S SliceConstraint](req []S) []S { if len(req) == 0 { return nil } result := make(R[S], 0) temp := map[S]struct{}{} for _, val := range req { if _, ok := temp[val]; !ok { ...
package greeting import "fmt" func Greeting(txt string) string { return fmt.Sprintf("<b>%s</b>", txt) }
package main import "fmt" // go 运算符 和其他语言一样 // 假定 A 值为 10,B 值为 20 //+ 相加 A + B 输出结果 30 //- 相减 A - B 输出结果 -10 //* 相乘 A * B 输出结果 200 /// 相除 B / A 输出结果 2 //% 求余 B % A 输出结果 0 //++ 自增 A++ 输出结果 11 //-- 自减 A-- 输出结果 9 func main() { var a bool = true var b bool = true if a && b { fmt.Printf("第一行 - 条件为 true\n") } if a ...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package productivitycuj import ( "context" "fmt" "regexp" "strconv" "strings" "time" "chromiumos/tast/common/action" "chromiumos/tast/errors" "chromiumos/tast/loca...
package helm import ( "fmt" "os" "github.com/onsi/ginkgo" "helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/chart/loader" "helm.sh/helm/v3/pkg/cli" "helm.sh/helm/v3/pkg/release" "helm.sh/helm/v3/pkg/storage/driver" "helm.sh/helm/v3/pkg/strvals" ) var ( logf = ginkgo.GinkgoT().L...
// tiger插件,一个脚手架工具,用于来初始化一个Tigo项目 package main import ( "Tigo/TigoWeb" "fmt" "io/ioutil" "os" "os/exec" "strings" ) const ( DemoCode = `package main import ( "github.com/karldoenitz/Tigo/TigoWeb" ) // HelloHandler it's a demo handler type HelloHandler struct { TigoWeb.BaseHandler } // Get http get meth...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package firmware import ( "context" "encoding/json" "fmt" "regexp" "sort" "strings" "time" "github.com/golang/protobuf/ptypes/empty" "github.com/google/go-cmp/cmp"...
package connector import ( gp "code.google.com/p/goprotobuf/proto" "common" "errors" "logger" "pockerclient" "proto" "rpc" "time" ) //创建函数 type CreateMsgFun func() gp.Message var mapRpc map[string]CreateMsgFun //消息回调用 func init() { mapRpc = make(map[string]CreateMsgFun) // mapRpc["Notice"] = func() gp.Me...
package lc // Time: O(1) for SumRange() // Benchmark: 56ms 9.6mb | 37% 17% type NumArray struct { sums []int } func Constructor(nums []int) NumArray { if len(nums) == 0 { return NumArray{[]int{}} } // precalculate the sums. sums := make([]int, len(nums)) sums[0] = nums[0] for i := 1; i < len(nums); i++ { ...
package psql import ( "fmt" "github.com/OIT-ads-web/widgets_import" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" "log" ) var Database *sqlx.DB func GetConnection() *sqlx.DB { return Database } func MakeConnection(conf widgets_import.Config) error { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ "pa...
package config var ( CosmosRPCHost = "localhost:9090" )
package sqlstore import ( "github.com/imflop/clnk/internal/app/models" uuid "github.com/satori/go.uuid" "time" ) // LinkRepository ... type LinkRepository struct { store *Store } // Create ... func (r *LinkRepository) Create(originalURL string) (*models.Link, error) { l := &models.Link{} u := uuid.NewV4() dat...
// Copyright 2021 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package tests import ( "testing" "github.com/muhammadandikakurniawan/training_go_salt/packages" ) func TestLengthOfLongestSubstring(t *testing.T) { packages.LengthOfLongestSubstring("abba") }
package web3 import ( "github.com/tharsis/ethermint/version" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" ) // PublicAPI is the web3_ prefixed set of APIs in the Web3 JSON-RPC spec. type PublicAPI struct{} // NewPublicAPI creates an instance of the Web3 API. func NewP...
//Copyright 2019 Chris Wojno // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribut...
package DataBase import ( "../../../bin/gorm" "fmt" "errors" "log" "../DTO" _ "../../../bin/pq" ) var DatabaseConnection *gorm.DB //database const ( DB_USER = "postgres" DB_PASSWORD = "postgres" DB_NAME = "postgres" ) func init () { log.Print("connecting to Data Base Postgresql") err:=err...
package http import ( "net" "strings" "github.com/caos/logging" ) func CreateListener(endpoint string) net.Listener { l, err := net.Listen("tcp", Endpoint(endpoint)) logging.Log("SERVE-6vasef").OnError(err).Fatal("creating listener failed") return l } func Endpoint(endpoint string) string { if strings.Contai...
package cmd import ( "bufio" "github.com/qwenode/gogo/sanitize" "io/ioutil" "os/exec" ) // commandFunc call by CommandFn type commandFunc func(output string, errCode int) bool // CommandFn run exec.command(name,arg...).CombinedOutput() func CommandFn(fn commandFunc, name string, arg ...string) bool { output, er...
package main import ( "flag" "fmt" "github.com/thejerf/afibmon/heartmon" "github.com/thejerf/suture" ) var address = flag.String("address", ":18498", "the address to bind the server to") func main() { flag.Parse() supervisor := suture.NewSimple("heartmon supervisor") server, err := heartmon.NewServer(*addr...
package interactor import ( "github.com/gobjserver/gobjserver/core/entity" "github.com/gobjserver/gobjserver/core/gateway" ) // GetObjectInteractor . type GetObjectInteractor interface { Get(objectName string) []*entity.Object GetByObjectID(objectName string, objectID string) (*entity.Object, error) GetAll() ([]...
/* vim:set sw=8 ts=8 noet: * * Copyright (c) 2017 Torchbox Ltd. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely. This software is provided 'as-is', without any express or implied * warranty. */ package m...
package database import ( "bytes" "encoding/json" "fmt" "github.com/boltdb/bolt" ) //DB , database struct type DB struct { conn *bolt.DB } //Datastore , db interface type Datastore interface { CreateBuckets(bucket string) error CreateSubBuckets(mBucket, sBucket string) error AddRecord(bucket, key string, v ...
package urlpath_test import ( "fmt" "testing" "github.com/ehsoc/urlpath" ) type DiffTests struct { root, path, want string err bool } var diffChildTests = []DiffTests{ {"/abc/def", "/abc/def", "", false}, {"/abc/def", "/abc/def/ghijklmn/opqrstuvwyz1234", "/ghijklmn/opqrstuvwyz1234", false}, {"/...
package runtime import ( "strconv" ) // Signed integer data type type Int int func (v Int) Eq(other Value) bool { return v == other } func (v Int) Gt(other Value) bool { y, ok := other.(Int) if ok == false { return v.Type() > other.Type() } return v > y } func (v Int) Lt(other Value) bool { y, ok := othe...
package main import ( "database/sql" "log" "github.com/mylxsw/container" "github.com/mylxsw/container/example/repo" _ "github.com/proullon/ramsql/driver" ) type Demo struct { UserRepo repo.UserRepo `autowire:"@"` roleRepo repo.RoleRepo `autowire:"@"` // 支持 private 字段 } func main() { cc := container.New() ...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package cellular provides functions for testing Cellular connectivity. package cellular import ( "context" "io/ioutil" "math/rand" "net" "os" "path/filepath" "strc...
package Maximum_Repeating_Substring import "testing" func Test_maxRepeating(t *testing.T) { type args struct { sequence string word string } tests := []struct { name string args args want int }{ // TODO: Add test cases. { "case", args{ sequence: "bbbbbb", word: "bb", }, 3...
package main import ( "io" "net/http" ) type gyan struct{} func (g gyan) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/dog/": io.WriteString(w, "dog ... woof") case "/cat": io.WriteString(w, "Cat ... Meow") } } func main() { var g gyan myMux := http.NewServeMux() myMux...
package sync import ( "fmt" "log" "strings" ) // MustParseAll parse sync string or fail with Fatal func MustParseAll(strings []string) (result []Sync) { for _, str := range strings { sync, err := Parse(str) if err != nil { log.Fatalf("Invalid formated sync [%s], must be in format: '<source>:<destination>',...
package main /* Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" Corner Cases: Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' ...
package requests import ( "net/url" "github.com/atomicjolt/canvasapi" ) // HideAllStreamItems Hide all stream items for the user // https://canvas.instructure.com/doc/api/users.html // type HideAllStreamItems struct { } func (t *HideAllStreamItems) GetMethod() string { return "DELETE" } func (t *HideAllStreamIt...
package main import ( "fmt" ) // START OMIT func main() { a1 := [...]int{1, 2, 3} s1 := a1[0:2] // same as s1 := a1[:2] var s2 []int // len == 0, cap == 0, s2 == nil s3 := make([]int, 2) // len == 2, cap == 2. Same as make([]int,2,2) s1 = append(s1, 5) s2 = append(s2, 5) s3 = append(s3, 5) ...
package config import ( "github.com/google/wire" "github.com/spf13/viper" ) // Init 初始化viper func New() (*viper.Viper, error) { var ( err error v = viper.New() ) v.SetEnvPrefix("IOJ") err = v.BindEnv("host") if err != nil { return nil, err } v.SetDefault("host", "http://10.20.107.171:2333") retu...
package model import ( "time" "github.com/satori/go.uuid" ) // List is a struct representing a TODO list type List struct { UUID uuid.UUID `db:"uuid" json:"list_uuid"` Name string `db:"name" json:"list_name"` Owner string `db:"owner" json:"owner"` Tasks *[]*Task `json:"tasks"` Created...
package user import ( "fmt" userModel "go_simpleweibo/app/models/user" "go_simpleweibo/app/requests" "go_simpleweibo/pkg/flash" "github.com/gin-gonic/gin" ) type UserLoginForm struct { Email string Password string } // Validate : 验证函数 func (u *UserLoginForm) Validate() (errors []string) { errors = reque...
package utils import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/sha1" "encoding/base64" "encoding/binary" "encoding/json" "encoding/xml" "fmt" "io" "io/ioutil" "log" "math/rand" "net/http" "sort" "strings" "time" ) type WXAccessToken struct { ErrorCode int `json:"errorcode"` Errmsg st...
package main import ( "fmt" "time" ) func printText() { for i:=0; i<5; i++ { fmt.Println("text", i) time.Sleep(500 * time.Millisecond) } } func printNumber() { for i:=0; i<5; i++ { fmt.Println(i) time.Sleep(200 * time.Millisecond) } } func main() { start := time.Now() go printNumber() go printText...
// Copyright 2020 The VectorSQL Authors. // // Code is licensed under Apache License, Version 2.0. package xlog import ( "testing" ) func Assert(tb testing.TB, condition bool, msg string, v ...interface{}) { if !condition { tb.FailNow() } } func TestGetLog(t *testing.T) { GetLog().Debug("DEBUG") log := NewSt...
package util import ( "fmt" "reflect" "strings" "time" "github.com/appscode/go/log" "github.com/appscode/go/types" snapshot_cs "github.com/kubernetes-csi/external-snapshotter/pkg/client/clientset/versioned" core "k8s.io/api/core/v1" kerr "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/a...
package tun2socks import ( "log" "net" "os" "os/signal" "syscall" "github.com/FlowerWrong/tun2socks/configure" "github.com/FlowerWrong/tun2socks/util" ) func (app *App) SignalHandler() *App { // signal handler c := make(chan os.Signal) signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, sysc...
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-present Datadog, Inc. package override import ( "testing" "github.com/DataDog/datadog-opera...
package main import exam "gitee.com/erdanli/ipproxypool/internal/examination" func main() { // avaliableProxyIP, _ := exam.TestJiangXianLi() // _, _, result := storage.MangoDB() exam.DeleteUnavailableProxyIP() }
package metrics import ( "net/url" "github.com/cerana/cerana/acomm" "github.com/cerana/cerana/pkg/errors" "github.com/shirou/gopsutil/mem" ) // MemoryResult is the result for the Memory handler. type MemoryResult struct { Swap *mem.SwapMemoryStat `json:"swap"` Virtual *mem.VirtualMemoryStat `json:"virtua...
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package network import ( "context" "time" "github.com/golang/protobuf/ptypes/empty" "chromiumos/tast/common/network/diag" "chromiumos/tast/errors" "chromiumos/tast/r...
package api import ( "encoding/json" "net/http" "github.com/adi/sketo/db" ) func alive(acpDB *db.DB) func(rw http.ResponseWriter, r *http.Request) { return func(rw http.ResponseWriter, r *http.Request) { rw.Header().Add("Content-Type", "application/json") jsonEnc := json.NewEncoder(rw) rw.WriteHeader(200) ...
package bank1 var deposits = make(chan int) // send amount to deposits var balances = make(chan int) // receive balane var withdrawRes = make(chan bool) var withdraw = make(chan withdrawMes) // send amount to withdraw type withdrawMes struct { ch chan bool amount int } func Deposit(amount int) { deposits <- am...
package model type harbors map[string]Harbor // Harbor is a Catan harbor, consisting out of a simple name, and the resource it has the trade benefit for type Harbor struct { Name string Resource } var ( HarborGrain = &Harbor{Name: "2:1 Grain", Resource: *Grain} HarborBrick = &Harbor{Name: "2:1 Brick", Resource...
// Copyright 2020 The LUCI 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...
// Copyright 2020 Insolar Network Ltd. // All rights reserved. // This material is licensed under the Insolar License version 1.0, // available at https://github.com/insolar/block-explorer/blob/master/LICENSE.md. // +build heavy_mock_integration package api import ( "testing" "github.com/insolar/block-explorer/te...
// Copyright 2020 Insolar Network Ltd. // All rights reserved. // This material is licensed under the Insolar License version 1.0, // available at https://github.com/insolar/block-explorer/blob/master/LICENSE.md. // +build unit package belogger import ( "bytes" "encoding/json" "runtime" "strconv" "testing" "g...
// Copyright (C) 2017 Google 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 t...
package main import "fmt" /* - Utiliza o formato key:value. - E.g. nome e telefone - Performance excelente para lookups. - map[key]value{ key: value } - Acesso: m[key] - Key sem value retorna zero. Isso pode trazer problemas. - Para verificar: comma ok idiom. - v, ok := m[key] - ok é um boolean, true/false - ...
/* Copyright 2016 - Jaume Arús Author Jaume Arús - jaumearus@gmail.com Licensed to the 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. The ASF licenses this file to you under t...
package model import ( "github.com/jinzhu/gorm" _"github.com/go-sql-driver/mysql" "github.com/siliconvalley001/wen/user/setting" "fmt" ) var ( DB *gorm.DB err error ) type AllConfig struct { } func init(){ if _,err:=setting.InitSetting();err!=nil{ panic(err) } fmt.Println(setting.Con.Mys.Name) DB,err=go...
package msgraph import ( "encoding/json" "fmt" "time" ) // globalSupportedTimeZones represents the instance that will be initialized once on runtime // and load all TimeZones form Microsoft, correlate them to IANA and set proper time.Location var globalSupportedTimeZones supportedTimeZones // supportedTimeZones r...
package cpool import ( "errors" "github.com/toolkits/consistent" "github.com/toolkits/file" "github.com/toolkits/logger" "github.com/toolkits/rpool/conn_pool" "strings" "sync" ) type RingBackend struct { sync.RWMutex Addrs map[string][]string Ring *consistent.Consistent Pools map[string]*conn_pool.ConnPoo...
// Copyright 2018 The go-Dacchain Authors // This file is part of the go-Dacchain library. // // The go-Dacchain library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License...
//obnoxious teenager responds to comments/questions package bob import ( "strings" "unicode" ) func IsUpper(s string) bool { for _, r := range s { if !unicode.IsUpper(r) && unicode.IsLetter(r) { return false } } return true } // Response based on input func Hey(input string) string { upper := IsUpper(i...
package dao import ( "mall/app/api/web/wechat/model" "github.com/jinzhu/gorm" ) func (d *Dao) QueryMcGroupsOne(p model.McGroupsQuery) (*model.McGroups, error) { db := d.parseMcGroupsQuery(p) var g model.McGroups err := db.First(&g).Error if err != nil { return nil, err } return &g, nil } func (d *Dao) ...
package odoo import ( "fmt" ) // Base represents base model. type Base struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` DisplayName *String `xmlrpc:"display_name,omptempty"` Id *Int `xmlrpc:"id,omptempty"` } // Bases represents array of base model. type Bases []Base // BaseModel is th...
package core import ( "github.com/golang/glog" "github.com/mefuwei/wdns/storage" "github.com/miekg/dns" "net" "strconv" ) const ( resovePath = "/etc/resolv.conf" ) var ( defaultServers = []string{"114.114.114.114"} defaultPort = 53 // TODO used config storageType = "redis" redisAddr = "localhost:637...
package oas3 import ( "bytes" "fmt" "log" "net/http" "net/textproto" "strings" "github.com/getkin/kin-openapi/openapi3" "github.com/SVilgelm/oas3-server/pkg/utils" "github.com/gorilla/mux" ) type response struct { http.ResponseWriter buf *bytes.Buffer statusCode int } func (w *response) WriteHe...
package p16 import ( "testing" ) func TestDance(t *testing.T) { tests := []struct { Input string Key string Result string }{ { Input: "@t.txt", Key: "abcde", Result: "baedc", }, { Input: "@a.txt", Key: "abcdefghijklmnop", Result: "cknmidebghlajpfo", }, } for i, test :...
package kafka_test import ( "context" "fmt" "time" "github.com/Shopify/sarama" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/sirupsen/logrus" ) var _ = Describe("Kafka", func() { Context("admin test", func() { It("create topic", func() { topicDetail := &sarama.TopicDetail{ NumPar...
package builder import ( "context" "net" "net/http" "net/http/httptest" "os" "path/filepath" "testing" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/registry" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/la...
package main import ( "fmt" ) func main() { // grade1 := 97 // grade2 := 85 // grade3 := 93 // fmt.Printf("Grades: %v, %v, %v \n", grade1, grade2, grade3) // ----------------------------------------------------------- // grades := [3]int{97, 85, 93} // fmt.Printf("Grades: %v \n", grades) // --------------...
package middleware import ( "strings" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) // The SkipperFunc signature, used to serve the main request without logs. // See `Configuration` too. type ( SkipperFunc = middleware.Skipper ) // DefaultSkipper returns false which processes the midd...
// +build cairo package expr import ( "testing" "time" ) func TestEvalExpressionGraph(t *testing.T) { now32 := int32(time.Now().Unix()) tests := []evalTestItem{ { &expr{ target: "threshold", etype: etFunc, args: []*expr{ {val: 42.42, etype: etConst}, }, argString: "42.42", }, ...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package intel import ( "context" "net/http" "net/http/httptest" "time" "chromiumos/tast/common/perf" "chromiumos/tast/local/chrome" "chromiumos/tast/local/media/devt...
package main import ( "fmt" "github.com/plunder-app/plunder/pkg/parlay/parlaytypes" ) func (e *etcdMembers) generateActions() []parlaytypes.Action { var generatedActions []parlaytypes.Action var a parlaytypes.Action if e.InitCA == true { // Ensure that a new Certificate Authority is generated // Create acti...
package _2_Abstract_Factory_Pattern import ( "reflect" "testing" ) //步骤 8 //使用 FactoryProducer 来获取 AbstractFactory,通过传递类型信息来获取实体类的对象。 func TestAbstractFactoryPattern(t *testing.T) { tests := []struct { name string args string want string }{ {"color", "color", "color"}, {"Shape", "Shape", "Shape"}, } ...
// 写真・スケッなどのイメージデータを取り込む // 対象フォルダに有るイメージファイルを、ファイル名を和名として取り込む。 // 該当の和名が存在しない場合は、ログを出力して継続する package main import ( "database/sql" "flag" "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" _ "github.com/mattn/go-sqlite3" ) //TODO 実行時の環境を引数で受け取れるように! const dbDir = "../../../db/" const imageDir = dbDir +...
package telemetry import ( rudder "github.com/rudderlabs/analytics-go" ) // rudderDataPlaneURL is set to the common Data Plane URL for all Mattermost Projects. // It can be set during build time. More info in the package documentation. var rudderDataPlaneURL = "https://pdat.matterlytics.com" // rudderWriteKey is se...
package main // Leetcode 333. (medium) func largestBSTSubtree(root *TreeNode) int { _, _, _, res := dfsLargestBSTSubtree(root) return res } func dfsLargestBSTSubtree(root *TreeNode) (bool, int, int, int) { if root == nil { return true, 1 << 31, -1 << 31, 0 } if root.Left == nil && root.Right == nil { return ...
package auth0 import ( "fmt" "net/url" "kolihub.io/koli/pkg/apis/authentication" "kolihub.io/koli/pkg/request" ) type AuthenticationInterface interface { ClientCredentials(token *authentication.Token) (*authentication.Token, error) } type ManagementInterface interface { Users() UserInterface } func NewForCo...
// Copyright (c) 2016-2019 Uber 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...
package command import "github.com/goodmustache/pt/command/display" type UserList struct { Config Config UI UI } func (cmd UserList) Execute(_ []string) error { configuredUsers, err := cmd.Config.GetUsers() if err != nil { return err } users := []display.UserRow{} for _, user := range configuredUsers {...
package exchange import ( . "ftnox.com/common" . "ftnox.com/config" "ftnox.com/auth" "github.com/jaekwon/GoLLRB/llrb" //"github.com/davecgh/go-spew/spew" "net/http" "time" "fmt" ) // Simplified order for orderbook API type SOrder struct { Amount uint64 `json:"a"` Price ...
package cmd import ( "testing" "github.com/flix-tech/confs.tech.push/confs" ) func TestFormatLocationAddsFlag(t *testing.T) { location := formatLocation(confs.Conference{ Name: "Go two", URL: "https://go2.com/", StartDate: "2019-08-21", EndDate: "2019-08-21", City: "Mariupol", Countr...
// Copyright 2022 Saferwall. All rights reserved. // Use of this source code is governed by Apache v2 license // license that can be found in the LICENSE file. package trid import ( "path" "path/filepath" "reflect" "runtime" "testing" ) func getAbsoluteFilePath(testfile string) string { _, p, _, _ := runtime.C...
package cache import ( "fmt" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/require" ) type testHandler struct{} func (h *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello world") } func TestHandler(t *testing.T) { curr := time.Now() c := N...
// Package reflexcion // Created by RTT. // Author: teocci@yandex.com on 2021-Aug-12 package main import ( "fmt" "reflect" ) // 1. Reflection goes from interface value to reflection object. // TypeOf returns the reflection Type of the value in the interface{}. // func TypeOf(i interface{}) Type func fromInterfaceTo...
// +build linux darwin freebsd package mount import ( "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestFileModTime(t *testing.T) { run.skipIfNoFUSE(t) run.createFile(t, "file", "123") mtime := time.Date(2012, 11, 18, 17, 32, 31, 0, time.UTC) err ...
// two pointers func maxSum(nums1 []int, nums2 []int) int { m, n := len(nums1), len(nums2) idx1, idx2 := 0, 0 var curr_sum1, curr_sum2 uint64 = 0, 0 for idx1 < m || idx2 < n { if idx1 < m && (idx2 == n || nums1[idx1] < nums2[idx2]) { curr_sum1 += uint64(nums1[idx1]) idx1++ } else if idx2 < n && (idx1 == m...
package rtc import ( "fmt" "time" "github.com/pokemium/worldwide/pkg/util" ) const ( S = iota M H DL DH ) // RTC Real Time Clock type RTC struct { Enable bool Mapped uint Ctr [5]byte Latched bool LatchedRTC LatchedRTC } // LatchedRTC Latched RTC type LatchedRTC struct{ Ctr [5]byte } ...
package main import "testing" func TestContainsEmptySlice(t *testing.T) { res := contains([]string{}, "a") if res { t.Error("should be false for empty slice") } } func TestContainsNoMatch(t *testing.T) { res := contains([]string{"b", "c"}, "a") if res { t.Error("should be false for no match") } } func Tes...
package scalars_test import ( "strings" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/nrfta/go-graphql-scalars" ) var _ = Describe("Marshal/ Unmarshal DateTime Test", func() { var ( correctDateTime = "2006-01-02T15:04:05Z" wrongDateTime = "2019-06-2435" testDateTime, _...
// Copyright 2014 Dirk Jablonowski. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package device import ( "fmt" "github.com/dirkjabl/bricker/net/packet" ) // Type for the debounce period (ms) with which the threshold callback is trigger...
/* * Copyright IBM Corporation 2021 * * 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 o...
package prompt import ( "bytes" "context" "io" "net/url" "reflect" "testing" "time" "github.com/stretchr/testify/assert" "github.com/tilt-dev/tilt/internal/store" "github.com/tilt-dev/tilt/internal/testutils" "github.com/tilt-dev/tilt/internal/testutils/bufsync" "github.com/tilt-dev/tilt/pkg/model" ) co...
package main import ( "bufio" "encoding/json" "fmt" "io/ioutil" "log" "math" "net" "net/http" "os" "strings" "sync" "github.com/aws/aws-xray-sdk-go/xray" "github.com/pkg/errors" ) const defaultPort = "8080" const defaultStage = "default" const maxTags = 1000 var tags [maxTags]string var tagsIdx int var...
package main import ( "bytes" "encoding/gob" "fmt" "godist/datamanager" "godist/dto" "godist/qutils" "log" ) const url = "amqp://guest@localhost:5672" func main() { ch, conn := qutils.GetChannel(url) defer conn.Close() defer ch.Close() msgs, err := ch.Consume( qutils.PersistentDataQueue, "", false,...
package v1beta1 import ( "context" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" "kubesphere.io/kubesphere/pkg/apiserver/query" ) type resourceCache struct { cache cache.Cache } func NewResourceCach...