text stringlengths 11 4.05M |
|---|
// Copyright (c) 2016 Magnus Bäck <magnus@noun.se>
package logstash
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"sort"
)
// getPipelineConfigDir copies one or more Logstash pipeline
// configuration files into the root of the specified directory.
// Returns an error if any I/O error occurs but ... |
// +build run
package main
import (
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/spiegel-im-spiegel/logf"
)
func main() {
rl, err := rotatelogs.New("./log.%Y%m%d%H%M.txt")
if err != nil {
logf.Fatal(err)
return
}
logger := logf.New(
logf.WithFlags(logf.LstdFlags|logf.Lshortfile),
log... |
package generator
import (
"github.com/devandrewgeorge/config-generator/internal/pkg/plugins"
"github.com/devandrewgeorge/config-generator/internal/pkg/variables"
"github.com/devandrewgeorge/config-generator/internal/pkg/templates"
"github.com/devandrewgeorge/config-generator/internal/pkg/outputs"
)
type Gene... |
package meter
import (
"errors"
"fmt"
"strings"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/charger/openwb"
"github.com/evcc-io/evcc/provider"
"github.com/evcc-io/evcc/provider/mqtt"
"github.com/evcc-io/evcc/util"
)
func init() {
registry.Add("openwb", NewOpenWBFromConfig)
}
// NewOpenWB... |
package main
import (
"github.com/trist725/myleaf"
"github.com/trist725/myleaf/network"
a "mlgs/src/robot/agent"
"mlgs/src/robot/conf"
"mlgs/src/robot/robot"
"time"
)
var gTcpClient network.TCPClient
func init() {
gTcpClient = network.TCPClient{
Addr: conf.Client.TCPAddr,
ConnNum: 1,
... |
package testing
import (
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
)
// Builder is a fake implementation of the Interface interface
type Builder struct {
}
// ShouldRebuild is a fake implementation of the function
func (b *Builder) ShouldRebuild(ctx devspacecontext.Context, forceRebuild boo... |
package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
)
/**
* https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/long-atm-queue-3/
*/
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanWords)
scanner.Scan()
N, _ := strconv.Atoi(scanner.... |
package datasourcetest
import (
"github.com/kdimak/go_datasource/datasource"
"testing"
)
func TestDatabase_Value(t *testing.T) {
TestWritableDataSource(t, TestConfig{DS: datasource.NewEmptyDistributedCache()})
TestWritableDataSource(t, TestConfig{DS: datasource.NewEmptyDatabase()})
}
|
package v1
import (
"fmt"
"regexp"
"strconv"
"github.com/go-ozzo/ozzo-validation"
"gopkg.in/yaml.v2"
)
// StoredSecret represents not the value of a "secret," but the abstract concept
// of "a secret stored somewhere".
//
// Note that "Name" will be the key that maps to this secret's actual value in
// the map[... |
// 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 policy
import (
"context"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"time"
"chromiumos/tast/common/fixture"
"chromiumos/tast/common/policy"
"chromiu... |
package db
import "github.com/go-xorm/xorm"
var DB *xorm.Engine |
// Copyright 2020 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 model
const (
CDNStatusActive = "active"
CDNStatusInactive = "inactive"
)
type CDN struct {
Model
HostName string `gorm:"column:host_name;size:256;uniqueIndex;not null" json:"host_name"`
IDC string `gorm:"column:idc;size:1024" json:"idc"`
Location string `gorm:"column:location;size:10... |
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package base
import (
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
"html/template"
"math"
"strings"
"time"
"github.com/Unknwon/i18n"
)
// Encod... |
package controllers
import (
"log"
"os"
"strings"
"time"
restful "github.com/emicklei/go-restful"
)
// logger : permet de définir son propore logger, par exemple pour écrire dans un fichier (en changeant le stdout je suppose)
// type *log.Logger
var logger = log.New(os.Stdout, "", 0)
// NCSACommonLogFormatLogg... |
package floors
import (
"errors"
"math"
"math/rand"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/currency"
"github.com/prebid/prebid-server/openrtb_ext"
)
type Price struct {
FloorMin float64
FloorMinCur string
}
const (
defaultCurrency string = "USD"
defaultDelimiter stri... |
package pdmcrawler
import (
"encoding/json"
"errors"
"fmt"
"github.com/PuerkitoBio/goquery"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
// BaseURL is url for wikipedia.
const BaseURL = "https://en.wikipedia.org"
// Crawler is crawler module
type Crawler struct {
Time time.Time `js... |
// Package base implements the basic data model and functionality for
// a sudoku solver.
package base
import "fmt"
import "io"
import "math/big"
import "os"
// Contradiction is the type of error that is returned if an operation
// results in a contradiction.
type Contradiction struct {
// Cell is the Cell that's th... |
package pubsubtest
import (
"errors"
"sync"
"github.com/NYTimes/gizmo/pubsub"
"github.com/golang/protobuf/proto"
"golang.org/x/net/context"
)
type (
// TestPublisher is a simple implementation of pubsub.Publisher meant to
// help mock out any implementations.
TestPublisher struct {
// Published will contai... |
package main
import (
"bufio"
"fmt"
"log"
"os"
)
type point struct {
x, y int
}
func within(a, b, c point) bool {
return c.x >= a.x && c.x <= b.x && c.y >= b.y && c.y <= a.y
}
func overlapping(a, b, c, d point) bool {
for _, i := range []point{a, point{a.x, b.y}, point{b.x, a.y}, b} {
if within(c, d, i) {
... |
package v3
import (
"fmt"
"github.com/cockroachdb/cockroach/pkg/util/treeprinter"
)
func init() {
registerOperator(indexScanOp, "index-scan", indexScanClass{})
}
func newIndexScanExpr(table *table, key *tableKey, scanProps *relationalProps) *expr {
index := *table
index.name = tableName(fmt.Sprintf("%s@%s", ta... |
// Copyright 2019 The gVisor 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... |
package main
import (
"fmt"
"os"
"github.com/joho/godotenv"
"github.com/streadway/amqp"
)
func init() {
err := godotenv.Load(".env")
if err != nil {
fmt.Printf("Failed to load the env file : Error = %s", err.Error())
return
}
}
func main() {
fmt.Println("Rabbit MQ tutorial")
conn, err := amqp.Dial("amq... |
package main
import "fmt"
type contactInfo struct { //struct can have mixed data types like string and int
email string
zip int
}
type person struct {
firstName string
lastName string
contact contactInfo // struct can be contained in another struct
}
func main() {
//alex := person{"Alex", "Anderson"} ... |
package netutil
import (
"encoding/binary"
"errors"
"net"
)
var (
// ErrIPv6 is an error that a function does not support IPv6.
ErrIPv6 = errors.New("only IPv4 address is supported")
)
// IP4ToInt returns uint32 value for an IPv4 address.
// If ip is not an IPv4 address, this returns 0.
//
// Deprecated: use IP... |
package cmd
import (
"fmt"
"github.com/brainicorn/skelp/generator"
"github.com/mgutz/ansi"
"github.com/spf13/cobra"
)
const (
errAliasAddMissingArgs = "alias name and a template url/path are required"
errAliasAddBadAlias = "first argument must be a valid alias name"
errAliasAddBadPath = "secon... |
package graphql
import (
"bytes"
"text/template"
"github.com/pkg/errors"
)
type fieldsRenderer struct {
templateFuncs map[string]interface{}
}
type mapFieldsRenderer struct {
templateFuncs map[string]interface{}
}
type RenderFieldsContext struct {
OutputObject OutputObject
ObjectContext BodyContext
}
func... |
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/dtbell99/golangexamples/localdatabase"
"github.com/gorilla/mux"
)
type health struct {
Status string `json:"status"`
SystemTime string `json:"systemTime"`
}
type successResponse struct {
Status string `json:"status"`
}... |
// Copyright 2020 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 udwRspLib
import (
"github.com/tachyon-protocol/udw/udwTest"
"testing"
)
func TestGoBuffer_ReadStringUTF16(t *testing.T) {
_buf := &GoBuffer{}
_buf.WriteStringUTF16("abc")
_buf.ResetToRead()
s := _buf.ReadStringUTF16()
udwTest.Equal(s, "abc")
}
|
package main
import (
"flag"
"github.com/coreos/go-etcd/etcd"
"github.com/dgryski/go-jump"
"github.com/inconshreveable/log15"
"github.com/michaelvlaar/etcd-endpointer"
api "github.com/michaelvlaar/etcd-endpointer/examples/echoservice/api/protos"
echo "github.com/michaelvlaar/etcd-endpointer/examples/echoservice... |
/*
* Created by lintao on 2023/7/27 上午10:04
* Copyright © 2020-2023 LINTAO. All rights reserved.
*
*/
package main
import (
"context"
"github.com/NSObjects/go-template/internal/api/biz"
"github.com/NSObjects/go-template/internal/api/data"
"github.com/NSObjects/go-template/internal/api/service"
"github.com/NS... |
// Copyright (c) 2020 - for information on the respective copyright owner
// see the NOTICE file and/or the repository at
// https://github.com/hyperledger-labs/perun-node
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may... |
package main
import (
"testing"
"gotest.tools/assert"
)
func TestDummy(t *testing.T) {
assert.Equal(t, dummy(1, 2), 3)
}
|
package rod_test
import (
"testing"
"github.com/go-rod/rod/lib/devices"
"github.com/go-rod/rod/lib/input"
"github.com/go-rod/rod/lib/proto"
"github.com/go-rod/rod/lib/utils"
)
func TestKeyActions(t *testing.T) {
g := setup(t)
p := g.page.MustNavigate(g.srcFile("fixtures/keys.html"))
body := p.MustElement("b... |
// Copyright (c) KwanJunWen
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package estemplate
import "fmt"
// DatatypeSparseVector Specialised Datatype that stores dense vectors of float
// values. The maximum number of dimensions that ca... |
package main
func (a *app) handleCommand(input string) (bool, error) {
// FIXME: uncomment in the event commands are needed at the CLI level.
// if strings.HasPrefix(input, cmdPrefix) {
// input = strings.TrimFunc(input, func(c rune) bool {
// // Trim off any unexpected input
// return unicode.IsSpace(c) || ... |
package db
import (
"database/sql"
)
func Connect(conn string) *sql.DB {
db, err := sql.Open("postgres", conn)
if err != nil {
panic(err)
}
return db
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package testlib
import (
"github.com/golang/mock/gomock"
mocks "github.com/mattermost/mattermost-cloud/internal/mocks/model"
)
// ModelMockedAPI has all mocked interfaces defined in model.
type ModelM... |
package rule
import (
"fmt"
"strings"
)
// Creates a regular expression from a domain that will block the domain and all
// subdomains of that domain.
func genRegex(domain string) string {
return fmt.Sprintf(`(?:^|.+\.)%s$`, strings.Replace(domain, ".", `\.`, -1))
}
|
// 订单服务
package elemeOpenApi
// 获取订单配送轨迹
// orderId 订单Id
func (delivery *Delivery) GetDeliveryRoutes(orderId_ string) (interface{}, error) {
params := make(map[string]interface{})
params["orderId"] = orderId_
return APIInterface(delivery.config, "eleme.order.delivery.getDeliveryRoutes", params)
}
// 获取订单
// order... |
package api
import (
"bytes"
"compress/gzip"
"encoding/json"
"io/ioutil"
"math"
"unicode"
"unicode/utf16"
)
// decodeAndTestFilter decodes the filter and determines if identifier is a member of the underlying
// set. Returns an error if the encoded filter is malformed (improperly compressed or invalid JSON).
f... |
package main
// F.Demurger 2019-06
//
// Swap language in the VDF file header. UTF8 and UTF16 LE only for now.
//
// Usage: vdfswaplang filename oldlang newlang > newfile
//
//
//
//
// cross compilation AMD64: env GOOS=windows GOARCH=amd64 go build vdfswaplang.go
import (
//"bufio"
"bytes"
"flag"
"fmt"
// "io... |
package litecoin
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"github.com/btcsuite/btcd/btcec"
btcwire "github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/coinset"
btchd "github.com/btcsuite/btcutil/hdkeychain"
"github.com/btcsuite/... |
/*
Copyright 2019 Baidu, 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 in writing, software
dis... |
package main
import (
"strings"
)
// 统计 字母数量多少就能对比
func checkInclusion(s1 string, s2 string) bool {
if len(s2) < len(s1) {
return false
}
c1 := make([]int, 26)
c2 := make([]int, 26)
for _, w := range s1 {
c1[w-'a']++
}
for i, w := range s2 {
if i >= len(s1) {
c2[s2[i-len(s1)]-'a']--
}
c2[w-'a']... |
package gore
import (
"io"
"strconv"
"time"
)
// Reply type, similar to Hiredis
const (
ReplyString = 1
ReplyArray = 2
ReplyInteger = 3
ReplyNil = 4
ReplyStatus = 5
ReplyError = 6
)
// Pair holds a pair of value, such as reply from HGETALL or ZRANGE [WITHSCORES]
type Pair struct {
First []byte
... |
package main
import (
"bufio"
"io"
"io/ioutil"
"os"
"strings"
)
type JSPFile struct {
Path string
}
func NewJSPFile(path string) *JSPFile {
return &JSPFile{Path: path}
}
func (self *JSPFile) Stamp(timestamp string) (int, error) {
lines, err := self.readLines()
if err != nil {
return 0, err
}
lines, rep... |
package metadata
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/openshift/oc-mirror/pkg/api/v1alpha2"
"github.com/openshift/oc-mirror/pkg/metadata/storage"
)
func TestUpdateMetadata_Catalogs(t *testing.T) {
type spec struct {
name string
config v1alpha2.ImageSetConfig... |
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// 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 sort
func MergeSort(values []int) []int {
return split(values)
}
func merge(left []int, right []int) []int {
sorted_list := make([]int, 0)
var x int
for len(left) > 0 || len(right) > 0 {
if len(left) > 0 && len(right) > 0 {
if left[0] < right[0] {
x, left = left[0], left[1:]
sorted_list = app... |
package main
import (
"bytes"
"context"
"flag"
"go/build"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"golang.org/x/tools/go/vcs"
"github.com/hirokidaichi/goviz/dotwriter"
"github.com/hirokidaichi/goviz/goimport"
"github.com/juju/ratelimit"
"github.com/pkg/errors... |
package main
import (
"log"
"os"
"time"
"github.com/urfave/cli/v2"
)
func main() {
if err := mainErr(); err != nil {
log.Fatal(err)
}
}
func mainErr() error {
app := cli.NewApp()
app.Name = "simulate parallel request to cassandra native transport"
app.Commands = []*cli.Command{
StressCommand(),
}
ret... |
package main
import (
"fmt"
"log"
)
func (cli *CLI) createTokoin(address, nodeID string) {
if !ValidateAddress(address) {
log.Panic("ERROR: Address is not valid")
}
bc := NewBlockchain(nodeID)
URPOSet := URPOSet{bc}
defer bc.db.Close()
//tx := NewURPOTransaction(&wallet, to, &URPOSet)
cbTx := NewCoinbase... |
package controllers
import (
"bytes"
"crypto/sha256"
"fmt"
"github.com/revel/revel"
"image"
"image/jpeg"
"io/ioutil"
"net/http"
"net/url"
"os"
"strconv"
"strings"
)
var pix = image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{1, 1}})
var img image.Image = pix
var buffer = new(bytes.Buffer)
var f... |
package lc
// Time: O(n)
// Benchmark: 8ms 4.2mb | 73% 75%
func floodFill(image [][]int, sr int, sc int, newColor int) [][]int {
m := len(image)
n := len(image[0])
origColor := image[sr][sc]
if origColor == newColor {
return image
}
var fill func(row, col int)
fill = func(row, col int) {
image[row][col] =... |
package crawler
import (
"context"
"github.com/pkg/errors"
"github.com/utahta/momoclo-crawler"
"google.golang.org/appengine/urlfetch"
)
type (
// FeedFetcher interface
FeedFetcher interface {
Fetch(ctx context.Context, code FeedCode, maxItemNum int, latestURL string) ([]FeedItem, error)
}
client struct {
... |
package websocket
import (
"testing"
"github.com/stretchr/testify/assert"
)
const (
// example in Sec-Websocket-Key in rfc6455
testSecWebsocketKey = "dGhlIHNhbXBsZSBub25jZQ=="
// example Sec-Websocket-Accept in rfc6455
testSecWebsocketAccept = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
)
func TestGenerateAcceptKey(t *tes... |
package zen
type fieldKey struct{}
type fields map[string]interface{}
func (f fields) Merge(m fields) {
for k, v := range m {
if _, ok := f[k]; !ok {
f[k] = v
}
}
}
|
// 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 network
import (
"context"
"time"
"chromiumos/tast/errors"
"chromiumos/tast/local/apps"
"chromiumos/tast/local/bundles/cros/network/vpn"
"chromiumos/tast/loca... |
// Copyright 2018 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package binsetup is used to perform setup before running Chrome video test binaries.
package binsetup
import (
"io/ioutil"
"os"
"path/filepath"
"chromiumos/tast/erro... |
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"fmt"
"github.com/libgit2/git2go"
"io/ioutil"
"log"
"os"
"reflect"
"testing"
)
var (
repo *git.Repository
err error
)
func setup() {
// log.Printf("testprint")
repo, err = git.OpenRepository("./test")
if err != nil {
log.Println("open repos... |
package grafana
import (
"fmt"
"net/url"
"os"
"path"
"strings"
)
func getGrafanaToken() (string, bool) {
return os.LookupEnv("GRAFANA_TOKEN")
}
func getGrafanaURL(urlPath string) (string, error) {
if grafanaURL, exists := os.LookupEnv("GRAFANA_URL"); exists {
u, err := url.Parse(grafanaURL)
if err != nil ... |
/**
* (C) Copyright IBM Corp. 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 or agree... |
package vox
import (
"encoding/json"
"fmt"
"github.com/prebid/openrtb/v19/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/openrtb_ext"
)
type adapter struct {
endpoint string
}
func Builder(bidderName openrtb_ext.BidderName, config... |
/*
* Created on Mon Dec 03 2018 9:3:16
* Author: WuLC
* EMail: liangchaowu5@gmail.com
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// simple recursive
func flipEquiv(root1 *TreeNode, root2 *TreeNode) bool {
if root1 ==... |
package main
import (
"sort"
"time"
"github.com/fanaticscripter/EggContractor/api"
"github.com/fanaticscripter/EggContractor/util"
)
type mission struct {
Ship api.MissionInfo_Spaceship `json:"ship"`
ShipName string `json:"shipName"`
ShipIconPath strin... |
// Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in complian... |
/*
Copyright © 2018 inwinSTACK 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 in writing, software... |
package azure
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure/auth"
)
func getAuthorizer() (autorest.Authorizer, error) {
return auth.NewAuthorizerFromEnvironment()
}
func getVaultAuthorizer() (autorest.Authorizer, error) {
return auth.NewAuthorizerFromCLIWithResourc... |
// Copyright (c) 2018 The MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package layereddpv2
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"strconv"
"testing"
"time"
"github.com/MatrixAINetwork/g... |
{%- from "../../partials/go.template" import messageName -%}
package channel
import (
"strings"
)
// Publish Operation Topics
{%- for ch_name, ch in asyncapi.channels() -%}
{%- if ch.hasPublish() -%}
{%- set opName = ch.publish().id() | toGoPublicID -%}
{%- set msgName = messageName(ch.publish().message()) %}
... |
package util
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)
const (
REGISTERED = "SMS_193511188" //注册
ChangePassword = "SMS_193511189" //修改密码
BingPhoneNumber = "SMS_193512698" //绑定手机号码
)
func SendSms(modeCode, number, code string) {
client, err := dysmsapi.NewClientWithAccess... |
package main
import (
"fmt"
"os"
"path/filepath"
"gopkg.in/urfave/cli.v1"
)
const (
cliVersion = "0.0.1"
envTypeDev = "dev"
envVarGPI = "GOPHR_GOOGLE_PROJECT_ID"
envVarKeyPath = "GOPHR_KEYFILE_PATH"
envVarK8SProdContext = "GOPHR_K8S_CONTEXT"
flagNameGPI = "gpi"
flagNamePro... |
package controller
import (
"path"
"net/http"
"html/template"
"github.com/julienschmidt/httprouter"
)
func HomeHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
fp := path.Join("views", "index.html")
tmpl, err := template.ParseFiles(fp)
if err != nil {
http.Error(w, err.Error(), http... |
// Copyright 2018 someonegg. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package racex provides race primitives.
// RaceEnabled : present if build with -race
package racex
|
package main
import (
"fmt"
"math/cmplx"
"os"
)
func main() {
size := 1024
result := makeMandelbrotSet(
complex(0.50, 1.00),
complex(-1.50, -1.00),
size,
100,
500,
)
file, _ := os.Create("image.pgm")
defer file.Close()
file.Write(([]byte)("P2\n"))
file.Write(([]byte)(fmt.Sprint(size) + " " + fm... |
package kata
// Deadfish parser: https://www.codewars.com/kata/make-the-deadfish-swim/train/go
func Parse(data string) []int {
value := 0
res := []int{}
for _, c := range data {
if c == 'i' {
value++
} else if c == 'd' {
value--
} else if c == 's' {
value *= value
} else if c == 'o' {
res = appe... |
package core
import (
"fmt"
"net/http"
"github.com/Al-un/alun-api/pkg/logger"
"github.com/gorilla/mux"
)
// ----------------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------------
// EndpointAdapter (or Decorator desi... |
// This file serves for the Page.Evaluate.
package rod
import (
"errors"
"fmt"
"strings"
"time"
"github.com/go-rod/rod/lib/cdp"
"github.com/go-rod/rod/lib/js"
"github.com/go-rod/rod/lib/proto"
"github.com/go-rod/rod/lib/utils"
"github.com/ysmood/gson"
)
// EvalOptions for Page.Evaluate
type EvalOptions str... |
package flipper
import (
"fmt"
"net/http"
"strconv"
"github.com/prometheus/client_golang/prometheus"
)
var (
flips = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "flips_total",
Help: "a counter of successful flips",
},
)
illegalFlips = prometheus.NewCounter(
prometheus.CounterOpts{
Name... |
package canvasapi
import (
"errors"
)
// ErrRateLimitExceeded is returned when the api rate limit has been reached.
var ErrRateLimitExceeded = errors.New("403 Forbidden (Rate Limit Exceeded)")
// IsRateLimit returns true if the error given is a rate limit error.
func IsRateLimit(e error) bool {
return e == ErrRate... |
package garden
import (
"fmt"
"strconv"
"github.com/mandelsoft/cmdint/pkg/cmdint"
"github.com/afritzler/garden-examiner/cmd/gex/cmdline"
"github.com/afritzler/garden-examiner/cmd/gex/context"
"github.com/afritzler/garden-examiner/cmd/gex/output"
"github.com/afritzler/garden-examiner/cmd/gex/util"
"github.com... |
package password
import (
"fmt"
"strings"
)
// Parse returns a Policy and a password parsed from s.
func Parse(s string) (*Policy, string, error) {
parts := strings.Split(s, ":")
if len(parts) != 2 {
return nil, "", fmt.Errorf("invalid password entry : %s", s)
}
policy, err := ParsePolicy(parts[0])
if err !... |
package log
import (
"testing"
"time"
)
func Test(t *testing.T) {
Printf("this is printf, %d", 1)
Printf("this is printf, %d", 2)
Infof("this is info, %d", 3)
Debugf("this is debug, %d", 4)
Errorf("this is error, %d", 5)
Warnf("this is warn, %d", 6)
}
func TestLogger(t *testing.T) {
log := NewLogger(OpenPri... |
package scraper_test
import (
"errors"
"fmt"
"strings"
"github.com/mh-orange/scraper"
)
type Name struct {
First string
Last string
}
func (n *Name) UnmarshalText(text []byte) (err error) {
tokens := strings.Split(string(text), ", ")
if len(tokens) == 2 {
n.Last = tokens[0]
n.First = tokens[1]
} else ... |
package main
import (
"fmt"
"time"
)
/*
Функция «or» объединяет несколько каналов в один, если один (или все закрыты).
В качестве аргумента, функция получает:
1) Срез каналов типа <-chan interface{}, который является исходным
для последующего объединения его элементов в один канал;
2) Канал типа chan interface{}... |
package bungo
import (
"errors"
"fmt"
)
type InventoryItemTierType string
func InventoryItemTierTypeTypes(key int) InventoryItemTierType {
out, _ := InventoryItemTierTypesE(key)
return out
}
func InventoryItemTierTypesE(key int) (InventoryItemTierType, error) {
switch key {
case 0:
return "Unknown", nil
ca... |
package observer
import (
"io"
"io/ioutil"
"testing"
)
func TestPipe(t *testing.T) {
r, w := Pipe()
type result struct {
b []byte
n int
err error
}
rs := make(chan result)
go func() {
n, err := w.Write([]byte("hello"))
if err != nil {
rs <- result{n: n, err: err}
}
w.Close()
}()
go f... |
package server
import (
"context"
"crypto/tls"
"fmt"
"io"
"log"
"net/http"
"regexp"
"github.com/gorilla/mux"
genericapiserver "k8s.io/apiserver/pkg/server"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/kubectl/pkg/proxy"
"github.c... |
package grpc
import (
"context"
"fmt"
"github.com/m-zajac/goprojectdemo/internal/app"
)
// AppService can return most active contributors.
type AppService interface {
MostActiveContributors(
ctx context.Context,
language string,
projectsCount int,
count int,
) ([]app.ContributorStats, error)
}
// Servi... |
/*
* Databricks
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* API version: 0.0.1
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package models
type ClustersS3StorageInfo struct {
Destination string `json:"... |
package LMGTest
import (
"AlgorithmPractice/src/Algorithm/comprehensive/sumofSubSequence/LMG"
"github.com/stretchr/testify/assert"
"testing"
)
func TestThiefSteal2(t *testing.T) {
thief := &LMG.ThiefSteal2{}
assertions := assert.New(t)
assertions.Equal(thief.Method(demo00), 0)
assertions.Equal(thief.Method(d... |
package atTheCrossroads
func isInfiniteProcess(a int, b int) bool {
if b < a || (b%2 != 0 && a%2 != 1) || (b%2 != 1 && a%2 != 0){
return true
}
return false
}
|
package persist
import (
"fmt"
"github.com/Miniand/venditio/core"
"github.com/Miniand/venditio/inject"
"strings"
)
const (
DEP_DB = "persistDb"
DEP_SCHEMA = "persistSchema"
)
type persistInit struct {
dbChecked bool
}
func Register(v *core.Venditio) {
v.BindFactory(DEP_SCHEMA, func(i inject.Injector) in... |
package cmd
import (
"path/filepath"
"github.com/HotelsDotCom/flyte/httputil"
"io/ioutil"
"os"
"strings"
"bufio"
"bytes"
"log"
)
func getContentType(filename string) string {
switch filepath.Ext(filename) {
case ".json":
return httputil.MediaTypeJson
case ".yaml", ".yml":
return httputil.MediaTypeYaml
... |
package di
import "net/http"
type FeatureToggler interface {
SplitPercentage(percentage float64) bool
}
type FeatureToggle struct {
Randomiser func() float64
}
func (ft *FeatureToggle) SplitPercentage(percentage float64) bool {
switch percentage {
case 0:
return false
case 100:
return true
default:
retu... |
package routers
import (
"github.com/astaxie/beego"
"../controllers"
)
func init() {
//template
beego.Router("/api/admin/email/template", &controllers.EmailTemplateController{}, "post:AddNew")
beego.Router("/api/admin/email/template/:name([\\w]+)", &controllers.EmailTemplateController{}, "get:GetByName")
beego.... |
package web
import (
"github.com/jbrook/go-web-utils/i18n"
"net/http"
"github.com/gorilla/sessions"
"github.com/gorilla/context"
"log"
)
type SessionConfig struct {
Routes http.Handler
Secret string
}
var sessionConfig SessionConfig
var cookieOptions = sessions.Options{
Path: "/"... |
package main
import (
"flag"
"fmt"
"github.com/james-bowman/slack"
"io/ioutil"
"log"
"os"
)
func main() {
slackToken := getToken()
text, err := ioutil.ReadFile("message.txt")
if err != nil {
log.Panic(fmt.Sprintf("Error opening message.txt for canned response: %s", err))
}
conn, err := slack.Connect(sl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.