text stringlengths 11 4.05M |
|---|
package ds
import (
"fmt"
"reflect"
"testing"
)
func ExampleRepeat() {
res := Repeat("b")
fmt.Println(res)
}
func TestAll(t *testing.T) {
t.Run("running Integers Add test", func(t *testing.T) {
sum := Add(1, 2)
expected := 3
if sum != 3 {
t.Errorf("expected '%d' but got '%d'", expected, sum)
}
})
... |
package main
import (
"github.com/DanielRenne/mangosNode/pair"
"log"
"time"
)
const url = "tcp://127.0.0.1:600"
func main() {
var node pair.Node
err := node.Connect(url, handlePairMessage)
if err != nil {
log.Printf("Error: %v", err.Error)
}
//Code a forever loop to stop main from exiting.
for {
time... |
package LeetCode
import "strconv"
var BinaryTreePathsInput = &TreeNode{
Val:1,
Left:&TreeNode{
Val:2,
Right:&TreeNode{
Val:5,
},
},
Right:&TreeNode{
Val:3,
},
}
func ConcatBinaryTreePath(pre string, node *TreeNode, list *[]string) {
if node == nil {
return
}
if len(pre) > 0 {
pre +="->"+strcon... |
package v039
import (
"fmt"
"strings"
)
// GenesisState is the head state of all scopes with history.
type GenesisState struct {
ScopeRecords []Scope `json:"scope_records,omitempty"`
// NOTE: this comes from the v39 spec module that was merged in. The migrate step should copy this over
Specifications []Contract... |
package bus
import (
"context"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber/server/types"
)
func (b *Bus) doCreateConnection(_ context.Context, msg *Message) error {
b.log.Debugf("running doCreateCon... |
package Problem0306
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
num string
ans bool
}{
{"0000000000", true},
{"10112", true},
{"101", true},
{"112358", true},
{"199100199", true},
{"1991001991", false},
{"11", false},
{"00123", false},
... |
package irc
import (
"strings"
"awesome-dragon.science/go/goGoGameBot/internal/irc/ctcp"
"awesome-dragon.science/go/goGoGameBot/pkg/event"
"awesome-dragon.science/go/goGoGameBot/pkg/util"
)
// HookMessage hooks on messages to a channel
func (i *IRC) HookMessage(f func(source, channel, message string, isAction bo... |
package main
import (
"fmt"
"math"
)
//靜態方法 (Static Method)
type Point struct{
x,y float64
}
func newpoint(x,y float64) *Point {
p := new(Point)
p.SetX(x)
p.SetY(y)
return p
}
//SetX is method
func (p *Point) SetX(x float64) {
p.x = x
}
//SetY is method
func (p *Point) SetY(y float64) {
p.y = y
}
//X is m... |
package styles
import "github.com/tumasgiu/go-mapbox/lib/base"
type Anchor string
const (
AnchorMap Anchor = "map"
AnchorViewport Anchor = "anchor"
)
// https://docs.mapbox.com/mapbox-gl-js/style-spec/#light
type Light struct {
Anchor Anchor `json:"anchor,omitempty"`
Color string `json:"color,... |
package agent
import (
"sync"
"golang.org/x/net/context"
"github.com/Sirupsen/logrus"
"github.com/bryanl/dolb/dolbutil"
"github.com/bryanl/dolb/firewall"
"github.com/bryanl/dolb/kvs"
"github.com/bryanl/dolb/service"
"github.com/gorilla/mux"
)
// Config is configuration for the agent api.
type Config struct ... |
package main
import (
"flag"
"log"
"strings"
pkg "github.com/ValerianRousset/Peerster"
)
func main() {
uiPort := flag.String("UIPort", "10000", "port for the client to connect")
gossipAddr := flag.String("gossipAddr", "127.0.0.1:5000", "port to connect the gossiper server")
name := flag.String("name", "nodeA"... |
package sort
import "fmt"
func SelectionSort() {
s := []int{23, 42, 35, 10, 34}
for i := 0; i < len(s); i++ {
for j := i + 1; j < len(s); j++ {
if s[i] > s[j] {
s[i], s[j] = s[j], s[i]
}
}
}
fmt.Println(s)
}
|
// Migration script to backfill the branches table with default branch rows
package main
import (
"database/sql"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/bradleyfalzon/ghinstallation"
_ "github.com/go-sql-driver/mysql"
"github.com/google/go-github/v28/github"
"github.com/malware-unicorn/managed... |
package Data
import (
"crypto/md5"
"encoding/hex"
uuid "github.com/satori/go.uuid"
"github.com/team-zf/framework/dal"
"github.com/wuxia-server/login/Control"
"github.com/wuxia-server/login/DataTable"
"math/rand"
"time"
)
func GetAccountByToken(token string) (account *DataTable.Account) {
account = DataTable.... |
/*
* @lc app=leetcode id=1122 lang=golang
*
* [1122] Relative Sort Array
*/
// @lc code=start
func relativeSortArray(arr1 []int, arr2 []int) []int {
count := make([]int, 1001)
result := make([]int, 0, len(arr1))
for _, num := range arr1 {
count[num]++
}
for _, num := range arr2 {
for j := 0; j < count[n... |
package backoffice
import (
"net/http"
"github.com/gorilla/mux"
"github.com/Zenika/marcel/config"
"github.com/Zenika/marcel/httputil"
"github.com/Zenika/marcel/module"
)
const index = "/index.html"
// Module creates backoffice module
func Module() *module.Module {
var fs http.FileSystem
// Set default URIs... |
package logic
func init() {
HandlerMap = make(map[string]Handler)
HandlerMap["FluctuateHandler"] = &FluctuateHandler{}
}
|
package sql
import (
"context"
"fmt"
"github.com/imrenagi/go-payment"
"github.com/imrenagi/go-payment/gateway/midtrans"
"gorm.io/gorm"
"github.com/rs/zerolog"
)
func NewMidtransTransactionRepository(db *gorm.DB) *MidtransTransactionRepository {
return &MidtransTransactionRepository{
DB: db,
}
}
type Midtr... |
package strings
// Reverses a string
/*
Since strings in Go are immutable, we first convert the string to a mutable array of runes ([]rune),
perform the reverse operation on that, and then re-cast to a string.
*/
func Reverse(s string) string {
runes := []rune(s)
reversedRunes := reverseRunes(runes)
return stri... |
package main
import (
"log"
"os"
"github.com/mikesimons/kpatch/pkg/kpatch"
"github.com/spf13/cobra"
)
var versionString = "dev"
func main() {
var selector string
var merges []string
var exprs []string
var params []string
cmd := &cobra.Command{
Use: "kpatch",
Version: versionString,
Run: func(cm... |
package storage
import (
"errors"
"godistributed-rabbitmq/common/dto"
)
// Maps sensor name to it's database id.
var sensors map[string]int
// -----------------------------------------------------------------------------
// SaveReadout - Saves the readout from the given sensor.
// ---------------------------------... |
package main
import (
"context"
"github.com/cucumber/godog"
)
func InitializeTestSuite(sc *godog.TestSuiteContext) {
// Runs before entire test Suite
sc.BeforeSuite(func() {
bookings = []Spot{}
})
}
// Godog Scenarios
func InitializeScenario(sc *godog.ScenarioContext) {
// Runs before every scenario
sc.Bef... |
package main
import (
"testing"
)
func TestCalc(t *testing.T) {
m1 := 12
m2 := 14
m3 := 1969
m4 := 100756
f1 := 2
f2 := 2
f3 := 654
f4 := 33583
if calc(m1) != f1 {
t.Errorf("Calculated %d, got %d, expected %d", m1, calc(m1), f1)
}
if calc(m2) != f2 {
t.Errorf("Calculated %d, got %d, expected %d", m2... |
package pod
import (
"context"
"fmt"
"github.com/projecteru2/cli/cmd/utils"
"github.com/projecteru2/cli/describe"
corepb "github.com/projecteru2/core/rpc/gen"
"github.com/google/uuid"
"github.com/juju/errors"
"github.com/urfave/cli/v2"
)
type capacityPodOptions struct {
client corepb.CoreRPCClient
podn... |
/*
* Copyright (C) 2016 Red Hat, Inc.
*
* 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 Licens... |
package view
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
// padding data
func padData(src []byte, size int) []byte {
num := size - len(src)%size
pad := bytes.Repeat([]byte{byte(num)}, num)
return append(src, pad...)
}
// unpadding data
func unPadData(src []byte) []byte {
n := len(src)
unPadNum := int(src... |
package web
import (
"crypto/md5"
"fmt"
"html/template"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const (
MaxUploadSize int64 = 2 << 32;
UploadPath string = "./upload"
)
func RenderError(w http.ResponseWriter, message string, statusCode int) {
w.Write... |
package model
import (
"github.com/TRON-US/soter-order-service/common/errorm"
"github.com/go-xorm/xorm"
)
var (
queryFileByIdSql = `
SELECT
b.address,
a.file_name,
a.file_size,
unix_timestamp(a.expire_time),
IFNULL(c.file_hash,''),
a.deleted,
a.version
FROM
file a
LEFT JOIN
... |
package main
import (
"os"
"testing"
)
func TestNewDeck(t *testing.T) {
d := newDeck()
if len(d) != 40 {
t.Errorf("Expected length of 40 but got: %v", len(d))
}
if d[0] != "1 of Club" {
t.Errorf("Expected first as 1 of Club: %v", d[0])
}
if d[len(d)-1] != "10 of Spade" {
t.Errorf("Expected las as 10 o... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
// Date is exported
type Date struct {
day int
month int
year int
}
// OurDate return *date
func OurDate(day int, month int, year int) Date {
values := Date{
day,
month,
year,
}
return values
}
func inputDay() int {
scanner :... |
package constant
import (
"time"
)
const STATUS_WAITING_FOR_PRINTING = "STATUS_WAITING_FOR_PRINTING"
const STATUS_SUCCESSFUL_PRINTED = "STATUS_SUCCESSFUL_PRINTED"
const STATUS_WAITING_FOR_RETURN_PAGES = "STATUS_WAITING_FOR_RETURN_PAGES"
const STATUS_ERROR_WITH_PRINTING = "STATUS_ERROR_WITH_PRINTING"
const STATUS_WAI... |
package rpl
import (
"io/ioutil"
"os"
"testing"
"time"
)
func TestGoLevelDBStore(t *testing.T) {
// Create a test dir
dir, err := ioutil.TempDir("", "wal")
if err != nil {
t.Fatalf("err: %v ", err)
}
defer os.RemoveAll(dir)
// New level
l, err := NewGoLevelDBStore(dir, 0)
if err != nil {
t.Fatalf("er... |
// Copyright 2017 Sevki <s@sevki.org>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package label
import (
"testing"
)
// Test that all valid Labels get parsed into proper (package, target) pairs.
func TestTargetLabelParse(t *testing.T)... |
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
)
type StsClient struct {
SVC *sts.STS
}
func NewStsClient() StsClient {
sess := session.Must(session.NewSession())
creds := credent... |
package main
import (
"fmt"
)
func main() {
x := 100 // short declaration plus assigned value
fmt.Println(x)
y := 67 + 9 // short declaration plus assigned value
fmt.Println(y)
x = 200 // only assigned value
fmt.Println(x)
y = 99 + 78 // only assigned value
fmt.Println(y)
z := "Bond, James"
fmt.Println(z)
... |
// Package repositories contains actual implementations of the repository interfaces defined in the `core` package.
// It currently supports Google Cloud Storage (GCS) for Bazel releases, release candidates and Bazel binaries built at arbitrary commits.
// Moreover, it supports GitHub for Bazel forks.
package repositor... |
package boltrepo
import (
"github.com/boltdb/bolt"
"github.com/scjalliance/drivestream"
"github.com/scjalliance/drivestream/binpath"
"github.com/scjalliance/drivestream/resource"
)
var _ drivestream.DriveMap = (*Drives)(nil)
// Drives accesses a map of drives in a bolt repository.
type Drives struct {
db *bolt.... |
package soapboxd
import (
"database/sql"
"net/http"
pb "github.com/adhocteam/soapbox/proto"
)
// Server is the basic soapbox server containing all the initialized items needed to perform its functions
type Server struct {
db *sql.DB
httpClient *http.Client
configurationStore Configurati... |
package _33_Search_in_Rotated_Sorted_Array
func search(nums []int, target int) int {
if len(nums) == 0 {
return -1
}
if len(nums) == 1 && nums[0] == target {
return 0
}
var (
left = 0
right = len(nums) - 1
mid = 0
)
for left <= right {
mid = (left + right) / 2
// 如果碰上了就碰上了
if nums[left] == ta... |
package aliyun
import (
"github.com/gogap/config"
"github.com/gogap/context"
"github.com/gogap/flow"
)
func init() {
flow.RegisterHandler("devops.aliyun.oss.bucket.create", CreateOSSBucket)
flow.RegisterHandler("devops.aliyun.oss.bucket.delete", DeleteOSSBucket)
}
func CreateOSSBucket(ctx context.Context, conf ... |
package caaa
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00100102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.001.001.02 Document"`
Message *AcceptorAuthorisationRequestV02 `xml:"AccptrAuthstnReq"`
}
func (d *Docu... |
package model
// Role is a user role.
type Role struct {
Name string
}
|
package activity
var DefaultActivityManager *ActivityManager
func init() {
DefaultActivityManager = newActivityManager()
}
func newActivityManager() *ActivityManager {
return &ActivityManager{
activitys: make(map[int32]*Activity),
}
}
|
package memory
import (
"errors"
"fmt"
)
const (
MinAllocMemSize = 32
FixedStackIdx = 16 * 1024
MaxDataMemSize = 16 * 1024
DefaultMinHeapMemSize = 64 * 1024
DefaultMaxHeapMemSize = 1024 * 1024
)
var (
ErrMemoryNotEnough = errors.New("memory not enough")
ErrMemoryOutBound = errors... |
//Not well-typed statements after a return
package main;
func main () {
}
func pain () bool{
return true;
x := true || "false"
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package vlabs
import (
"encoding/json"
"strings"
"github.com/Azure/aks-engine/pkg/api/common"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"github.com/pkg/errors"
)
// Re... |
package externalplugins
import (
"errors"
"fmt"
"net/url"
"regexp"
"strings"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/test-infra/prow/labels"
)
const (
// defaultGracePeriodDuration define the time for blunderbuss plugin to wait
// before requesting a review (default five se... |
package service
import (
"mobingi/ocean/pkg/tools/machine"
"path/filepath"
"mobingi/ocean/pkg/constants"
cmdutil "mobingi/ocean/pkg/util/cmd"
)
const schedulerServiceTemplate = `[Unit]
Description=Kubernetes Scheduler
Documentation=https://github.com/GoogleCloudPlatform/kubernetes
After=network.target
After=kube... |
package migrate
const (
// TagDB is the tag used for the model structfields that defines 'pq' options.
TagDB string = "db"
// TagDatabaseName is the tag key that defines database column name.
TagDatabaseName string = "name"
// TagColumnIndex is the tag key that defines database column name.
TagColumnIndex string... |
package main
import (
"database/sql"
"fmt"
"log"
"io/ioutil"
_ "github.com/mattn/go-sqlite3"
)
func main() {
// инициализируем базу данных
db, err := sql.Open("sqlite3", "./tasks.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
sqlStmt, err := ioutil.ReadFile("scheme.sql")
if err == nil {
_, ... |
// Copyright 2022 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 errors
import (
"errors"
)
var (
As = errors.As
Is = errors.Is
Unwrap = errors.Unwrap
New = errors.New
)
var (
// Base Errors
ErrBadRequest = AddCodeWithMessage(nil, "bad_request", "bad request")
ErrUnauthorized = AddCodeWithMessage(nil, "unauthorized", "unauthorized")
// Service
Er... |
/**
* @Time : 2020/9/16 4:48 PM
* @Author : solacowa@gmail.com
* @File : service_main
* @Software: GoLand
*/
package foo
|
package models
type Log struct {
Method string
URL string
}
func (l *Log) SetMethod(method string) {
l.Method = method
}
func (l *Log) GetMethod() string {
return l.Method
}
func (l *Log) SetURL(method string) {
l.URL = method
}
func (l *Log) GetURL() string {
return l.URL
}
|
package netio
import (
"fmt"
"sync"
"github.com/colefan/gsgo/netio/packet"
)
type BaseClient struct {
*Client
DefaultPackDispatcher
bInited bool
socketStatus int
clientName string
serverListenAddress string
serverListenPort uint16
mu sync.Mutex
}
func (this... |
package leetcode
func numberOfLines(widths []int, S string) []int {
if len(S) == 0 {
return []int{0, 0}
}
lines := 0
accu := 0
for _, c := range S {
if accu+widths[c-'a'] > 100 {
lines++
accu = 0
}
accu += widths[c-'a']
}
return []int{lines + 1, accu}
}
|
package main
import (
"flag"
"log"
"net/http"
"github.com/hugobcar/k8s-metadata/router"
DB "github.com/hugobcar/k8s-metadata/models"
)
var portListen string
var userDB string
var passDB string
var database string
var hostDB string
var portDB string
func init() {
flag.StringVar(&portListen, "port", "6885", "P... |
package action
import (
"html/template"
)
type JumpSelectBoxAction struct {
BaseAction
Options JumpOptions
NewTabTitle string
}
type JumpOptions []JumpOption
type JumpOption struct {
Value string
Url string
}
func SelectBoxJump(options JumpOptions) *JumpSelectBoxAction {
return &JumpSelectBoxAction{Op... |
// Copyright © 2020 Attestant Limited.
// 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 root
import (
"github.com/alecthomas/kingpin"
"github.com/apex/log"
ooni "github.com/ooni/probe-cli"
"github.com/ooni/probe-cli/internal/log/handlers/batch"
"github.com/ooni/probe-cli/internal/log/handlers/cli"
"github.com/ooni/probe-cli/utils"
"github.com/ooni/probe-cli/version"
)
// Cmd is the root c... |
package reconciler
import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/image"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/poi... |
package models
type WSMessage struct {
Code int `json:"code"` // Code, for errors
Type WSType `json:"type"` // Type of message
AppID string `json:"app_id"` // AppID of "owner" app
Token string `json:"token"` // Unique token
Error string `json:"error"` // Error message
Message string `js... |
/**
* Copyright (C) 2019, Xiongfa Li.
* All right reserved.
* @author xiongfa.li
* @date 2019/2/21
* @time 15:31
* @version V1.0
* Description:
*/
package test
import (
"container/list"
"fmt"
"github.com/xfali/gomem/recyclePool"
"math/rand"
"runtime"
"testing"
"time"
)
func TestP... |
package fbmessenger
import (
"encoding/json"
"strings"
)
/*------------------------------------------------------
Send API
------------------------------------------------------*/
// TextMessage is a fluent helper method for creating a SendRequest containing a text message.
func TextMessage(text string) *SendReque... |
package helper
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/denisbrodbeck/machineid"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"time"
)
type LicenseInfo struct {
Email string `json:"email"`
CpuId string `js... |
package server
import (
"net/http"
"github.com/empirefox/esecend/front"
"github.com/gin-gonic/gin"
)
func (s *Server) GetHeadUptoken(c *gin.Context) {
c.JSON(http.StatusOK, &front.HeadUptokenResponse{
HeadToken: s.Cdn.HeadUptoken(s.TokenUser(c).ID),
})
}
|
package consumers
import (
"fmt"
"log"
"github.com/pedromss/kafli/config"
c "github.com/pedromss/kafli/config"
cst "github.com/pedromss/kafli/config/constants"
"github.com/pedromss/kafli/confluent"
"github.com/pedromss/kafli/contracts"
"github.com/pedromss/kafli/model"
"github.com/pedromss/kafli/ops/offset"
... |
package tmpl2
func findMin(nums []int) int {
if len(nums) == 0 {
return -1
}
if len(nums) == 1 {
return nums[0]
}
l, r := 0, len(nums)-1
for l < r {
m := l + (r-l)>>1
if m == 0 {
if nums[m+1] > nums[m] {
return nums[m]
}
}
if m == len(nums)-1 {
if nums[m] < nums[m-1] {
return nums[m... |
package main
import "fmt"
func multiple(first string, last string) (string, string) {
return first, last
}
func main() {
f, l := multiple("luispa", "garcia")
fmt.Println(f, l)
f2, _ := multiple("luispa", "garcia")
fmt.Println(f2)
}
|
package models
import (
"github.com/astaxie/beego/orm"
"github.com/gosimple/slug"
)
type Manga struct {
Id int
Name string `orm:"unique"`
Content string
Image string
NewsImage string
DownloadUrl string
Status *Status `orm:"rel(fk)"`
Slug string
}
func (m *Manga) auto... |
/*
Implementação de uma pilha estática de inteiros
1. Definição do tamanho da pilha, pois trata-se de uma pilha
estática, ou seja, a alocação de memória para a pilha será feita
em tempo de compilação;
2. Definição da estrutura de pilha;
3. Declaração de uma variável do tipo da pilha;
4. Função isEmpty() que veri... |
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
)
var (
root = flag.String("root", "", "")
match = flag.String("match", "", "")
dirs = flag.Bool("dirs", false, "")
)
func testErr(root string) {
fmt.Println("testErr: always return error")
f := func(path string, info os.... |
package api
import (
"bytes"
"encoding/json"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/netrack/openflow"
"github.com/netrack/openflow/ofp"
log "github.com/sirupsen/logrus"
"io"
"net"
"net/http/httptest"
"testing"
"time"
)
type DeviceList struct {
Devices []string `json:... |
package main
import (
"fmt"
"time"
"github.com/satori/go.uuid"
)
func NewTrainFromHistory(events []interface{}) *Train {
train := &Train{}
for i := range events {
train.apply(events[i])
}
return train
}
func AnnounceNewTrain(From string, FromTime time.Time, To string, ToTime time.Time) *Train {
t := &Trai... |
package main
import (
"fmt"
"math/big"
"github.com/jackytck/projecteuler/tools"
)
func solve(limit int) int {
var maxD int
// largest value of x among all minimal solutions
maxX := big.NewInt(0)
for d := 2; d <= limit; d++ {
if tools.IsSquareNumber(d) {
continue
}
// minimal solution of x and y
min... |
// File implementation of profile repository.
//
// @author TSS
package file
import (
"encoding/json"
"io/ioutil"
"log"
"path/filepath"
"github.com/mashmb/1pass/1pass-core/core/domain"
)
type fileProfileRepo struct {
profileJson map[string]interface{}
}
func NewFileProfileRepo() *fileProfileRepo {
return &f... |
package certGenerator
/*
This modified code of generate_cert.go
available on https://golang.org/src/crypto/tls/generate_cert.go.
File generate_cert.go was written by Go Authors
*/
import (
"github.com/krix38/gophotogallery/properties"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"... |
package main
import "sync"
type application struct {
CfgProvider ConfigProvider
}
var App *application
var appOnce sync.Once
type AppOption func(app *application) error
func InitApplication(opts ...AppOption) error {
var err error
appOnce.Do(func() {
App = &application{
CfgProvider: NewInMemoryConfigProvid... |
package main
import (
"fmt"
"github.com/ant0ine/go-urlrouter"
"log"
"net/http"
)
func Hello(w http.ResponseWriter, req *http.Request, params map[string]string) {
fmt.Fprintf(w, "Hello %s", params["name"])
}
func Bonjour(w http.ResponseWriter, req *http.Request, params map[string]string) {
fmt.Fprintf(w, "Bonjo... |
package muxcodec
import (
"bytes"
"fmt"
"io"
mc "gx/ipfs/QmYMiyZRYDmhMr2phMc4FGrYbsyzvR751BgeobnWroiq2z/go-multicodec"
)
var (
ErrNoCodec = fmt.Errorf("no suitable codec")
)
var Header []byte
func init() {
Header = mc.Header([]byte("/multicodec"))
}
// SelectCodec is a function that selects which codecs are... |
package cache
import (
"time"
"github.com/dgraph-io/ristretto"
)
type Local struct {
Cache *ristretto.Cache
MaxItems int64
MaxSize int64
MaxTTL time.Duration
}
func NewLocal(maxItems, maxSize int64, maxTTL time.Duration) *Local {
c, err := ristretto.NewCache(&ristretto.Config{
NumCounters: maxItems *... |
package local
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
// Dependencies holds the data related to a local Realm app's dependencies
type Dependencies struct {
RootDir string
FilePath string
isDirectory bool
}
// FindNodeModules finds the Realm app dependencies as a node_modu... |
// Copyright 2019 The Meshery 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... |
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package task
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"os"
"sort"
"sync"
"time"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
brpb "github.com/pingcap/kvproto/pkg/brpb"
"github.com/pingcap/kvproto... |
package test
import (
"fmt"
"reflect"
"runtime"
"testing"
)
var (
// Alias
BeTrue = AssertTrue
BeNil = AssertNil
BeEqual = AssertEqual
)
func AssertTrue(t *testing.T, resultValue interface{}) {
AssertEqual(t, resultValue, true)
}
func AssertNil(t *testing.T, resultValue interface{}) {
AssertEqual(t, re... |
package serverweb
import (
"encoding/json"
"fmt"
"formation/api"
"io"
"net/http"
)
func Delete(w http.ResponseWriter, req *http.Request) {
id := req.URL.Query()["id"]
if len(id) > 0 {
fmt.Println("delete", len(api.List()))
//s := strconv.Itoa(id)
api.DeleteTodo(id[0])
//io.WriteString(w, "Afficher ma ... |
package main
import (
"coludRenderDiscovery/models"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"os"
)
func init() {
os.MkdirAll(beego.AppConfig.String("upfile::SaveDir"), 0755)
connStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&loc=%s",
beego.App... |
/*
Challenge
Given two non negative integers a < b, output all countries, from the below Top 100 Countries, where area is between a and b: a<= area <= b.
Example
147500,180000 --> uruguay, suriname, tunisia, bangladesh
1200000,1300000 --> peru, chad, niger, angola, mali, south africa
1234567,1256789 --> angola, ma... |
package polyanalyst6api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"github.com/gluk-skywalker/polyanalyst6api-go/parameters/project"
"github.com/gluk-skywalker/polyanalyst6api-go/responses"
"github.com/gluk-skywalker/polyanalyst6api-go/objects"
"github.com/gluk-sky... |
package logging_test
import (
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
"time"
"github.com/Syncbak-Git/logging"
)
func Example() {
l := logging.New("")
val, _ := logging.NewKV("key 1", "value 1", "key2", "value2")
l.Info(val, "Hello World %s\t{%d}", "An\targument", 1234)
// Expected output (adjust timest... |
package main
import (
"bytes"
"encoding/json"
"go/format"
"io/ioutil"
"log"
"strings"
"text/template"
"github.com/captncraig/wildchef/constants"
)
func must(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
dat, err := ioutil.ReadFile("items.json")
must(err)
nameLoo... |
package main
import (
"context"
"fmt"
"os"
"os/signal"
"runtime"
"github.com/pkg/errors"
"github.com/xackery/log"
"github.com/xackery/talkeq/client"
)
// Version is the build version
var Version string
func main() {
log := log.New()
if Version == "" {
Version = "1.x.x EXPERIMENTAL"
}
log.Info().Msgf("... |
package leetcode
import "testing"
func Test_longestPalindrome(t *testing.T) {
//t.Log(reverseString("abcdasdfghjkldcba"))
t.Log(longestPalindrome("babad"))
t.Log(longestPalindrome("abcacbadf"))
t.Log(longestPalindrome("cbbca"))
t.Log(longestPalindrome("cbbd"))
}
func Test_Manacher(t *testing.T) {
str := "abcac... |
package gui
import (
"context"
"time"
"github.com/jesseduffield/lazydocker/pkg/tasks"
)
func (gui *Gui) QueueTask(f func(ctx context.Context)) error {
return gui.taskManager.NewTask(f)
}
type RenderStringTaskOpts struct {
Autoscroll bool
Wrap bool
GetStrContent func() string
}
type TaskOpts stru... |
/*
Tencent is pleased to support the open source community by making Basic Service Configuration Platform available.
Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain... |
package main
import f "fmt"
type Manusia struct{
name string
age int
phone string
}
type Pelajar struct{
Manusia
sekolah string
loan float32
}
type Karyawan struct{
Manusia
company string
uang float32
}
func (m Manusia) SayHay(){
f.Printf("Hy nama saya %s telpon saya di nomer ini %s\n", m.name, m... |
package store
import (
"encoding/json"
"errors"
"net/http"
"sort"
"time"
"github.com/manishrjain/gocrud/x"
)
var (
ErrNoParent = errors.New("No parent found")
)
// Query stores the read instrutions, storing the instruction set
// for the entities Query relates to.
type Query struct {
kind string
id ... |
package command
import (
"context"
"fmt"
"math"
"math/rand"
"sync"
"time"
"github.com/mum4k/termdash"
"github.com/mum4k/termdash/cell"
"github.com/mum4k/termdash/container"
"github.com/mum4k/termdash/container/grid"
"github.com/mum4k/termdash/keyboard"
"github.com/mum4k/termdash/linestyle"
"github.com/mum... |
package controllers
import (
"github.com/astaxie/beego"
"scholarship/models"
"scholarship/middlewares"
)
type AccountBalanceController struct {
beego.Controller
}
// @Title Get
// @Description test search for the relate account
// @Param address query string true "address of the user"
// @Success 200 {object} ... |
package market
import (
"github.com/gookit/gcli/v3"
"github.com/ovrclk/akcmd/cmd/akash/x/market/bid"
"github.com/ovrclk/akcmd/cmd/akash/x/market/lease"
"github.com/ovrclk/akcmd/cmd/akash/x/market/order"
)
func QueryCmd() *gcli.Command {
cmd := &gcli.Command{
Name: "market",
Desc: "Market query commands",
F... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.