text stringlengths 11 4.05M |
|---|
package log
import (
"sync"
)
var _ Labels = (*labels)(nil)
type labels sync.Map
// NewLabels returns a Labels instance.
func NewLabels() Labels {
l := labels(sync.Map{})
return &l
}
func (l *labels) Get(key string) (string, bool) {
value, ok := (*sync.Map)(l).Load(key)
return value.(string), ok
}
func (l *l... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
var (
a AddressBook
message string
)
func initialize() {
a = AddressBook{}
fmt.Println(" \n------------------------------------ ")
fmt.Println(" 📕 Welcome To Your Address Book 📗 ")
fmt.Println("----------------------------------... |
package main
import (
"OneeSan/controllers"
_ "OneeSan/models"
"OneeSan/pixiv"
_ "OneeSan/routers"
"github.com/astaxie/beego"
"strings"
"time"
)
func main() {
getdelay, err := beego.AppConfig.Int("get_illust_delay")
if controllers.CheckError(err) {
return
}
pixiv.BooksLimit, err = beego.AppConfig.Int("ad... |
package models
import (
"gorm.io/gorm"
"time"
)
type BaseModel struct {
CreatedAt *time.Time `gorm:"created_at" json:"createdAt"`
UpdatedAt *time.Time `gorm:"updated_at" json:"updatedAt"`
CreateBy string `gorm:"create_by" json:"createBy"`
UpdateBy string `gorm:"update_by" json:"updat... |
package ws_local_server
import (
"encoding/json"
"open_im_sdk/open_im_sdk"
)
type GroupCallback struct {
uid string
}
func (g *GroupCallback) OnMemberEnter(groupId string, memberList string) {
m := make(map[string]interface{}, 2)
m["groupId"] = groupId
m["memberList"] = memberList
j, _ := json.Marshal(m)
Sen... |
package main
import (
"./dao"
"./http"
"./socket"
"./types"
"encoding/gob"
"encoding/json"
"flag"
"fmt"
"log"
"net"
"os"
"strconv"
"strings"
"time"
)
/*
Note - I am still learning a lot about Go. I'm not sure how much of this is idiomatic.
Its just a hobby / learning experiment and a bit of fun.
*/
... |
// +groupName=vacuum.swine.de
package vacuum
const GroupName = "vacuum.swine.de"
|
package main
import (
"fmt"
)
type embedded struct {
i int
}
func (x embedded) do() {
fmt.Println("do()")
}
type test struct {
embedded
}
func main() {
var x test
x.do()
fmt.Println(x.i)
}
|
package main
import (
"net/http"
"github.com/a-h/gosign"
"github.com/gorilla/mux"
)
func main() {
// Initialise the Gorilla Router.
r := mux.NewRouter()
// Create a test Hello World handler.
helloHandler := &helloHandler{}
// Load the private key, and create an instance of the signing
// middleware which ... |
package auth
import (
"net/http"
// "fmt"
// "log"
"html/template"
// "database/sql"
"github.com/kataras/go-sessions"
// "github.com/kataras/go-sessions"
"golang.org/x/crypto/bcrypt"
// q "project_reservasi/src/controller/query"
conn "project_reservasi/src/config"
mo "project_reservasi/src/model"
)
func ... |
package catalog
import (
"k8s.io/client-go/dynamic"
"github.com/operator-framework/operator-lifecycle-manager/pkg/api/client/clientset/versioned"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/clients"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorclient"
)
type stu... |
// Copyright 2018 the Service Broker Project 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 applic... |
package pokemon
import (
"encoding/json"
"github.com/pkg/errors"
"io/ioutil"
"net/http"
)
const pokemonAPI = "https://pokeapi.co/api/v2/pokemon/"
type Location struct {
Name string
}
type Encounter struct {
Location Location `json:"location_area"`
}
type Pokemon struct {
Name string `json:"name"`
}
type Ou... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"my9awsgo/my9client"
"my9awsgo/my9ec2"
"my9awsgo/my9ecs"
"my9awsgo/my9s3"
"my9awsgo/my9sfn"
"my9awsgo/my9sns"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
)
type StepWorkerCleanupConfig struct {
Project st... |
package resources
import (
"github.com/anshap1719/authentication/design/types"
. "goa.design/goa/v3/dsl"
)
var _ = Service("password-auth", func() {
HTTP(func() {
Path("/")
})
Method("register", func() {
Security(APIKeyAuth)
Description("Register a new user with an email and password")
HTTP(func() {
... |
package main
import (
"fmt"
"math"
)
func main() {
n := 361
for i := 1; i <= 100; i++ {
for j := 2; j <= 100; j++ {
temp := math.Pow(float64(i), float64(j))
if n == int(temp) {
fmt.Println("true")
return
}
}
}
fmt.Println("false")
}
|
/*
* KSQL
*
* This is a swagger spec for ksqldb
*
* API version: 1.0.0
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package swagger
type DescribeResultItemSourceDescriptionSchema struct {
Type_ string `json:"type,omitempty"`
MemberSchema *interface{} `... |
package concurrency
import (
"runtime"
"testing"
)
func TestNoSched(t *testing.T) {
NoSched()
// only prints "Bye"
}
func TestSched(t *testing.T) {
Sched()
//show some, since according documentation
//runtime.Gosched allows other goroutines to run
//which mean that maybe not all are allowed
}
func TestSched... |
// Copyright 2018 Andrew Bates
//
// 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 wri... |
package backends
import (
"context"
"github.com/pkg/errors"
"github.com/batchcorp/plumber/backends/activemq"
"github.com/batchcorp/plumber/backends/awskinesis"
"github.com/batchcorp/plumber/backends/awssns"
"github.com/batchcorp/plumber/backends/awssqs"
azureEventhub "github.com/batchcorp/plumber/backends/azu... |
package cmd
import (
"net/http"
"strconv"
)
func Logs(subsystem string, level string, texOnly bool) error {
if subsystem != "" {
subsystem = "/" + subsystem
}
var method method
method = http.MethodGet
if level != "" {
method = http.MethodPost
}
opts := map[string]string{
"subsystem": subsystem,
"lev... |
/**
* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
* If the last word does not exist, return 0.
* Note: A word is defined as a character sequence consists of non-space characters only.
* For example, Given s = "Hello World", r... |
package main
import (
"context"
"errors"
"net"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Sirupsen/logrus"
"github.com/miekg/dns"
)
const (
dnsDefaultPort = ":53"
)
var (
allowedDomainChars [255]bool
dnsServers []string
)
func init() {
for _, b := range []byte("1234567890qwertyuiopasdfg... |
package categories
import (
"sync"
"github.com/Nv7-Github/Nv7Haven/eod/base"
"github.com/Nv7-Github/Nv7Haven/eod/polls"
"github.com/Nv7-Github/Nv7Haven/eod/types"
"github.com/bwmarrin/discordgo"
)
type Categories struct {
dat map[string]types.ServerData
lock *sync.RWMutex
base *base.Base
dg *discordg... |
package messages
import "fmt"
type SimpleMessage struct {
OriginalName string
RelayPeerAddr string
Contents string
}
type GossipPacket struct {
Simple *SimpleMessage
Rumor *RumorMessage
Status *StatusPacket
Private *PrivateMessage
DataRequest *DataRequest
DataReply *DataReply
ShareFile *ShareFil... |
// +build unit
package coreapi
import (
"testing"
"github.com/go-chi/chi"
"github.com/stretchr/testify/assert"
)
func TestRegister(t *testing.T) {
r := chi.NewRouter()
Register(r, nil, nil, nil)
assert.Len(t, r.Routes(), 6)
assert.Equal(t, r.Routes()[0].Pattern, "/documents")
assert.Len(t, r.Routes()[0].Han... |
package codec
import (
"github.com/iotaledger/wasp/packages/coretypes"
)
func DecodeHname(b []byte) (coretypes.Hname, bool, error) {
if b == nil {
return 0, false, nil
}
r, err := coretypes.NewHnameFromBytes(b)
return r, err == nil, err
}
func EncodeHname(value coretypes.Hname) []byte {
return value.Bytes()
... |
package main
import (
"crypto/md5"
"fmt"
"github.com/zenazn/goji"
"html/template"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
)
const (
ASSET_ROOT = "./assets"
)
type fileInfo struct {
directory string
name string
extension string
nameWithoutExtension string
}
... |
// Copyright 2021 Akamai Technologies, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
package gfuns
import (
"github.com/joho/godotenv"
"log"
"os"
)
func Run_init() {
err := godotenv.Load("env")
if err != nil {
log.Fatal("Error loading env file", err)
}
load()
}
func load() {
if !Exists(os.TempDir() + "/ffmpeg") {
ffmpeg, _ := os.Create(os.TempDir() + "/ffmpeg")
ffprobe, _ := os.Create(o... |
package iban
//IBAN is the international bank number representation
type IBAN struct {
Number string
Length int
}
//NewIBAN creates a new IBAN from the given IBAN string
func NewIBAN(number string) *IBAN {
iban := IBAN{Number: number, Length: len(number)}
return &iban
}
|
package sensu
import (
"encoding/json"
"fmt"
"github.com/streadway/amqp"
"log"
"os"
"plugins"
"strings"
"time"
)
const RESULTS_QUEUE = "results"
type check struct {
Name string `json:"name"` // the check name in sensu
Command string `json:"command"` // the "command" that was run
Exec... |
package db
import (
"log"
"os"
"testing"
"time"
"github.com/breathingdust/house.api/models"
"github.com/stretchr/testify/assert"
"gopkg.in/mgo.v2"
)
func clearDatabase(conn string) {
s, _ := mgo.Dial(conn)
//defer s.Close()
s.DB("house_test").C("transactions").RemoveAll(nil)
}
func getConnectionString() s... |
package tree
import (
"testing"
)
// 1
// 2 3
// 4 5 6
func generateBinaryTree() *Node {
root := NewTreeNode(1)
root.left = NewTreeNode(2)
root.right = NewTreeNode(3)
root.left.left = NewTreeNode(4)
root.left.right = NewTreeNode(5)
root.right.left = NewTreeNode(6)
return root
}
// 前序遍历,输出应为 1 2 4... |
package main
import (
"math/big"
"fmt"
"bytes"
)
//定义切片存储base58字母
var b58Alphaet = []byte("123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
func Base58Encode(input []byte) []byte {
var result []byte //定义一个切片。返回值
x := big.NewInt(0).SetBytes(input) //把字节数组input转化为大整数bigint
bas... |
// 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 main
import (
"encoding/binary"
"fmt"
"math/big"
"time"
clt "github.com/QuarkChain/goqkcclient/client"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp"
)
var (
client = clt.... |
/*
The Chinese Remainder Theorem tells us that we can always find a number that produces any required remainders under different prime moduli. Your goal is to write code to output such a number in polynomial time. Shortest code wins.
For example, say we're given these constraints:
n ≡ 2 mod 7
n ≡ 4 mod 5
n ≡ 0 mo... |
package ecs
import "testing"
var commandOverrideTests = []struct {
commandString string
expectedOverride []string
}{
{"node src/bin/cli.js generate-snapshots", []string{"node", "src/bin/cli.js", "generate-snapshots"}},
{
"sh -c \"/var/www/qc2-crons; php /var/www/app/Console/cake.php cron generateScorecardsDa... |
package cloudflare
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
)
var ErrMissingWorkerRouteID = errors.New("missing required route ID")
type ListWorkerRoutes struct{}
type CreateWorkerRouteParams struct {
Pattern string `json:"pattern"`
Script string `json:"script,omitempty"`
}
type ListWor... |
package queue
type (
// Queue FIFO
Queue struct {
start, end *node
length int
}
node struct {
value interface{}
next *node
}
)
// New Create a new queue
func New() *Queue {
return &Queue{nil, nil, 0}
}
// Len Return the number of items in the queue
func (q *Queue) Len() int {
return q.length
}
/... |
package main
import (
"flag"
"fmt"
//"log"
"os"
//"os/exec"
"strconv"
"strings"
)
const (
ErrorRevision = -1
RevisionSep = ","
)
type Revision int32
type RevisionPair struct {
defined bool
a Revision
b Revision
}
func (r *Revision) String() string {
return strconv.Itoa(int(*r))
}
func (r... |
package main
import (
"bytes"
"io/ioutil"
"log"
"regexp"
"time"
"github.com/fatih/color"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.Use(reqLogger())
router.GET("/", func(context *gin.Context) {
context.JSON(200, gin.H{
"app": "budgetbro API",
"timeNow": time.Now()... |
package mocking
import "reflect"
//Restorer 함수 타입은 이전 상태를 복원하기 위해
//사용할 수 있는 함수를 보유하고 있다.
type Restorer func()
//Restore 함수를 호출하면 이전 상태로 복원된다.
func (r Restorer) Restore() {
r()
}
//Patch 함수는 지정된 대상(destination)이 가리키는 값을 주어진 값으로
//설정하고, 이를 원래 상태로 되돌릴 수 있는 함수를 리턴한다.
//이 값은 반드시 대상 타입의 객체에
//할당 가능 (assignable)해야 한다.
f... |
package fuctional_options
import (
"crypto/tls"
"time"
)
type Server struct {
Addr string
Port int
Protocol string
Timeout time.Duration
MaxConns int
TLS *tls.Config
}
func NewDefaultServer(addr string, port int) (*Server, error) {
return &Server{addr, port, "tcp", 30 * time.Second, 100, nil},... |
/* nighthawk.nhstruct.persistence.go
* author: roshan maskey <roshanmaskey@gmail.com>
*
* Datastructure for persistence
*/
package nhstruct
type PersistenceItem struct {
JobCreated string `xml:"created,attr"`
TlnTime string `json:"TlnTime"`
PersistenceType string
RegPath ... |
package heapsort
func heapify(arr []int, n, current int) {
right := 2*current + 2
left := 2*current + 1
root := current
if left < n && arr[left] > arr[root] {
root = left
}
if right < n && arr[right] > arr[root] {
root = right
}
if root != current {
swap(arr, current, root)
heapify(arr, n, root)
}
... |
package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"strconv"
"github.com/go-errors/errors"
"tezos-contests.izibi.com/backend/signing"
)
func (s *Server) NewGame(firstBlock string) (*GameState, error) {
type Request struct {
Author string `json:"author"`
FirstBlock s... |
package main
import "fmt"
/**
133. 克隆图
给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。
图中的每个节点都包含它的值 `val(int)` 和其邻居的列表`(list[Node])`。
```
class Node {
public int val;
public List<Node> neighbors;
}
```
测试用例格式:
简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1(val = 1),第二个节点值为 2(val = 2),以此类推。该图在测试用例中使用邻接列表表示。
邻接列表 是用于表示有限图的无序列表的集合。每个列表... |
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/gorilla/feeds"
)
func main() {
for _, rawUri := range os.Args[1:] {
b, err := readerFromURI(rawUri)
if err != nil {
log.Fatal(err)
}
defer b.Close()
f, err := extract... |
package core
import (
"fmt"
"github.com/textileio/go-textile/pb"
)
func (t *Textile) Likes(target string) (*pb.LikeList, error) {
likes := make([]*pb.Like, 0)
query := fmt.Sprintf("type=%d and target='%s'", pb.Block_LIKE, target)
for _, block := range t.Blocks("", -1, query).Items {
info, err := t.like(block... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/6/16 10:04 上午
# @File : lt_二进制_位1的个数.go
# @Description :
# @Attention :
*/
package v2
func hammingWeight(num uint32) int {
count := 0
for num > 0 {
count++
num = num & (num - 1)
}
return count
}
|
//这是一个账号密码加密解密的例子
//程序员开发程序的基本礼貌,如果数据被泄露了,密码也不应该能被还原
//date:2018-06-12
//此时的感想:不想加班,我喜欢写文档,但是不想做需要用office的工作
//需要安装bcyrpt库
//go get golang.org/x/crypto/bcrypt
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
passwddok := "admin" //... |
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func headers(w http.ResponseWriter, req *http.Request) {
fmt.Printf("got headers:\n")
w.WriteHeader(500)
fmt.Fprintf(w, "got headers:\n")
for name, headers := range req.Header {
for _, h := range headers {
fmt.Printf("%v: %v\n", name, h)
fmt.Fprintf... |
package main
import (
"net/http"
"net/http/httptest"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Raindrops", func() {
Describe("Print Pling Plang Plong based on whether the number passed in the URL is divisible by 3, 5 or 7", func() {
Context("Print Pling if number is divisible ... |
package email
import (
"bytes"
"errors"
"fmt"
"net/smtp"
"github.com/ch3lo/overlord/logger"
"github.com/ch3lo/overlord/notification"
"github.com/ch3lo/overlord/notification/factory"
)
const notificationID = "email"
func init() {
factory.Register(notificationID, &emailCreator{})
}
// emailCreator implementa... |
package main
import (
"bufio"
"fmt"
"net"
"net/http"
)
type client struct {
connection net.Conn
reader *bufio.Reader
writer *bufio.Writer
clientNum int
port int
playerInfo connectionPlayerInfo
}
const debug = false
const NUMPLAYERS = 2
func main() {
fmt.Println("starting game service!")
init... |
package routes
import (
"context"
"encoding/json"
"log"
"net/http"
"push_article/pkg/token"
"firebase.google.com/go/v4/messaging"
"github.com/go-chi/chi"
)
type NotificationService struct {
*messaging.Client
token.Storage
}
func (ns *NotificationService) sendNotification(w http.ResponseWriter, r *http.Req... |
package 模拟
// ------------------- 方法1: 使用栈 -------------------
func minAddToMakeValid(S string) int {
stackStoringLeftParentheses := NewMyStack()
minCountOfAdding := 0
for i := 0; i < len(S); i++ {
if S[i] == '(' {
stackStoringLeftParentheses.Push(S[i])
continue
}
if stackStoringLeftParentheses.IsEmpty(... |
package e2e
import (
"path/filepath"
"testing"
"time"
"github.com/sensu/sensu-go/testing/testutil"
"github.com/sensu/sensu-go/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRoundRobinScheduling(t *testing.T) {
t.Parallel()
// Create two backends
backendA, clea... |
// package main
//
// import "fmt"
//
// func main() {
// var vector struct {
// X int
// Y int
// }
//
// vector.X = 2
// vector.Y = 5
// fmt.Println(vector) // {2 5}
// }
// package main
//
// import "fmt"
//
// type Vector struct {
// X int
// Y int
// }
//
// func main()... |
package version
import (
"fmt"
"strings"
)
type Info struct {
Name string
Tag string
Commit string
Branch string
}
// Version show version info
func (i *Info) Version() string {
parts := []string{i.Name, i.Tag, i.Branch, i.Commit}
for k, v := range parts {
if len(v) == 0 {
parts[k] = "unknown"
}... |
/*
* Copyright @ 2020 - present Blackvisor Ltd.
*
* 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 l... |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package glide
import (
"bytes"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"github.com/golang/dep"
"github.com/golang/dep/gps"
"github.com/golang/d... |
package main
import (
"fmt"
_ "github.com/denisenkom/go-mssqldb"
)
var (
/*
BuildVersion, BuildDate, BuildCommitSha are filled in by the build script
*/
BuildVersion = "<<< filled in by build >>>"
BuildDate = "<<< filled in by build >>>"
BuildComment = "<<< filled in by build >>>"
)
func main() {
fmt.Pr... |
package schema
import (
"time"
"gopkg.in/mgo.v2/bson"
)
type Device struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
UserId bson.ObjectId `json:"user_id" bson:"user_id,omitempty"`
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"... |
package core
import (
"context"
"errors"
"fmt"
"time"
"github.com/drand/drand/beacon"
"github.com/drand/drand/ecies"
"github.com/drand/drand/entropy"
"github.com/drand/drand/key"
"github.com/drand/drand/protobuf/drand"
"google.golang.org/grpc/peer"
)
// Setup is the public method to call during a DKG proto... |
package main
import (
"context"
"fmt"
"log"
"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter13/firebase"
)
func main() {
ctx := context.Background()
c, err := firebase.Authenticate(ctx, "collection")
if err != nil {
log.Fatalf("error initializing client: %v", err)
}
defer c.Close... |
package main
import (
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v4"
uuid "github.com/iris-contrib/go.uuid"
)
// Session middleware facilitates HTTP session management backed by gorilla/sessions.
// https://echo.labstack.com/middleware/session
func main() {
app := ... |
/*
This challenge is to take an alphabetical string as input and to apply the following conversion:
The first of each type of character of the string must stay, and must be immediately followed by an integer representing how many of these characters were in the original string. Any repeating characters must be omitte... |
package astiamqp
import (
"encoding/json"
"github.com/molotovtv/go-astilog"
"github.com/pkg/errors"
"github.com/streadway/amqp"
)
// Producer represents a producer
type Producer struct {
channel func() *amqp.Channel
configuration ConfigurationProducer
}
// AddProducer adds a producer
func (a *AMQP) AddP... |
package chatlog
import (
"fmt"
"os"
"testing"
)
func TestHandleChatItem(t *testing.T) {
c := New(os.Getenv("VIDEO_ID"))
err := c.HandleChat(func(renderer ChatRenderer) error {
switch renderer.(type) {
case *LiveChatViewerEngagementMessageRenderer:
fmt.Println(renderer.ChatMessage())
return nil
case... |
// 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 tfc
import (
"fmt"
"regexp"
"github.com/hyperledger/fabric/core/chaincode/shim"
tfcPb "github.com/stefanprisca/strategy-protobufs/tfc"
)
func handleTrade(APIstub shim.ChaincodeStubInterface, creatorSign []byte,
gameData tfcPb.GameData, payload tfcPb.TradeTrxPayload) (tfcPb.GameData, error) {
err := as... |
package nats
import (
"context"
"sync"
"github.com/nats-io/nats.go"
pubsub "github.com/zhangce1999/pubsub/interface"
)
var _ pubsub.Broker = &Broker{}
// Broker -
type Broker struct {
URL string
Opts *BrokerOptions
Handlers pubsub.HandlersChain
// if the topic has a prefix of some group, it must b... |
package main
import (
"math/rand"
"ms/sun/servises/model_service"
"ms/sun/scripts/facts/fact_utils"
)
func main() {
for i := 0; i < 10000; i++ {
if rand.Intn(10) < 2 {
factUnLike()
}else {
factLike()
}
}
}
func factLike() {
model_service.Like_LikePost(fact_util... |
package hateoas
import (
"fmt"
"reflect"
"strings"
)
type hateoasResource map[string]interface{}
func toHateoasResources(r []Resource, baseUrl string, resourceName string) []hateoasResource {
hateoasResources := make([]hateoasResource, len(r))
for index, value := range r {
hateoasResources[index] = toHateoas... |
package tests
import (
"../lib"
"testing"
)
func TestSum(t *testing.T) {
var a float64 = 5
var b float64 = 5
total := lib.Sum(a, b)
if total != 10 {
t.Error("Sum is wrong")
}
}
|
package manager
import (
sdk "github.com/identityOrg/oidcsdk"
"gopkg.in/square/go-jose.v2/json"
"log"
"net/http"
"net/url"
"path"
)
func (d *DefaultManager) ProcessDiscoveryEP(writer http.ResponseWriter, _ *http.Request) {
issuerUrl, err := url.Parse(d.Config.Issuer)
if err != nil {
http.Error(writer, err.E... |
package main
import (
"fmt"
"strings"
)
type person struct {
name string
age int
}
func main() {
var one person
fmt.Println("one: ", one)
one = person{name:"alice", age:30}
fmt.Println("one: ", one)
one = person{name:"fred"}
fmt.Println("one: ", one)
one = person{"jack", 20}
fmt.Println("one: ", one)
... |
package main
import (
"testing"
)
type nodeExpceted struct {
path string
nType nodeType
methods HTTPMethod
wildChild bool
indicesIsEmpty bool
childrenNum int
isLeaf bool
statusIsNil bool
}
func checkNodeValid(t *testing.T, n *node, e nodeExpceted) {
if n == nil ... |
package genKey
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"os"
)
func GenKey()([]byte, *ecdsa.PrivateKey){
//ECDSA KEYPAIR 생성
curve := elliptic.P256()
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
pubKey := append(privateKey.Pu... |
package test_persistence
import (
"reflect"
cdata "github.com/pip-services3-go/pip-services3-commons-go/data"
persist "github.com/pip-services3-go/pip-services3-mongodb-go/persistence"
"go.mongodb.org/mongo-driver/bson"
)
// extends IdentifiableMongoDbPersistence<Dummy, string>
// implements IDummyPer... |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package parser
import (
"github.com/npat-efault/godef/exp-go/token"
"os"
"testing"
)
var fset = token.NewFileSet()
var illegalInputs = []interface{}{
nil... |
package redis
import "gitee.com/johng/gf/g"
const prefix = "bbd_"
const cache = "cache"
func Set(key string, value []byte) error {
_, e := g.Redis(cache).Do("Set", prefix+key, value)
return e
}
func Clear() error {
_, e := g.Redis(cache).Do("FLUSHDB")
return e
}
func Get(key string) (interface{}, error) {
res... |
package oauth
import (
"encoding/json"
"errors"
"oauth-server-lite/g"
"oauth-server-lite/models/utils"
)
func CreateClient(client OauthClient) error {
db := g.ConnectDB()
err := db.Create(&client).Error
return err
}
func UpdateClient(client OauthClient) error {
db := g.ConnectDB()
err := db.Save(&client).E... |
/*
* 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 the Apache License, Version 2.0
* (the "License"); you may ... |
package permutations
import (
"testing"
"lib"
"fmt"
)
func TestPermutation(t *testing.T) {
testData := []struct {
input []int
output [][]int
}{
{[]int{1, 2, 3}, [][]int{{3, 2, 1}, {2, 3, 1}, {3, 1, 2}, {1, 3, 2}, {2, 1, 3}, {1, 2, 3}}},
{[]int{0, 1}, [][]int{{1, 0}, {0, 1}}},
{[]int{1}, [][]int{{1}}},... |
package main
import (
"fmt"
)
const x int = 10
const y = 10
func main() {
fmt.Println(x, y)
}
|
package health
import (
"testing"
"time"
"context"
"encoding/json"
)
type mockComponent struct {
timeout time.Duration
countFail int
status HealthComponentStatus
desc string
}
func (m *mockComponent) Check(ctx context.Context) HealthComponentState {
time.Sleep(m.timeout)
if m.countFail > 0 {
m.countFail... |
package standard
import "github.com/labstack/echo/v4"
func Register(group *echo.Group) {
group.POST("/standard/encrypt", Encrypt)
group.POST("/standard/decrypt", Decrypt)
}
|
package util
import (
"time"
mesh_proto "github.com/kumahq/kuma/api/mesh/v1alpha1"
"github.com/kumahq/kuma/pkg/core/resources/model"
"github.com/kumahq/kuma/pkg/util/proto"
)
type resourceMeta struct {
name string
version string
mesh string
creationTime *time.Time
modifi... |
package hello
import (
"fmt"
"html/template"
"net/http"
)
func init() {
http.HandleFunc("/sign", sign)
}
func sign(w http.ResponseWriter, r *http.Request) {
err := signTemplate.Execute(w, r.FormValue("content")) // HL
}
var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML)) // HL
const... |
package main
import (
"fmt"
"strings"
"time"
"golang.org/x/text/language"
)
type tmplIssueTemplateData struct {
Labels []string
Versions []string
Proxies []string
}
type tmplConfigurationKeysData struct {
Timestamp time.Time
Keys []string
Package string
}
type tmplScriptsGEnData struct {
Packa... |
package schema
// ErrorContainer represents a container where we can add errors and retrieve them.
type ErrorContainer interface {
Push(err error)
PushWarning(err error)
HasErrors() bool
HasWarnings() bool
Errors() []error
Warnings() []error
}
// StructValidator is a validator for structs.
type StructValidator ... |
// +build qml
package dialog
import (
"github.com/therecipe/qt/quick"
"github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/controller"
)
func init() {
deleteDialogController_QmlRegisterType2("Dialog", 1, 0, "DeleteDialogController")
}
type deleteDialogController struct {
quick.QQuickI... |
package display
import (
"html/template"
"github.com/GoAdminGroup/go-admin/template/types"
)
type Dot struct {
types.BaseDisplayFnGenerator
}
func init() {
types.RegisterDisplayFnGenerator("dot", new(Dot))
}
func (d *Dot) Get(args ...interface{}) types.FieldFilterFn {
return func(value types.FieldModel) inter... |
package dashSlicer
import (
"errors"
"sync"
)
type sliceData struct {
duration int
bitrate int
data []byte
}
type sliceDataContainer struct {
maxSliceCounter int
avSeparated bool
videoHeader []byte
audioHeader []byte
startNumber_av int
idx_av int
startNumber_a int
idx_a ... |
package persistence
import (
"context"
"fmt"
"github.com/philippgille/gokv"
"github.com/tinkerbell/pbnj/pkg/repository"
)
// GoKV store, methods implement repository.Actions interface.
type GoKV struct {
Ctx context.Context
Store gokv.Store
}
// Create a record.
func (g *GoKV) Create(id string, val reposito... |
// Copyright 2016-2021, Pulumi Corporation.
package provider
import (
"context"
"fmt"
"net"
gocidr "github.com/apparentlymart/go-cidr/cidr"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudformation"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.