text stringlengths 11 4.05M |
|---|
package theory
import (
"buddin.us/musictheory"
"buddin.us/musictheory/intervals"
lua "github.com/yuin/gopher-lua"
)
func newChord(state *lua.LState) int {
pitch := state.CheckString(1)
root, err := musictheory.ParsePitch(pitch)
if err != nil {
state.RaiseError(err.Error())
}
var (
name = state.CheckStr... |
package fakes
import "github.com/cloudfoundry-incubator/notifications/models"
type KindsRepo struct {
Kinds map[string]models.Kind
UpsertError error
TrimError error
FindError error
TrimArguments []interface{}
}
func NewKindsRepo() *KindsRepo {
return &KindsRepo{
Kind... |
package main
import (
"errors"
"image"
"image/color"
"image/jpeg"
_ "image/png"
"log"
"math"
"os"
"runtime"
"runtime/pprof"
"time"
"github.com/samuel/go-astar/astar"
)
func abs(v int) int {
if v < 0 {
return -v
}
return v
}
type ImageMap struct {
Pix []byte
YStride, XStride int
Widt... |
// ˅
package main
import (
"github.com/lxn/walk"
)
// ˄
type ColleagueRadioButton struct {
// ˅
// ˄
Colleague
radioButton *walk.RadioButton
// ˅
// ˄
}
func NewColleagueRadioButton(radioButton *walk.RadioButton) *ColleagueRadioButton {
// ˅
colleagueRadioButton := &ColleagueRadioButton{}
colleagueRa... |
package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
"strings"
)
func main() {
n := readInt64()
if n == 0 {
fmt.Println(0)
os.Exit(0)
}
if n < 10 {
fmt.Println(n)
os.Exit(0)
}
N := getNumberOfDigits(n)
maxnum := int64(0)
for i := 1; i < N; i++ {
digitVal := getDigitValue(n, i)
if digi... |
package models
// PokemonSpecies follows the naming convention provided here: https://pokeapi.co/docs/v2.html/#pokemon-species
//
// For the purposes of this test we have only implemented the fields we require
type PokemonSpecies struct {
Name string `json:"name"`
FlavorTextEntries []FlavorText `j... |
// Copyright (c) 2013 - Max Persson <max@looplab.se>
//
// 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 applicab... |
package main
import "fmt"
func twoSum(nums []int, target int) []int {
data := make(map[int]int)
for i, x := range nums {
if p, ok := data[target-x]; ok {
return []int{p, i}
}
data[x] = i
}
return nil
}
func main() {
fmt.Println(twoSum([]int{2, 7, 9, 11}, 9))
}
|
package background
type RepeatType string
const Repeat RepeatType = "repeat"
const RepeatX RepeatType = "repeat-x"
const RepeatY RepeatType = "repeat-y"
const NoRepeat RepeatType = "no-repeat"
const RepeatInitial RepeatType = "initial"
const RepeatInherit RepeatType = "inherit"
type PositionType string
const LeftTo... |
package cart
import (
"github.com/gingerxman/eel"
)
//CartItem Model
type CartItem struct {
eel.Model
UserId int
CorpId int
PoolProductId int `gorm:"index"`
ProductSkuName string `gorm:"size:256"`
ProductSkuDisplayName string `gorm:"size:256"`
Count int
}
func (self *CartItem) TableName() string {
return "ca... |
package onelogin
import (
"fmt"
"errors"
"strconv"
"github.com/op/go-logging"
)
func New(shard string, client_id string, client_secret string, subdomain string, loglevel logging.Level)(*OneLogin) {
ol := OneLogin{Shard:shard, Client_id: client_id, Client_secret:client_secret, SubDomain: subdomain}... |
package main
//for manual testing with browser
//have to delete browser cookies everytime because db is cleared on reset
import (
"github.com/hokora/bank/db/server"
"github.com/hokora/bank/recurring"
"time"
"log"
mgo "gopkg.in/mgo.v2"
"os"
"github.com/hokora/bank/http"
"github.com/hokora/bank/auth"
... |
use std::any::Any;
use std::fmt;
use std::fmt::Debug;
pub trait Object: Any {
fn serialize(&self) -> Vec<u8>;
}
pub trait ObjectLike: Object {
fn deserialize(Vec<u8>) -> Box<Object>;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedObject {
id: u64,
data: Vec<u8>,
}
impl<'a> From<&'a... |
package pgsql
import (
"testing"
)
func TestIntervalArray(t *testing.T) {
testlist2{{
data: []testdata{
{
input: string(`{"1 day","-5 years -4 mons -00:34:00"}`),
output: string(`{"1 day","-5 years -4 mons -00:34:00"}`)},
},
}, {
data: []testdata{
{
input: []byte(`{"1 day","-5 years -4 mo... |
/*
There is a sale going on in Chefland. For every 2 items Chef pays for, he gets the third item for free (see sample explanations for more clarity).
It is given that the cost of 1 item is X rupees. Find the minimum money required by Chef to buy at least N items.
Input Format
First line will contain T, number of tes... |
package main
import (
"fmt"
"sort"
)
func MaxNum(a []int) int {
//count := -1
if len(a) == 1 {
//temp := 0
//temp = a[0]
return a[0]
} else {
//sort.Ints(a)
sort.Sort(sort.Reverse(sort.IntSlice(a)))
a = a[0 : len(a)-1]
return MaxNum(a)
}
}
func main() {
fmt.Println(MaxNum([]int{2}))
}
|
package _725_Split_Linked_List_in_Parts
import (
"fmt"
"testing"
)
func TestSplitListToParts(t *testing.T) {
l := &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 3,
Next: nil,
},
},
}
k := 5
ret := splitListToParts(l, k)
for _, tl := range ret {
fmt.Println(tl)
}
}
|
package swap
import (
"context"
"errors"
"fmt"
"time"
"github.com/gagliardetto/solana-go"
associatedtokenaccount "github.com/gagliardetto/solana-go/programs/associated-token-account"
"github.com/gagliardetto/solana-go/programs/token"
"github.com/gagliardetto/solana-go/rpc"
"github.com/gopartyparrot/goparrot-... |
package main
import(
"github.com/martini-contrib/render"
)
// モデル
type Profile struct {
Name string
Skill []string
}
// モデル
type AboutViewModel struct {
Title string
Profile Profile
}
// Get("/about", ...) に対するコールバック関数
func AboutRender(r render.Render) {
// モデル作成
profile := Profile{ Name: "perrier1034", Ski... |
package main
import (
"io/ioutil"
"net/url"
"path"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
gitssh "github.com/go-git/go-git/v5/plumbing/transport/ssh"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
// setup... |
//go:build generate
package generated
import (
_ "github.com/calico-vpp/vpplink/pkg"
_ "go.fd.io/govpp/cmd/binapi-generator"
)
//go:generate go build -buildmode=plugin -o ./.bin/vpplink_plugin.so github.com/calico-vpp/vpplink/pkg
//go:generate go run go.fd.io/govpp/cmd/binapi-generator --no-version-info --no-sourc... |
package event
import (
"context"
"github.com/dwaynelavon/es-loyalty-program/internal/app/eventsource"
"github.com/dwaynelavon/es-loyalty-program/internal/app/user"
"github.com/pkg/errors"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type userEventHandler struct {
readRep... |
package invoice
import (
"time"
)
type ProcessedState struct {
}
func (s *ProcessedState) State(i *Invoice) State {
now := time.Now()
if i.DueDate.Before(now) {
return Failed
}
return WaitForPayment
}
func (s *ProcessedState) Publish(i *Invoice) error {
return InvoiceError{InvoiceErrorInvalidStateTransition... |
package tasks
// Sanitize returns a copy of the config sanitized for client side input.
// This is strictly a whitelist for safety.
func (src *Config) Sanitize() *Config {
dst := &Config{
Tasks: map[string]Task{},
}
for name, srcT := range src.Tasks {
dstT := Task{
Title: srcT.Title,
Description: s... |
package scheduler
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/apex/log"
"github.com/gocraft/work"
"gopkg.in/tomb.v2"
"git.scc.kit.edu/sdm/lsdf-checksum/internal/lifecycle"
"git.scc.kit.edu/sdm/lsdf-checksum/workqueue"
)
type ControllerScheduler interface {
SetInterval(interval time.Duration)... |
package main
import (
"fmt"
)
var (
coins = 50
users = []string{
"Matthew",
"Sarah",
"Augustus",
"Heidi",
"Emilie",
"Peter",
"Giana",
"Adriano",
"Aaron",
"Elizabeth",
}
distribution = make(map[string]int, len(users))
)
//自定义类型
type myInt int
// 类型别名
type yourInt = int
var a rune
func m... |
package socket
import (
"strconv"
"chatAppServer/models"
socketio "github.com/googollee/go-socket.io"
)
/*GroupData Socket组信息*/
type GroupData struct {
Id int
Phone string
NickName string
}
/*GroupMsgMount 挂载监听*/
func GroupMsgMount(server socketio.Server) {
JoinGroupRoom(server)
SendGroupMsg(server)... |
package main
func celsiusToFahrenheit(temp float64) float64 {
return (temp - 32) * (5 / 9)
}
/*
Lowercase == private method
Private methods don't need comments!
*/
|
package model_test
import (
"buildings/platform/model"
. "buildings/platform/model"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Building", func() {
var (
dummyBuilding Building
dummy2Building Building
updateBuilding Building
emptyBuilding Building
)
BeforeEach(func() {... |
package log
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"gorestfulapiforcms/pkg/setting"
"log"
"os"
"strconv"
"time"
)
var absolute_file_name = ""
func init() {
//用数组串联整个目录结构,没有哪层就创建哪层 获取日志写入路径没有则创建
now := time.Now()
file_name := strconv.Itoa(now.Day()) + ".log"
var paths = ... |
package main
import (
"database/sql"
"encoding/json"
"flag"
"fmt"
"github.com/garyburd/redigo/redis"
"net/http"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/gin-gonic/gin"
"strings"
)
type Mate struct{
m_Name string
Chinese string
English string
Math string
}
type list struct{
fileName string
}... |
package main
import (
"encoding/json"
"fmt"
"github.com/gofiber/fiber"
"github.com/gofiber/logger"
"os"
)
var version = "$VERSION"
type Hello struct {
Hello string `json:"hello"`
Version string `json:"version"`
}
func main() {
appSettings := new(fiber.Settings)
appSettings.CaseSensitive = true
appSetti... |
// Copyright 2015 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package dht
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
queue "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore/queue"
)
func TestDialQueueGrowsOnSlowDials(t *testing.T) {
in := queue.NewChanQu... |
package model
import (
"fmt"
)
type Response struct {
Status string `json:"status"`
Copyright string `json:"copyright"`
}
func PropublicaModel() {
fmt.Println("PropublicaModel")
} |
package main
import (
"bytes"
"fmt"
"github.com/coreos/go-etcd/etcd"
"github.com/miekg/dns"
"github.com/rcrowley/go-metrics"
"net"
"strconv"
"strings"
"sync"
"time"
)
type Resolver struct {
etcd *etcd.Client
etcdPrefix string
defaultTtl uint32
}
type EtcdRecord struct {
node *etcd.Node
ttl uint... |
package foundation
import (
"html/template"
"testing"
"github.com/stretchr/testify/assert"
)
// TestDelimiters runs
func TestDelimiters(t *testing.T) {
assert := assert.New(t)
d := Delimiters{}
assert.False(d.isValid())
d.Left, d.Right = "[%", "%]"
assert.True(d.isValid())
l, r := d.Get()
assert.Equal("[... |
// This package helps in counting number of segment when we send text using twilio service.
// Twilio services charge on number of segments present in text.
package smsSegment
import (
"math"
)
// Define constants
const (
EncodingGSM = "GSM"
EncodingUCS2 = "UCS-2"
GSMChracter... |
package lengthsafe
import (
"os"
"strings"
"sync/atomic"
"time"
"golang.org/x/sys/unix"
"git.scc.kit.edu/sdm/lsdf-checksum/internal/osutils"
)
const (
PathMax uint = 4096
POSIXSymlinkMax uint = 255
findBoundsBaseLength uint = 256
sampleStr string = "0123456789"
symlinkProgres... |
/*
Create a strut type, Virtmach, to track information about virtual machines.
Your record can track whatever you'd like, but values like ip, hostname, diskgb, ram, could all be possible values.
Create at least two (2) methods that allow you to interact with your strut. If you come up with your own working solution, ... |
package protoform
import "regexp"
type mapTypeExtract struct {
expr *regexp.Regexp
matches [][]string
}
func (m *mapTypeExtract) compile() {
m.expr = regexp.MustCompile(`.*Map\<(.+)\>.*`)
}
func (m mapTypeExtract) matchIndex() int {
return 0
}
func (m mapTypeExtract) groupIndex() int {
return 1
}
func (m *m... |
package main
import (
"encoding/json"
"fmt"
"github.com/julienschmidt/httprouter"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"io/ioutil"
"log"
"net/http"
)
type (
// ComponentController represents the controller for operating on the Component resource
ComponentController struct {
session *mgo.Session
}
)
... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//208. Implement Trie (Prefix Tree)
//Implement a trie with insert, search, and startsWith methods.
//Note:
//You may assume that all inputs are consis... |
// 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 main
import (
"fmt"
"html/template"
"net/url"
"strconv"
"time"
"github.com/go-macaron/gzip"
"github.com/looyun/feedall/controllers"
"github.com/looyun/feedall/middleware"
"github.com/looyun/feedall/models"
"github.com/looyun/feedall/parse"
macaron "gopkg.in/macaron.v1"
)
const (
Minute = 60
Hour... |
package models
import (
"fmt"
"cloud.google.com/go/storage"
"context"
"api-gaming/internal/config"
)
// GetVideo - Return storage bucket handle data.
func GetVideo() *storage.BucketHandle {
return config.StorageConn()
}
// ReadFile - Read a file from Google Cloud storage.
func ReadFile(fileName string) *storage... |
/*
* @lc app=leetcode.cn id=14 lang=golang
*
* [14] 最长公共前缀
*/
package solution
import "strings"
// @lc code=start
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
} else if len(strs) == 1 {
return strs[0]
}
prefix := strings.Builder{}
for i := 0; true; i++ {
if i >= len(... |
package string
import (
"strings"
"regexp"
)
/**
算法的实现逻辑可以参考: https://segmentfault.com/a/1190000004881457
设计思想:
将中文数学转换成阿拉伯数字。
将中文权位转换成10的位数。
对每个权位依次转换成位数并求和。
零直接忽略即可。
解决的问题:
1.一旦字符串中 含有非数字 非数学单位的文字 解析会出问题 已解决
2.字符串为十,解析出问题。直接判断第0个位置如果是权重单位,则特殊处理 已解决
*/
var chNumChar = map[string]int{
"零": 0, "一": 1, "二": 2... |
package main
import "fmt"
// 236. 二叉树的最近公共祖先
// 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
// 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
// 说明:
// 所有节点的值都是唯一的。
// p、q 为不同节点且均存在于给定的二叉树中。
// https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
func main... |
package service
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
"gin-vue-admin/model/request"
"gin-vue-admin/model/response"
)
// @title CreateTitUser
// @description create a TitUser
// @param user model.TitUser
// @auth (2020/04/05 20:22)
// @return err ... |
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 requir... |
package authorize
import (
"context"
"strings"
envoy_service_auth_v3 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v3"
"github.com/go-jose/go-jose/v3/jwt"
"github.com/rs/zerolog"
"github.com/pomerium/pomerium/authorize/evaluator"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/p... |
package mysql
import (
"database/sql"
"encoding/json"
"github.com/bearname/videohost/internal/common/db"
"github.com/bearname/videohost/internal/videoserver/domain"
dto2 "github.com/bearname/videohost/internal/videoserver/domain/dto"
"github.com/bearname/videohost/internal/videoserver/domain/model"
log "github.... |
package router
import (
"fmt"
"github.com/ijidan/jgo/controller"
"github.com/ijidan/jgo/jgo/jlogger"
"github.com/ijidan/jgo/jgo/jrouter"
"net/http"
)
const HttpHost = "127.0.0.1"
const HttpPort = int64(8080)
//注册n
func Registry() {
//控制器
index := controller.IndexController{}
user := controller.UserController... |
package types
import (
"testing"
"github.com/stretchr/testify/require"
sdk "github.com/irisnet/irishub/types"
)
func TestValidateParams(t *testing.T) {
// check that valid case work
defaultParams := DefaultParams()
err := ValidateParams(defaultParams)
require.Nil(t, err)
// all cases should return an error... |
package gbinterface
type IMessage interface {
GetMsgId() uint32
GetMessgLen() uint32
GetData() []byte
SetMsgId(uint32)
SetData([]byte)
SetDataLen(uint32)
}
|
package ama
import (
"log"
"net/http"
"io/ioutil"
"github.com/itsabot/abot/shared/datatypes"
"github.com/itsabot/abot/shared/nlp"
"github.com/itsabot/abot/shared/plugin"
)
var p *dt.Plugin
func init() {
// Abot should route messages to this plugin that contain any combination
// of ... |
//funcoes variativas: recebem parametros variaveis
package main
import "fmt"
func printAprovados(aprovados ...string) {
for _, aluno := range aprovados {
fmt.Println(aluno)
}
}
func main() {
aprovados := []string{"ytallo", "gabriel", "pessoa", "leda"} //slice=nao definimos tamanho
printAprovados(aprovados...)
... |
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"opentsp.org/internal/config"
"opentsp.org/internal/flag"
"opentsp.org/internal/relay"
"opentsp.org/internal/restart"
"opentsp.org/internal/tsdb/filter"
"opentsp.org/internal/validate"
)
type Config struct {
Filter []filter.Rule ... |
// Package teststruct - myteststruct.go
package teststruct
// MyTestStruct test
type MyTestStruct struct {
X int
Y int
}
// SetValues - Call a method to do stuff
func (m *MyTestStruct) SetValues(x, y int) {
m.X = x
m.Y = y
}
// Add - add the two values
func (m MyTestStruct) Add() int {
return m.X + m.Y
}
// Mu... |
package lockservice
// RPC definitions for a simple lock service.
// Lock(lockname) returns OK=true if the lock is not held.
// If it is held, it returns OK=false immediately.
type LockArgs struct {
// Go's net/rpc requires that these field
// names start with upper case letters!
Lockname string // lock name
UUID... |
package cage
import (
"encoding/base64"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ecs"
"os"
"path/filepath"
)
type Envars struct {
_ struct{} `type:"struct"`
Region *string `json:"region" type:"string"`
Cluster ... |
package delivery
import (
"encoding/json"
"github.com/Arkadiyche/bd_techpark/internal/pkg/models"
"github.com/Arkadiyche/bd_techpark/internal/pkg/thread"
"github.com/gorilla/mux"
"net/http"
)
type ThreadHandler struct {
UseCase thread.UseCase
}
func (th *ThreadHandler) Create(w http.ResponseWriter, r *http.R... |
package dto
type ExerciseStarted struct {
ExerciseId int `json:"exercise_id" db:"ExerciseId"`
UserId int `json:"user_id" db:"UserId"`
IsCompleted bool `json:"is_completed" db:"IsCompleted"`
StartDate *TimeJson `json:"start_date" db:"StartDate"`
CompleteDate *TimeJson `json:"complete_date" db:"CompleteDate"`
}
|
package main
import (
"fmt"
"github.com/jackytck/projecteuler/tools"
)
func count(p, r int) (int, []int) {
var pos []int
digits := tools.Digits(p)
for i, d := range digits {
if d == r && i != len(digits)-1 {
pos = append(pos, i)
}
}
return len(pos), pos
}
func replace(p, r int, pos []int) int {
digit... |
package main
import (
"fmt"
"sync"
)
/**
RWMutex 读写锁,同样没有记录当前是谁持有此锁,所以如果使用不当容易发生死锁现象
例如,最常见的不可复制
1 RWMutex 读写锁,是写优先,什么是锁优先? 当前有读锁持有锁时,写锁也会进行等待,只是此时后面来的读锁要等待写锁。
这就是写锁的优先级体现(此时会不会有其他读锁在等待呢? 不会,因为读读不互斥)
*/
func RWT(mutex sync.RWMutex) {
mutex.Lock()
defer mutex.Unlock()
fmt.Println("加锁")
}
func main() {
va... |
package connectors
import (
"fmt"
"errors"
"encoding/json"
"github.com/go-playground/validator/v10"
log "github.com/sirupsen/logrus"
)
var (
// define custom errors
ErrInvalidYelpMetadata = errors.New("Invalid yelp metadata")
// create new validator
validate = validator.New()
)
... |
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package cache
import (
"bytes"
"fmt"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCache(t *testing.T) {
t.Parallel()
conf := Config{}
var rmKey, rmVal []byte
conf.OnDelete = func(key, val []byte) {
rmKey = key
rmVal = val
}
conf.MaxSize = 12
conf.MaxElementSize = 12
conf.MaxCoun... |
package k8s
import (
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
// Client ...
type Client struct {
c *kubernetes.Clientset
}
// NewClient creates new Kubernetes client.
func NewClient() (*Client, error) {
config, err := rest.InClusterConfig(... |
package fileversion
import "github.com/scjalliance/drivestream/resource"
// A Map is a map of file versions.
type Map interface {
// List returns a list of version numbers for the file.
List() (v []resource.Version, err error)
// Ref returns a file version reference for the version number.
Ref(v resource.Version... |
package utils
import "fmt"
type RowRecord struct {
timestamp int64
fieldList []Field
}
func NewRowRecord(timestamp int64, fieldList []Field) *RowRecord {
r_ := &RowRecord{}
r_.timestamp = timestamp
r_.fieldList = fieldList
return r_
}
func (r_ *RowRecord) AddField(f Field) {
r_.fieldList = append(r_.fieldLis... |
// Copyright 2020 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
package server
import (
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/jackc/pgx"
"github.com/jackc/yakstak/server/handlers"
)
type TodoRow struct {
id int32
body string
done bool
}
func Serve() {
db, err := createDB()
if err != nil {
panic(err)
}
r := chi.NewRout... |
package open_resource_discovery
import (
"encoding/json"
"regexp"
"strings"
"time"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/go-ozzo/ozzo-validation/v4/is"
"github.com/kyma-incubator/compass/components/director/internal/model"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
)
// Disc... |
package monitorcontroller
import (
"monitor/models"
)
// @Title GenMonitor
// @Description view statistics request
// @Success 200 {object} responses.BoolResponse
// @router /genmonitor [get]
func (this *MonitorController) GenMonitor() {
m := models.GetMonitorModel()
if m != nil {
resp := m.GetAllInfoForCharti... |
package main
import (
"flag"
"github.com/golang/glog"
"github.com/peteabre/ocp-client-go/pkg/ocpclient"
"github.com/spf13/cobra"
rapiv1 "github.com/peteabre/ocp-client-go/pkg/route/api/v1"
"os"
)
var kubeconfig *string
var metricsPort *int
func main() {
handleErr(newCmd().Execute())
}
func init() {
// We lo... |
/*
Copyright 2022 The KubeVela 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 to in writing, softw... |
package term
import (
"time"
"github.com/brigadecore/brigade/sdk/v3"
"github.com/gdamore/tcell/v2"
)
const (
textGreen = "[green]"
textGrey = "[grey]"
textRed = "[red]"
textWhite = "[white]"
textYellow = "[yellow]"
)
var colorsByWorkerPhase = map[sdk.WorkerPhase]tcell.Color{
sdk.WorkerPhaseAborted: ... |
package mathematics
import (
. "github.com/numacci/go-algorithm/stl/function"
"math"
)
// Eratosthenes returns prime numbers in [1, n]
func Eratosthenes(n int) []int {
primes := make([]int, 0, n)
isPrime := make([]bool, n+1)
for i := 2; i <= n; i++ {
isPrime[i] = true
}
for i := 2; i <= n; i++ {
if !isPr... |
package syndicate
import (
"fmt"
"sync"
pb "github.com/getcfs/megacfs/syndicate/api/proto"
)
type RingSubscribers struct {
sync.RWMutex
subs map[string]chan *pb.Ring
}
func (s *Server) addRingSubscriber(id string) chan *pb.Ring {
s.ringSubs.Lock()
defer s.ringSubs.Unlock()
c, exists := s.ringSubs.subs[id]
... |
// 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... |
/*
* Copyright (c) 2018 Jeffrey Walter <jeffreydwalter@gmail.com>
*
* 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, c... |
package main
import "fmt"
func main() {
// a := 'a' //rune ?
// z := 'z'
// fmt.Println(int(a)," ",int(z)) //print ascii
// var b int=68
// fmt.Println(string(b),"\n") //print character from ascii
// q :=[5]int{68,69,70,71,72}
// for i:=0;i<=4;i++{
// fmt.Println(string(q[i]))
// }
var input [5]rune
... |
package drivers
// 存储设备驱动接口
//type Driver interface {
// Register(*Service, ...RegisterOption) error
// Deregister(*Service) error
//}
|
package main
import "testing"
func TestMultiply(t *testing.T){
var v int
v = multiply([]int{1,4,8,6}...)
exp := 192
if v != exp {
t.Errorf("Expected: %v\nGot: %v\n", exp, v)
}
var w int
input := []int{1, 4, 8, 0}
w = multiply(input...)
exp = 0
if w != exp {
t.Errorf("Expected: %v\nGot: %v\n", exp, w)
}... |
package cli
import (
"testing"
)
func TestValidateAlphaNumeric(t *testing.T) {
rule := "alphaNumeric"
testCases := []struct {
name string
ui string
ph string
v []validator
want bool
}{
{
"letters",
"abc",
"var1",
[]validator{{
expression: "",
fields: []string{"var1"},
... |
package streaming
import (
"fmt"
"github.com/gorilla/mux"
"github.com/jlingohr/p2pvstream/hls"
"github.com/jlingohr/p2pvstream/settings"
"github.com/jlingohr/p2pvstream/stringutil"
"log"
"net/http"
"os"
"sync"
"time"
)
type DiscoveredFile struct {
Filename string
NodeName string
Timestamp int64
}
type... |
package manager
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"testing"
)
func getTestServer() (*Server, *httptest.Server) {
m := new(Server)
m.startFileWatcher()
handler := m.getManagerRouting()
server := httptest.NewServer(handler)
return m, server
}
func TestStaticServing(t ... |
package api
import (
"net/http"
"github.com/gin-gonic/gin"
"advance-go/internal/config"
"advance-go/internal/ping"
"advance-go/internal/project"
"advance-go/internal/score"
)
type Route struct {
Name string
Path string
Method string
Endpoint gin.HandlerFunc
}
func Init(conf *config.Config) http.... |
package forms
import (
"strings"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego/validation"
"github.com/imsilence/gocmdb/server/cloud"
"github.com/imsilence/gocmdb/server/models"
)
type PlatformCreateForm struct {
Name string `form:"name"`
Type string `form:"type"`
Addr string `form:"addr"... |
// Copyright (c) 2013-2015 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package legacyrpc
import "github.com/btcsuite/btclog"
var log = btclog.Disabled
// UseLogger sets the package-wide logger. Any calls to this function must be
// made... |
package main
import (
"fmt"
"net/http"
"strconv"
"strings"
)
const cookieName = "__user_counter"
func main() {
http.HandleFunc("/", incrementCookie)
fmt.Println("listening on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
func incrementCookie(w http.ResponseWriter, r *http.Request) {
// first, ... |
package reader
import (
"errors"
"io"
"io/ioutil"
)
type rawReader struct {
input io.Reader
}
func (r rawReader) Unmarshal(object interface{}) error {
return errors.New("unable to unmarshal plain text")
}
func (r rawReader) Valid() bool {
return true
}
func (r rawReader) Reader() (io.Reader, error) {
return... |
// Package worker implements a worker node. A worker node can connecto to a
// single master node and replicate its data.
package worker
|
package main
import (
"fmt"
"github.com/achakravarty/30-days-of-go/day7"
)
func main() {
var size int
fmt.Scanf("%d\n", &size)
arr := make([]int, size)
for i := 0; i < size; i++ {
fmt.Scanf("%d", &arr[i])
}
outArr := day7.Reverse(arr)
for i := 0; i < size; i++ {
fmt.Printf("%d ", outArr[i])
}
}
|
package gosnowth
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
const graphiteMetricsTestData = `[
{
"leaf": true,
"name": "11223344-5566-7788-9900-aabbccddeeff.test;test=test",
"leaf_data": {
"uuid": "11223344-5566-7788-9900-aabbccddeeff",
"name": "t... |
package asset
import (
sdk "github.com/irisnet/irishub/types"
)
// InitGenesis - store genesis parameters
func InitGenesis(ctx sdk.Context, k Keeper, data GenesisState) {
if err := ValidateGenesis(data); err != nil {
panic(err.Error())
}
k.SetParamSet(ctx, data.Params)
// init gateways
for _, gateway := ran... |
package nilchan
import "fmt"
// CheckChanAndMake cheks if chan of type int is nil and make it
func CheckChanAndMake() {
var a chan int
if a == nil {
fmt.Println("channel is nil")
a = make(chan int)
fmt.Printf("Type of channel is %T", a)
if a == nil {
fmt.Println("channel is nil again")
}
}
}
|
package k8s
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
)
type ContainerLogsImpl struct {
namespace string
podName string
container corev1.Container
}
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.