text stringlengths 11 4.05M |
|---|
package entity
import (
"bytes"
"crypto/md5"
"fmt"
)
//easyeasyjson:json
type StatsRow struct {
hash string
Hostname string
Process *Process
Packet *Packet
}
func (s *StatsRow) Hash() string {
if s.hash == "" {
var buff bytes.Buffer
buff.WriteString(fmt.Sprintf("%v", s.Process.Path))
buff.Write... |
package util
import "fmt"
// LogErr of passed functions, most often deferred and the error is of no real interest
func LogErr(f ...func() error) {
for i := len(f) - 1; i >= 0; i-- {
if err := f[i](); err != nil {
fmt.Println("Encountered error:", err)
}
}
}
|
package rt
import "testing"
func TestCreateJob(t *testing.T) {
job := NewJob("test", []byte("{\"some\": 1}"))
if string(job.data.([]byte)) != "{\"some\": 1}" {
t.Error("job data incorrect, expected '{\"some\": 1}', got", job.data)
}
if job.jobType != "test" {
t.Error("job type incorrect, expected 'test', go... |
package db
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
// 构建一个连接器接口,所有实现这个接口的结构体都可以作为参数传入,每个单独的连接器
type IConnector interface {
SetConn(config map[string]string) // 设置连接器
GetConn() *sql.DB // 获取数据库连接器接口
Table(tableName string) IBuilder // 表 Builder,用于表的增删改查
Schema() ISchemaBuild... |
package main
import (
"fmt"
"mylog/test"
)
func main() {
cfg := LoadConfig()
fmt.Println("config:", cfg)
for i := 0; i < 10; i++ {
mainLog.Infof("this is my mainlog %v", i)
}
// test包就相当于我们项目中的子包
test.Test()
}
|
package main
import "fmt"
type pessoa struct {
nome string
idade int
}
//Seria o equivalente à um método do tipo, como se fosse uma classe.
func (p pessoa) apresentacao() {
fmt.Println("Eu sou um médoto de Pessoa!")
fmt.Print("Meu nome é ", p.nome, " e eu tenho ", p.idade, " anos.")
}
func main() {
jose := p... |
/*
* Amazon FreeRTOS Echo Server V1.1.1
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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 restrict... |
package crd
import (
"context"
v1 "github.com/rancher/rancher-operator/pkg/apis/rancher.cattle.io/v1"
"github.com/rancher/wrangler/pkg/crd"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/rest"
)
func List() []crd.CRD {
return []crd.CRD{
newCRD(&v1.Cluster{}, func(c crd.CRD) crd.CRD {
return c.... |
package requests
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
"github.com/atomicjolt/canvasapi/models"
"github.com/atomicjolt/string_utils"
)
// CreateExternalFeedGroups Create a new external feed for the course or... |
package opencc
// #cgo LDFLAGS: -lopencc
/*
#include<opencc/opencc.h>
*/
import "C"
type Config struct {
cfFile C.opencc_t
}
type ConfigType int
const (
ConfigTypeS2T ConfigType = 1
ConfigTypeS2TW ConfigType = 2
ConfigTypeS2TWP ConfigType = 3
ConfigTypeTW2S ConfigType = 4
ConfigTypeTW2SP ConfigType = 5
)
... |
package rpcevents
import (
"fmt"
"context"
bcm "github.com/hyperledger/burrow/blockchain"
"github.com/hyperledger/burrow/consensus/tendermint"
"github.com/hyperledger/burrow/event"
"github.com/hyperledger/burrow/event/query"
"github.com/hyperledger/burrow/execution/events"
"github.com/hyperledger/burrow/exec... |
package dao
import (
"fmt"
"strconv"
log "github.com/cihub/seelog"
"github.com/gocql/gocql"
"github.com/juliendsv/go-cassadmin/domain"
)
const (
clusterNodes = "127.0.0.1"
port = 19043
consistency = gocql.Quorum
defaultLimit = 100
)
type CassandraStore struct {
cluster gocql.ClusterConfig
Sess... |
package network
import (
"bytes"
"./messages"
"../config"
"../tools"
"../types"
)
func Process(connection *types.Connection) {
for {
msg := <-connection.Incoming
switch {
case msg.Type == 0x01:
if config.Password == "" {
connection.Outgoing<- messages.ConnectionApproved(connection.ConnectionLi... |
// Attribute mapper manager for dependency injection
package FlatFS
import (
"log"
)
type AttrMapperManager struct {
attrMappers map[string]AttrMapper
}
func NewAttrMapperManager() *AttrMapperManager {
return &AttrMapperManager{
attrMappers: make(map[string]AttrMapper, 0),
}
}
func (attrMapperManager *AttrMa... |
package helper
func StrArrContains(arr []string, e string) bool {
for _, str := range arr {
if str == e {
return true
}
}
return false
}
func IntArrContains(arr []int, e int) bool {
for _, n := range arr {
if n == e {
return true
}
}
return false
}
|
// Copyright (C) 2015-Present Pivotal Software, Inc. All rights reserved.
// This program and the accompanying materials are made available under
// the terms of the 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 th... |
package main
import (
"encoding/json"
"net/http"
"time"
"christine.website/cmd/site/internal"
"within.website/ln"
"within.website/ln/opname"
)
var bootTime = time.Now()
var etag = internal.Hash(bootTime.String(), IncrediblySecureSalt)
// IncrediblySecureSalt *******
const IncrediblySecureSalt = "hunter2"
fun... |
package main
import (
"github.com/vlad-doru/microhiro/gateway/app"
"os"
)
func main() {
// Get and start the application.
app := app.NewGateway()
app.Run(os.Args)
}
|
package serve
// NamespaceConfigration config for namespace object
type NamespaceConfigration struct{}
// ApplicationConfigration config for application object
type ApplicationConfigration struct {
Modules []string
Roles map[string][]string
}
// ModuleConfigration config for module object
type ModuleConfigration... |
package openshiftadmission
import (
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle"
mutatingwebhook "k8s.io/apiserver/pkg/admission/plugin/webhook/mutating"
validatingwebhook "k8s.io/apiserver/pkg/admission/plugin/webhook/validating"... |
// Copyright 2018 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 plug
import (
"mqtts/core"
"mqtts/utils"
)
func MQTTUnauthCheck(opts *core.TargetOptions) bool {
client := core.GetMQTTClient(opts)
connectError := client.Connect()
if connectError != nil {
utils.OutputNotVulnMessage(opts.Host, opts.Port, "Unauthorized access vulnerability not Exists")
return false
... |
package handler
import (
"encoding/json"
"net/http"
"strconv"
"go-crud/app/model"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
)
func GetAllProducts(db *gorm.DB, w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
categoryName := vars["name"]
category := getCategoryOr404(db, categoryName, ... |
// Copyright 2017 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 gymydb
import (
"fmt"
"database/sql"
"strconv"
"gylib/common"
"strings"
"crypto/md5"
"encoding/hex"
"time"
)
var mysqldb *sql.DB
var Slavedb []*sql.DB
type Db_conn struct {
Db_host string
Db_port string
Db_name string
Db_password string
Db_perfix string
}
var Db_perfix string
var ... |
package gw
import (
"fmt"
"github.com/oceanho/gw/conf"
)
type DefaultAuthManagerImpl struct {
store IStore
cnf *conf.ApplicationConfig
users map[string]*defaultUser
}
func DefaultAuthManager(state *ServerState) *DefaultAuthManagerImpl {
var authManager DefaultAuthManagerImpl
authManager.cnf = state.Applicat... |
// Created by cgo -godefs - DO NOT EDIT
// cgo -godefs ,,const.go
package syscall
const (
BRKINT = 0x2
IGNPAR = 0x4
ICRNL = 0x100
INPCK = 0x10
ISTRIP = 0x20
IXON = 0x400
OPOST = 0x1
ECHO = 0x8
ICANON = 0x2
IEXTEN = 0x8000
ISIG = 0x1
VTIME = 0x5
VMIN = 0x6
CLOCAL = 0x800
CREAD = 0x80
CBAU... |
package core
import (
"MCS_Server/global"
"fmt"
zaprotatelogs "github.com/lestrrat-go/file-rotatelogs"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"path"
"time"
)
var level zapcore.Level
func Zap() (logger *zap.Logger) {
_, err := os.Stat(global.MCS_Config.Zap.Dir)
if err != nil || os.IsNotExist(err) ... |
package main
import (
"bytes"
"fmt"
"html/template"
"io"
"log"
"strings"
chartrender "github.com/go-echarts/go-echarts/v2/render"
)
// Code from https://blog.cubieserver.de/2020/how-to-render-standalone-html-snippets-with-go-echarts/
// adapted from
// https://github.com/go-echarts/go-echarts/blob/master/tem... |
package main
import (
"log"
"net/http"
"time"
logrus "github.com/sirupsen/logrus"
)
func main() {
logrus.Info("dean") // never remove this line
router := NewRouter()
t := time.Tick(10 * time.Second)
go func() {
for {
<-t
CurrentTime = time.Now().UTC()
}
}()
log.Fatal(http.ListenAndServe(":8080"... |
package main
import (
"fmt"
"log"
"net"
"net/http"
"net/http/fcgi"
)
// fcgi包实现了FastCGI协议。目前只支持响应器的角色。
// 协议定义的地址:http://www.fastcgi.com/drupal/node/6?q=node/22
func main() {
// 服务监听
listener, err:= net.Listen("tcp", "127.0.0.1:8081")
if err != nil {
log.Fatal(err)
}
// 初始化一个自定义handler
srv := new(FastC... |
package odoo
import (
"fmt"
)
// AccountReconcileModel represents account.reconcile.model model.
type AccountReconcileModel struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
AccountId *Many2One `xmlrpc:"account_id,omptempty"`
Amount *Float `xmlrpc:"... |
package models
import (
"time"
)
// album represents data about a record album.
type LogEntry struct {
ID int `json:"id"`
ServiceId int `json:"service_id"`
Description string `json:"description"`
CreatedAt time.Time `json:"created_at"`
}
type Logs struct {
Logs []LogEntry `json:"logs"`
}
type Lo... |
package strategy_pattern
import (
"fmt"
)
type Duck struct {
quacker QuackStrategy
flyer FlyStrategy
name string
}
/* Passing down calls to duck's quacker and flyer */
func (d Duck) Quack() string {
return d.quacker.Quack(d)
}
func (d Duck) Fly() string {
return d.flyer.Fly(d)
}
/* Allows us to define ... |
package command
import (
"fmt"
"github.com/urfave/cli"
"github.com/wincentrtz/gobase/gobase/command/app"
"github.com/wincentrtz/gobase/gobase/command/db"
"github.com/wincentrtz/gobase/gobase/command/generate"
instance "github.com/wincentrtz/gobase/gobase/infrastructures/db"
)
func Command(c *cli.Context) error... |
package main
import (
"log"
"time"
)
type PayApp struct {
Command string
Timestamp int64
Payer string
ResultState bool
AccountType string
Account string
Amount float64
Data PayAppResult
}
type PayAppResult struct {
Account string
Url string
Code int
Message string
Da... |
// Copyright 2018-present The Yumcoder Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Author: yumcoder (omid.jn@gmail.com)
//
package datatype
import (
"crypto/rand"
"encoding/base64"
"github.com/gogo/protobuf/proto"
"test... |
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/cactus/go-statsd-client/statsd"
"io/ioutil"
"log"
"net/http"
"time"
)
type NginxResponse struct {
Connections struct {
Accepted int64 `json:"accepted"`
Active int64 `json:"active"`
Dropped int64 `json:"dropped"`
Idle int64 `json:... |
//Clinical Text Spell Checker
//What the tool does: Uses a large clinical dictionary to check for spelling mistakes in a large csv file
package main
import (
"bufio"
"flag"
"io"
"log"
"encoding/csv"
"fmt"
"os"
"github.com/VertisPro/fasthealth-tools/pkg/textutils"
)
/*
"Database support is provided through t... |
package models
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/bnagy/gapstone"
"strings"
)
func Disas(mem []byte, addr uint64, arch *Arch, pad ...int) (string, error) {
if len(mem) == 0 {
return "", nil
}
engine, err := gapstone.New(arch.CS_ARCH, arch.CS_MODE)
if err != nil {
return "", err
}
defer e... |
package manifest
import (
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
// makeTestFile creates a temporary test file and writes data into it
// It returns full path to newly created path or error if the file fails to be created
func makeTestFile(data []byte) (string, error) {
// create tem... |
package main
func decodeUint16(data []byte, offset int) uint16 {
return uint16(
data[offset]<<8 |
data[offset+1])
}
func encodeUint16(value uint16, data []byte, offset int) []byte {
data[offset] = (byte)(value >> 8)
data[offset+1] = (byte)(value)
return data
}
func decodeUint32(data []byte, offset int) uint... |
// 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 wevideo implements WeVideo operations.
package wevideo
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"chromiumos/tast/common/action"
"chromiumos/tast... |
// 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 filemanager
import (
"context"
"strings"
"time"
"chromiumos/tast/common/action"
"chromiumos/tast/ctxutil"
"chromiumos/tast/local/drivefs"
"chromiumos/tast/lo... |
// Copyright (c) 2017 Kuguar <licenses@kuguar.io> Author: Adrian P.K. <apk@kuguar.io>
//
// MIT License
//
// 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
//... |
package layout
import (
"fmt"
"github.com/cstockton/go-conv"
"strings"
)
type CheckBoxWidget struct {
Choice
Value []interface{} `json:"value"`
Layout string `json:"layout"`
}
func (this *CheckBoxWidget) GetValue() interface{} {
if this.Value == nil {
this.Value = []interface{}{}
}
return this.Va... |
package keepassrpc
import (
"crypto/sha256"
"fmt"
"math/big"
"os"
"testing"
)
var mult = []byte("" +
"\xb7\x86\x7f\x12\x99\xda\x8c\xc2\x4a\xb9" +
"\x3e\x08\x98\x6e\xbc\x4d\x6a\x47\x8a\xd0" +
"")
var k = new(big.Int).SetBytes(mult)
var username = "username"
var salt = "salt"
var password = "password"
var snp... |
package main
import (
"strconv"
"github.com/codegangsta/cli"
)
var ipOps []cli.Command
func init() {
ipdIdFlag := cli.StringFlag{
Name: "id, i",
Usage: "ID of the IP address",
}
ipOps = []cli.Command{
{
Name: "ip",
Description: "1&1 public IP operations",
Usage: "Public IP operatio... |
package models
import "github.com/go-swagger/go-swagger/strfmt"
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
/*User User user
swagger:model User
*/
type User struct {
/* Email email
*/
Email *string `json:"email,omitempty"`... |
package spotifyclient
import (
"github.com/ankjevel/spotify"
)
type MockSpotifyClient struct {
PlayerStateResponse struct {
p *spotify.PlayerState
e error
}
ShuffleResponse error
PlayResponse error
PauseResponse error
NextResponse error
PreviousResponse error
}
func (c *MockSpotifyClient) Pla... |
package ecs
// Graph is an auto-relation: one where both the A-side and B-side are the
// same Core system.
type Graph struct {
Relation
}
// NewGraph creates a new graph relation for the given Core system.
func NewGraph(core *Core, flags RelationFlags) *Graph {
G := &Graph{}
G.Init(core, flags)
return G
}
// In... |
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"path"
"crypto/md5"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type User struct {
ID primitive.ObjectID `json:"... |
package internal
import (
"testing"
"path/filepath"
"log"
"io/ioutil"
"os"
)
func createIndex(i string) (*Index, string) {
path := filepath.Join(os.TempDir(), "INDEX")
fd, err := os.Create(path)
if err != nil {
log.Fatal(err)
}
defer fd.Close()
_, err = fd.WriteStri... |
//go:build e2e_testing
// +build e2e_testing
package e2e
import (
"crypto/rand"
"fmt"
"io"
"net"
"os"
"testing"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/imdario/mergo"
"github.com/sirupsen/logrus"
"github.com/slackhq/nebula"
"github.com/slackhq/nebula/cert"
"g... |
package tokenizer
import (
"bytes"
"crypto/aes"
"crypto/sha256"
"encoding/base64"
"testing"
"time"
)
func newTokenizer() (*T, error) {
return New(
NewKey(aes.BlockSize),
NewKey(sha256.BlockSize),
nil,
)
}
func TestTokenizer(t *testing.T) {
_, err := New(NewKey(8), NewKey(8), nil)
if err == nil {
t.... |
package main
import (
"fmt"
"log"
"os/exec"
)
// DockerBuild ... カレントのDockerfileを元にenvタグを付けてbuildする
func DockerBuild() error {
if out, err := exec.Command(
"docker",
"build",
"--pull",
"-t",
ImageTags["env"],
".",
).CombinedOutput(); err != nil {
return fmt.Errorf("docker build: %s: %s", err, strin... |
package main
import (
"fmt"
"strings"
)
func t11() {
s := []int{1,2,3,5}
fmt.Println(s[0])
fmt.Println(s[:2])
s = append(s[:2], s[3:]...)
fmt.Println(s)
}
//[1 2]
//[1 2 5]
type T struct {
t int
}
func t12() {
s := []*T{}
s = append(s, &T{1})
s = append(s, &T{2})
t3 := &T{3}
s = append(s, t3)
s = appe... |
package main
import (
"os"
"path/filepath"
"flag"
"log"
"fmt"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/apimachinery/pkg/watch"
)
func main() {
var _namespace,
_labelSelector,
_fieldSelector string
//... |
// Copyright 2019 Yunion
//
// 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 writi... |
package subcmd
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/go-git/go-git/v5"
"github.com/vim-volt/volt/config"
"github.com/vim-volt/volt/fileutil"
"github.com/vim-volt/volt/gitutil"
"github.com/vim-volt/volt/lockjson"
... |
package main
func main() {
Fib(20)
}
// Возьмем fibo как пример того, что производительность ПК для одноядерной работы почти стоит на месте
// можно запустить на своем старом маке код и посмотреть бенчмарк для fibo, и сравнить с этим
func Fib(n int64) int64 {
switch n {
case 0:
return 0
case 1:
return 1
def... |
package msgraph
import (
"fmt"
"testing"
)
func GetTestGroup(t *testing.T) Group {
t.Helper()
groups, err := graphClient.ListGroups()
if err != nil {
t.Fatalf("Cannot GraphClient.ListGroups(): %v", err)
}
groupTest, err := groups.GetByDisplayName(msGraphExistingGroupDisplayName)
if err != nil {
t.Fatalf("... |
package ravendb
import (
"bytes"
"io"
"net/http"
)
var (
_ IOperation = &PutAttachmentOperation{}
)
type PutAttachmentOperation struct {
Command *PutAttachmentCommand
_documentID string
_name string
_stream io.Reader
_contentType string
_changeVector *string
}
func NewPutAttachmentOperat... |
package services
import (
"github.com/gobuffalo/validate/v3"
"github.com/gofrs/uuid"
movetaskorderops "github.com/transcom/mymove/pkg/gen/primeapi/primeoperations/move_task_order"
"github.com/transcom/mymove/pkg/models"
)
// HiddenMove struct used to store the MTO ID and the reason that the move is being hidden... |
package validate_binary_search_tree
import (
"algorithm-trials/questions/utils"
"math"
)
func isValidBST(root *utils.TreeNode) bool {
var isValid func(root *utils.TreeNode) bool
pre := math.MinInt64
isValid = func(node *utils.TreeNode) bool {
if node == nil {
return true
}
if !isValid(node.Left) {
... |
package typedkey
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/iotaledger/hive.go/ds/types"
"github.com/iotaledger/hive.go/kvstore/mapdb"
)
func Test(t *testing.T) {
// create a new mapdb instance
storage := mapdb.NewMapDB()
// create new StorableCommitment instance
storableCommitmen... |
package play
import (
"errors"
"log"
"github.com/joshprzybyszewski/cribbage/logic/pegging"
"github.com/joshprzybyszewski/cribbage/model"
"github.com/joshprzybyszewski/cribbage/server/interaction"
)
var _ PhaseHandler = (*peggingHandler)(nil)
type peggingHandler struct{}
func (*peggingHandler) Start(g *model.G... |
package model
type Cart struct {
ID int `json:"id" gorm:"column:id;primaryKey`
UserID int `json:"user_id" gorm:"column:user_id"`
ProductID int `json:"product_id" gorm:"column:product_id"`
}
func (Cart) TableName() string {
return "carts"
}
|
package provider
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/filecoin-project/go-legs"
"github.com/filecoin-project/go-legs/dtsync"
"github.com/go-resty/resty/v2"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-log/v2"
"github.com/ipld/go-ipld-prime"
"... |
package nats
import (
"time"
nats "github.com/nats-io/go-nats"
)
type Broker struct {
conn *nats.Conn
}
func NewBroker(conn *nats.Conn) *Broker {
return &Broker{conn: conn}
}
func (nb *Broker) Publish(topic, message string) error {
return nb.conn.Publish(topic, []byte(message))
}
func (n *Broker) Request(top... |
package xsql
import (
"github.com/emqx/kuiper/plugins"
"strings"
)
// ONLY use NewFunctionValuer function to initialize
type FunctionValuer struct {
funcPlugins *funcPlugins
}
//Should only be called by stream to make sure a single instance for an operation
func NewFunctionValuer(p *funcPlugins) *FunctionValuer {... |
package internal
import (
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Module_Run(t *testing.T) {
at := assert.New(t)
t.Run("success", func(t *testing.T) {
defer func() {
at.Nil(os.RemoveAll("testcase"))
}()
out, err := runCobraCmd(ModuleCmd, "testcase")
at.N... |
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package model
import (
log "github.com/sirupsen/logrus"
)
const (
// DatabaseMigrationStatusSetupIP indicates that database migration setup is still running.
DatabaseMigrationStatusSetupIP = "setup-i... |
package main
//872. 叶子相似的树
//请考虑一棵二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列
//举个例子,如上图所示,给定一棵叶值序列为(6, 7, 4, 9, 8)的树。
//
//如果有两棵二叉树的叶值序列是相同,那么我们就认为它们是叶相似的。
//
//如果给定的两个根结点分别为root1 和root2的树是叶相似的,则返回true;否则返回 false 。
//输入:root1 = [1,2,3], root2 = [1,3,2]
//输出:false
//
//
//提示:
//
//给定的两棵树可能会有1到 200个结点。
//给定的两棵树上的值介于 0 到 200 之间... |
package session
import (
"time"
uuid "github.com/satori/go.uuid"
"encoding/json"
"fmt"
"github.com/go-redis/redis"
)
// RedisStore represents a session.Store backed by redis.
type RedisStore struct {
//Redis client used to talk to redis server.
Client *redis.Client
//Used for key expiry time on redis.
Ses... |
package main
import (
"fmt"
)
func main() {
var min, max int
fmt.Println("entrez la borne basse")
fmt.Scanln(&min)
fmt.Println("entrez la borne haute")
fmt.Scanln(&max)
fmt.Println("///////")
for i := min + 2; i < max; i += 2 {
if min%2 == 0 {
fmt.Println(i)
} else {
fmt.Println(i - 1)
}
}
}... |
/*
* Copyright(C) 2020 EASTCOM-BUPT Inc.
* Author: wangpeng_1@ebupt.com
* Date: 2020-08-21 11:16:48
* LastEditTime: 2020-08-21 17:53:20
* LastEditors: wangpeng_1@ebupt.com
* Description:
*/
package kunxunReproduction
import (
"io/ioutil"
"gopkg.in/yaml.v2"
"fmt"
)
type conf struct {
Disks... |
package arrays
import "fmt"
// Return the concepts of the Chapter 4, about arrays.
func Call() {
fmt.Println("Arrays")
/*
Array declaration sintax with values:
Check that arrays have a max length predetermined, if the values at
those positions are not informed, they will be evalued with the default
value o... |
package main
import (
"go_code/execrise/redisexec/redisexec03/utils"
_ "fmt"
)
func main() {
conn := utils.Pool.Get()
defer conn.Close()
conn.Do("set", "k1", "v1")
conn.Do("flushdb")
} |
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
var once sync.Once
//单向通道,只能写入
func senttoch(ch1 chan<- int) {
for i := 0; i < 100; i++ {
ch1 <- i
}
//写入数据完成后,关闭chan,此时只能读不能写入
close(ch1)
wg.Done()
}
//单向通道 ch1只能读取,ch2只能写入
func getfromch(ch1 <-chan int, ch2 chan<- int) {
fmt.Println("start get")... |
package controllers
import (
"encoding/json"
"net/http"
"peribahasa/app/models"
"peribahasa/app/utils"
"strconv"
"github.com/gorilla/mux"
)
// CreateAsal controller
var CreateAsal = func(w http.ResponseWriter, r *http.Request) {
asal := &models.Asal{}
defer r.Body.Close()
err := json.NewDecoder(r.Body).Dec... |
package interpreter
import "errors"
import actor "github.com/filecoin-project/specs/systems/filecoin_vm/actor"
import addr "github.com/filecoin-project/specs/systems/filecoin_vm/actor/address"
import market "github.com/filecoin-project/specs/systems/filecoin_markets/storage_market"
import spc "github.com/filecoin-proj... |
package watcher
import (
"os"
)
type fileEventLog struct {
file *os.File
}
func (f fileEventLog) Emit(event Event) error {
_, err := f.file.Write(event.MarshalYAML())
f.file.WriteString("\n")
return err
}
func (f fileEventLog) Close() error {
return nil
}
func NewFileEventLog(file *os.File) (EventLog, error)... |
package main
import (
"fmt"
"time"
)
// 每个任务Task类型,可以抽象成一个函数;
type Task struct {
f func() error // 一个无参的函数类型
}
//通过一个NewTask 来创建一个task
func NewTask(fx func() error) *Task {
t := Task{
f: fx,
}
return &t
}
// Task 执行任务的方法
func (t *Task) Execute() {
t.f() // 调用任务所绑定的函数
}
// 有关协程池的定义及操作
type Pool struct {
I... |
// 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 leaderelect
import (
"time"
"github.com/MatrixAINetwork/go-matrix/ca"
"github.com/MatrixAINetwork/go-matrix/common"
"github.com... |
package main
import (
"github.com/BurntSushi/toml"
"log"
"path"
)
type OptionalLimits struct {
Hourly *int
Daily *int
Weekly *int
Monthly *int
}
type Config struct {
Defaults struct {
Limits OptionalLimits
Remote struct {
Limits OptionalLimits
}
}
Snapshot []struct {
Directory string
Des... |
package html5_test
import (
. "github.com/bytesparadise/libasciidoc/testsupport"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("cross references", func() {
Context("using shorthand syntax", func() {
It("with custom id to section above with rich title", func() {
source := `[[... |
package main
import (
"database/sql"
"log"
"net/http"
"os"
_ "github.com/go-sql-driver/mysql"
"github.com/ksbeasle/GoLang/pkg/models"
"github.com/ksbeasle/GoLang/pkg/models/mysql"
)
/*Run the command in this comment to run app
***************IMPORTANT******************
****************************************... |
// Copyright © 2020 Weald Technology Trading
// 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 a... |
package BLC
type PHBBlockData struct {
PHBAddrFrom string
PHBBlock []byte
}
|
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package macaroon
import (
"bytes"
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/zeebo/errs"
"storj.io/common/testcontext"
)
func TestSerializeParseRestrictAndCheck(t *testing.T) {
ctx := con... |
// 网页服务器1
package main
import (
"GoNet/goWeb"
"io"
"net/http"
)
// 一个文本框和一个提交按钮
const form2 = `<html><body><form action="#" method="post" name="bar">
<input type="text" name="in"/>
<input type="submit" value="Submit"/>
</form></html></body>`
func SimpleServer(w http.ResponseWriter, req *http.Re... |
package response_test
import (
"testing"
"github.com/shandysiswandi/echo-service/internal/infrastructure/app/response"
"github.com/stretchr/testify/assert"
)
func TestSuccess(t *testing.T) {
act := response.Success("message", nil)
ref := act.(response.SuccessBody)
assert.Equal(t, false, ref.Error)
assert.Equ... |
package commands
import (
"fmt"
"github.com/jessevdk/go-flags"
devspacecontext "github.com/loft-sh/devspace/pkg/devspace/context"
"github.com/loft-sh/devspace/pkg/devspace/devpod"
"github.com/loft-sh/devspace/pkg/devspace/pipeline/types"
"github.com/loft-sh/devspace/pkg/util/stringutil"
"github.com/pkg/errors"
... |
package main
import "fmt"
func main() {
x := retornaUmaFuncao()
y := x(3)
fmt.Println(y)
}
func retornaUmaFuncao() func(int) int {
return func(i int) int {
return i * 10
}
}
|
// 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 exiftool
import (
"strings"
"unicode"
"github.com/saferwall/saferwall/internal/utils"
)
const (
// Command to invoke exiftool scanner
cmd = "ex... |
package utils
import (
"regexp"
)
// Contains find is string in slices
func Contains(slices []string, comparizon string) bool {
for _, a := range slices {
if a == comparizon {
return true
}
}
return false
}
// IsEmail check email the real email string
func IsEmail(email string) bool {
re := regexp.MustC... |
// 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"
// TokenFilterMinHash token filter that hashes each token of the token stream
// and divdes the resulting hashes into buckets, keep... |
package rt
// Option is a function that modifies workerOpts
type Option func(workerOpts) workerOpts
//PoolSize returns an Option to set the worker pool size
func PoolSize(size int) Option {
return func(opts workerOpts) workerOpts {
opts.poolSize = size
return opts
}
}
//TimeoutSeconds returns an Option with th... |
package gorm2
import (
"context"
"errors"
"fmt"
"net/url"
"github.com/google/uuid"
"github.com/traPtitech/trap-collection-server/src/domain"
"github.com/traPtitech/trap-collection-server/src/domain/values"
"github.com/traPtitech/trap-collection-server/src/repository"
"github.com/traPtitech/trap-collection-se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.