text
stringlengths
11
4.05M
package database type TbGwInfo struct { ID uint IPAddr string MacAddr string SocketPort uint GatewayID uint FreqID uint CenterFreq uint Addr string `gorm:"column:Addr"` FanAmount uint } func (TbGwInfo) TableName() string { return "tb_gw_info" }
package types // DONTCOVER import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" gogotypes "github.com/gogo/protobuf/types" "github.com/irisnet/irismod/modules/nft/exported" ) va...
package 动态规划 // ------------------------------ 暴力搜索 ------------------------------ // 执行用时:1072 ms, 在所有 Go 提交中击败了 8.09% 的用户 // 内存消耗:2.1 MB, 在所有 Go 提交中击败了 100.00% 的用户 func isInterleave(s1 string, s2 string, s3 string) bool { if len(s3) != len(s1)+len(s2) { return false } if len(s3) == 0 { return true } if l...
//source: https://doc.qt.io/qt-5/qtcharts-audio-example.html package main import ( "os" "github.com/therecipe/qt/widgets" ) func main() { var app = widgets.NewQApplication(len(os.Args), os.Args) var w = NewWidget(nil, 0) w.Show() app.Exec() }
/* You are given a dictionary of names and the amount of points they have. Return a dictionary with the same names, but instead of points, return what prize they get. "Gold", "Silver", or "Bronze" to the 1st, 2nd and 3rd place respectively. For all the other names, return "Participation" for the prize. Examples awar...
package v3 type Album struct { Id string `json:"id"` Title string `json:"title"` Description string `json:"description"` Datetime int64 `json:"datetime"` Cover string `json:"cover"` CoverWidth int64 `json:"cover_width"` CoverHeight int64 `json:"cover_height"` AccountUrl stri...
package main import ( "log" "net" ) func main() { var conns []net.Conn for i := 0; i < 200; i++ { c, err := net.Dial("tcp", "127.0.0.1:2020") if err != nil { log.Fatalf("dial error: %v", err) } conn...
package journey import ( "../train" "time" ) type Journey struct { name string route Route date time.Time train train.Train places map[string][][]int }
package model import "time" type PlayerInfo struct { Id int `json:"id"` Name string `json:"name"` Team string `json:"team"` Nationality string `json:"nationality"` Height string `json:"height"` Born string `json:"born"` Shirt_number string `json:"shirt_number"` } ty...
/* Copyright © 2020 Denis Rendler <connect@rendler.me> 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...
package tarot type Table struct { Scores [2]float32 `json:"scores"` Cards [NB_PLAYERS]Card `json:"cards"` PlayerTurn int `json:"playerTurn"` FirstPlayer int `json:"firstPlayer"` TrickNb int `json:"trickNb"` IsTaker ...
package main import "fmt" // 392. 判断子序列 // 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 // 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 // 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 // 后续挑战 : // 如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你...
package endpoints import ( "context" "fmt" "net/http" "time" "github.com/google/uuid" "github.com/gorilla/mux" "github.com/go-kit/kit/endpoint" kithttp "github.com/go-kit/kit/transport/http" "github.com/sumelms/microservice-course/internal/course/domain" ) type findSubscriptionRequest struct { UUID uuid...
package main import ( "fmt" authnpb "istio.io/api/authentication/v1alpha1" betapb "istio.io/api/security/v1beta1" commonpb "istio.io/api/type/v1beta1" corev1 "k8s.io/api/core/v1" ) type mTLSMode int // Unset, Strict and Permissive for the mTLS mode. const ( Unset mTLSMode = 0 Strict mTLSMode = 1 Pe...
// Copyright 2022 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...
/* nighthawk.nhstruct.registry.go * author: roshan maskey <roshanmaskey@gmail.com> * * Datastructure for Registry Entry */ package nhstruct type RegistryItem struct { JobCreated string `xml:"created,attr"` TlnTime string `json:"TlnTime"` KeyPath string Type string...
package cli import ( "errors" "fmt" "github.com/10gen/realm-cli/internal/cloud/atlas" "github.com/10gen/realm-cli/internal/cloud/realm" "github.com/10gen/realm-cli/internal/local" "github.com/10gen/realm-cli/internal/terminal" "github.com/AlecAivazis/survey/v2" ) // ProjectInputs are the project/app inputs f...
package sqlite import ( "database/sql" "encoding/json" "time" "github.com/Tanibox/tania-core/src/growth/decoder" "github.com/Tanibox/tania-core/src/growth/repository" "github.com/Tanibox/tania-core/src/helper/structhelper" "github.com/gofrs/uuid" ) type CropEventRepositorySqlite struct { DB *sql.DB } func N...
package triangle import ( "testing" "triangle" ) func TestValidTriangle(t *testing.T) { sides := [3]uint16{3, 3, 3} if !triangle.IsValid(sides) { t.Fail() } } func TestInvalidTriangle(t *testing.T) { sides := [3]uint16{5, 10, 25} if triangle.IsValid(sides) { t.Fail() } }
package dao import ( "log" . "github.com/gonzaloescobar/prescription/models" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type PrescriptionsDAO struct { Server string Database string } var db *mgo.Database const ( COLLECTION = "prescriptions" ) // Establish a connection to database func (m *Prescriptio...
package main import ( "fmt" ) //闭包是什么? //闭包是一个函数,这个函数包含了他外部作用域的一个变量 //底层的原理: //1.函数可以作为返回值 //2.函数内部查找变量的顺序,现在自己内部找,找不到往外层找 // func adder(x int) func(int) int { // return func(y int) int { // x += y // return x // } // } // func main() { // ret := adder(100) // ret2 := ret(200) // fmt.Println(ret2) // } //...
package integration_test import ( "github.com/APTrust/exchange/constants" "github.com/APTrust/exchange/context" "github.com/APTrust/exchange/models" "github.com/APTrust/exchange/network" "github.com/APTrust/exchange/util" "github.com/APTrust/exchange/util/testutil" "github.com/stretchr/testify/assert" "github....
package user import ( "github.com/globalsign/mgo/bson" ) func (userModel *UserModel) SubUser(uid, subUid bson.ObjectId) (err error) { c := userModel.GetC() defer c.Database.Session.Close() err = userModel.addAttention(uid, subUid) if err != nil { return } return userModel.addFans(subUid, uid) }
package worker import ( "testing" ) func Test_SmtpPing_1(t *testing.T) { array := [3]string{ "126mx01.mxmail.netease.com:25", "mx1.qq.com:25", "163mx01.mxmail.netease.com:25", } for _, v := range array { result := SmtpPing(&v, true) if result.Error != "" { t.Error(result.Error) continue } if ...
package filter import ( "context" "encoding/json" "fmt" "github.com/coreos/etcd/mvcc/mvccpb" "go.etcd.io/etcd/clientv3" "gocherry-api-gateway/components/common_enum" "gocherry-api-gateway/components/etcd_client" "gocherry-api-gateway/components/http_client" "gocherry-api-gateway/proxy/enum" "gocherry-api-gat...
package deck import ( "fmt" "testing" ) func ExampleCard() { fmt.Println(Card{Spade, King}) fmt.Println(Card{Heart, Ace}) fmt.Println(BigJoker) fmt.Println(LittleJoker) fmt.Println(Card{Club, Ten}) fmt.Println(Card{Diamond, Six}) // Output: // ♠K // ♥A // BigJoker // LittleJoker // ♣10 // ♦6 } func T...
// Naked return package main import ( "fmt" ) func all(sum ...int) (value int) { for _, v := range sum { value += v } return } func main() { a := all(1, 2, 3, 4, 5) fmt.Println(a) }
package gui import ( "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/steelx/go-rpg-cgm/utilz" ) type ProgressBar struct { x, y float64 Background *pixel.Sprite Foreground *pixel.Sprite foregroundFrames ...
package main import ( "bytes" "encoding/binary" "fmt" "io" "math" "time" "github.com/howeyc/crc16" ) type SYNC_TYPE int const ( SYNC_TYPE_DATA SYNC_TYPE = 0 SYNC_TYPE_HEADER SYNC_TYPE = 1 SYNC_TYPE_CFG1 SYNC_TYPE = 2 SYNC_TYPE_CFG2 SYNC_TYPE = 3 SYNC_TYPE_CFG3 SYNC_TYPE = 5 SYNC_TYPE_CMD SYN...
package photo import ( "net/http" ) type photoHandler struct { } func NewPhotoHandler() *photoHandler { m := new(photoHandler) return m } func (m *photoHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { http.Redirect(responseWriter, request, "/photo/portfolio", http.StatusMovedPerma...
package command import ( "context" "flag" "github.com/bongnv/gokit/internal/parser" "github.com/bongnv/gokit/internal/iohelper" "github.com/google/subcommands" ) // Execute ... func Execute(ctx context.Context) int { subcommands.Register(subcommands.HelpCommand(), "") subcommands.Register(subcommands.FlagsCom...
//go:build wasm && js && webclient package main import ( "fmt" "strconv" "syscall/js" "time" "github.com/ekotlikoff/gochess/internal/model" ) func (clientModel *ClientModel) initStyle() { document := clientModel.document styleEl := document.Call("createElement", "style") document.Get("head").Call("appendChi...
package oob import ( "context" "errors" "github.com/hashicorp/go-multierror" ) // BMC management methods. type BMC interface { // NetworkSource() (result string, err repository.Error) CreateUser(context.Context) error UpdateUser(context.Context) error DeleteUser(context.Context) error } // CreateUser interfa...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
package main import ( "container/heap" "fmt" ) // https://leetcode-cn.com/problems/sliding-window-maximum/ //------------------------------------------------------------------------------ func maxSlidingWindow(nums []int, k int) []int { return maxSlidingWindow0(nums, k) } //-------------------------------------...
package main import ( "net/http" "strconv" "strings" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/version" "github.com/sirupsen/logrus" ) const exporterName = "netns_exporter" func init() { //nolint:gochecknoi...
package repositories import ( "blog/app/models" "errors" "github.com/jinzhu/gorm" "github.com/mlogclub/simple" "time" ) type TagRepository struct { db *gorm.DB } func NewTagRepository(db *gorm.DB) *TagRepository { return &TagRepository{ db: db} } // 获取标签列表 func (this *TagRepository) TagList(paging *simple....
package gotten import ( "errors" "fmt" "net/http" "reflect" "strings" ) const ( BaseUrlCannotBeEmpty = "baseUrl cannot be empty" MustPassPtrToImpl = "must pass the ptr of the service to be implemented" ServiceMustBeStruct = "service must be struct" UnrecognizedHTTPMethod ...
package openid import ( "net/http" "github.com/dgrijalva/jwt-go" ) // The Configuration contains the entities needed to perform ID token validation. // This type should be instantiated at the application startup time. type Configuration struct { tokenValidator jwtTokenValidator idTokenGetter GetIDTokenFunc err...
// // Copyright (C) 2019-2021 vdaas.org vald team <vald@vdaas.org> // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless requir...
package main import( "fmt" "os" "bufio" "strings" "strconv" ) //check if the char is a num between 0 to 9 func IsNum(c uint8) bool { return c >= '0' && c <= '9' } //define the precedence of the operator func PreOfOperator(op string) int { switch op { case "+", "-": return 1 case "*", "/": re...
package main import ( "bufio" "bytes" "fmt" "io" ) type parser struct { br *bufio.Reader tok, last byte n int err, lasterr error indent int } func (p *parser) next() byte { p.last = p.tok p.lasterr = p.err p.tok, p.err = p.br.ReadByte() p.printTrace(fmt.Sprintf("next: %x", ...
package server import ( "net/http" "github.com/julienschmidt/httprouter" "github.com/syariatifaris/shopeetax/app/resource/uires" "github.com/syariatifaris/shopeetax/app/usecase" ) //httpHandlerFunc abstraction of http handler type httpHandlerFunc func(ui *uires.UIResource, request *http.Request, useCase usecase....
// Copyright 2017 The Fuchsia 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 wlan import ( "fmt" mlme "garnet/public/lib/wlan/fidl/wlan_mlme" "sort" "strings" ) type AP struct { BSSID [6]uint8 SSID string BSS...
package pkg import ( "testing" "github.com/stretchr/testify/assert" "github.com/OpenDiablo2/dc6/pkg/frames" ) func TestDC6New(t *testing.T) { if dc6 := New(); dc6 == nil { t.Error("d2dc6.New() method returned nil") } } func getExampleDC6() *DC6 { exampleDC6 := &DC6{ Flags: 1, Encoding: 0, Te...
package main import ( "context" "log" "github.com/go-redis/redis/v8" ) var client *redis.Client func NewRedisClient() { log.Printf("Connecting to Redis..") client = redis.NewClient(&redis.Options{ Addr: "redis:6379", Password: "", // no password set DB: 0, // use default DB }) pong, err := ...
// 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 acco...
package main import ( "github.com/stretchr/testify/assert" "os" "testing" ) const localURL = "localhost" const redisURL = "REDIS_URL" func TestGetEmptyEnvFile(t *testing.T) { err := os.Setenv("GO_ENV", "") if err != nil { assert.Fail(t, err.Error(), "Failed setting env") } GetEnvFile() expectedURL := os.Ge...
package repository import ( "context" "fmt" "github.com/jackc/pgx/v4/pgxpool" "github.com/teploff/otus/scheduler/internal/domain/entity" "strconv" "strings" ) // eventRepository implements EventRepository interface type eventRepository struct { pgxPool *pgxpool.Pool } // NewEventRepository gets Event reposito...
package 单调栈 // -------------------------- 无单调栈,朴素解法 -------------------------- // 时间复杂度: O(n^2 * m^2) func numSubmat(mat [][]int) int { maxRectangleHeight := getMaxRectangleHeight(mat) return getCountOfRectangle(maxRectangleHeight) } func getMaxRectangleHeight(mat [][]int) [][]int { rows, cols := getRowsAndCols(ma...
package cloud type Cloud interface { Name() string Init(string, string, string, string) TestConnect() error GetInstances() []*Instance StartInstance(string) error StopInstance(string) error RestartInstance(string) error }
package scraper_test import ( "context" "testing" "time" discoveryv1 "github.com/syncromatics/kafmesh/internal/protos/kafmesh/discovery/v1" scraper "github.com/syncromatics/kafmesh/internal/scraper" gomock "github.com/golang/mock/gomock" "gotest.tools/assert" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachin...
// 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 flow import ( "testing" "time" ) func TestRegistry(t *testing.T) { r := new(MeterRegistry) m1 := r.Get("first") m2 := r.Get("second") m1.Mark(10) m2.Mark(30) time.Sleep(2 * time.Second) if total := r.Get("first").Snapshot().Total; total != 10 { t.Errorf("expected first total to be 10, got %d", to...
package cm15 import ( "encoding/json" "time" ) // RubyTime is a wrapper around time.Time that adds the ability to unmarshal ruby JSON date time // values. type RubyTime struct { time.Time } // MarshalJSON implements the marshaller interface. func (r *RubyTime) MarshalJSON() ([]byte, error) { return json.Marshal(...
package semver import ( "testing" ) func TestMajor(t *testing.T) { tests := []struct { name string sample string want int }{ { name: "sample-1", sample: "v12.3.1", want: 12, }, { name: "sample-2", sample: "v0.0.1", want: 0, }, { name: "sample-3", sample: "v.1.2...
package main import ( "database/sql" "fmt" "log" "net/http" "os" "github.com/shitakemura/myapi/api" _ "github.com/go-sql-driver/mysql" ) var ( dbUser = os.Getenv("DB_USER") dbPassword = os.Getenv("DB_PASSWORD") dbDatabase = os.Getenv("DB_NAME") dbConn = fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?p...
package fulladdress import ( "fmt" "net" "regexp" "strconv" ) var ( regIPv4 *regexp.Regexp regIPv6 *regexp.Regexp ) func init() { regIPv4, _ = regexp.Compile(`^((?:[0-9]{1,3}\.){3}[0-9]{1,3}):([0-9]{1,5})$`) regIPv6, _ = regexp.Compile(`^\[((?:(?:[a-fA-F0-9]{1,4})?:){2,7}(?:[a-fA-F0-9]{1,4}))\]:([0-9]{1,5})$...
package encoding import ( "context" "encoding/json" "net/http" libError "github.com/angryronald/guestlist/lib/error" ) func EncodeError(ctx context.Context, err error, w http.ResponseWriter) { w.Header().Set("Content-Type", "application/json; charset=utf-8") code := http.StatusInternalServerError message := ...
package api import ( "fmt" "golang-distributed-parallel-image-processing/api/download" "golang-distributed-parallel-image-processing/api/login" "golang-distributed-parallel-image-processing/api/logout" "golang-distributed-parallel-image-processing/api/status" "golang-distributed-parallel-image-processing/api/upl...
// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://github.com/gogf/gf. // Package gtest provides simple and useful test utils. ...
package requests type CreateSprint struct { Name string `validate:"required,min=2,max=36"` Description string } type UpdateSprint struct { Name string `validate:"required,min=2,max=36"` Description string } func (c *CreateSprint) Valid() error { return validate.Struct(c) } func (c *UpdateS...
package main import ( "fmt" "sort" ) func main() { test1 := []int{1, 2} test2 := []int{3, 4, 5} //var test3 []int for _, x := range test2 { test1 = append(test1, x) } sort.Ints(test1) if len(test1)%2 == 1 { med := len(test1) / 2 fmt.Println(test1[med]) fmt.Println("test1") return } index := ...
package dht import ( "fmt" "math/big" eHex "encoding/hex" "time" ) /* Heartbeat: allows us to say if our predecessor is alive or not, so that we know if we have to make data original or not Include the predecessor of the predecessor in the heartbeat (Heartbeat could also be used by our successor so th...
package main import ( "bufio" "fmt" "net" "os" "strings" ) func main() { conn, err := net.Dial("tcp", "localhost:8888") if err != nil { fmt.Println("client dial err=", err) return } // 功能1 客户端可以发送单行数据, 然后退出 reader := bufio.NewReader(os.Stdin) // os.Stdin 代表标准输入 [终端] for { // 从终端读取一行用户输入,并准备发送给服务器 ...
/* * Copyright 2020-present Open Networking Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law ...
package main import ( "fmt" ) func exec1() { a := 99 fmt.Printf("%v -- %T\n", a, a) } func exec2() { str1 := "yang yuei xiong" arr1 := []string{"java", "python", "golang"} for _, i := range str1 { fmt.Printf("%c %v %T\n", i, i, i) } for _, i := range arr1 { fmt.Printf("%v %T\n", i, i) } } func exec3()...
package main import ( "github.com/gin-gonic/gin" "github.com/tomasen/ginkin" "gopkg.in/alecthomas/kingpin.v2" "log" "net/http" ) func main() { apis := map[string]ginkin.APIHandler{ "version": {"GET", DescribeVersion, "print version info"}, "user/list": {"POST", UserList, "list users"}, "user/:...
package http import ( "fmt" "reflect" "strconv" ) // PluginRouter 插件路由 type PluginRouter struct { handlers []HandleFunc private bool group bool discuss bool } // Plugin is the plugin of hanabi type Plugin interface { Parse(ctx *CQContext) } // HandleFunc 处理函数 type HandleFunc func(*CQContext) func (ser...
package main import ( f "fmt" "net" ) func main() { f.Println("server running 8888 port") ln, err := net.Listen("tcp", ":8888") if err != nil { f.Println(err) return } defer ln.Close() for { conn, err := ln.Accept() if err != nil { f.Println(err) continue } defer conn.Close() go reques...
package main import ( "fmt" ) // Sqrt uses Newton's method to calculate the square root func Sqrt(x float64) float64 { var z float64 = 1 for i := 0; i < 10; i++ { if y := z - (z*z-x)/(2*z); y == z { return y } else { z = y fmt.Println("z =", z) } } return z } func main() { fmt.Println(Sqrt(9)) }...
package usermanager import ( "config" "dbmanager" "encoding/json" "httprouter" "io" "lebangproto" "logger" "net/http" "processor/common" "gopkg.in/mgo.v2/bson" ) func UpdateErrandsCommonMerchant(phone string, merchant string) { if merchant == "就近购买" || merchant == "" { return } var merchantdata leban...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //371. Sum of Two Integers //Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. //Example: //Given a = 1 a...
package supervisor import ( "fmt" "net" "os/exec" "reflect" "strings" "github.com/quilt/quilt/db" "github.com/quilt/quilt/minion/docker" "github.com/quilt/quilt/minion/ipdef" "github.com/quilt/quilt/util" "github.com/vishvananda/netlink" log "github.com/Sirupsen/logrus" ) const ( // Etcd is the name etc...
package dummyworker import ( "context" "time" "math/rand" "fmt" "github.com/dave/blast" "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) func New() blast.Worker { return &Worker{} } type Worker struct { base string } func (w *Worker) Start(ctx context.Context, raw map[string]interface{}) e...
package model import ( "gin-webapi/database" "time" "gopkg.in/mgo.v2/bson" ) // User structure type User struct { ID bson.ObjectId `bson:"_id"` FirstName string `bson:"firstname"` LastName string `bson:"lastname"` Address string `bson:"address"` Age int `bson:"a...
package service import ( "fmt" "github.com/Jenkins/model" "github.com/Jenkins/setting" ) func AddUser(name, mobile string) error { id, err := model.AddUser(name, mobile) if err != nil { return err } fmt.Printf("添加用户%v成功,ID为%v", name, id) return nil } func UserInfo(name string) setting.User { return model....
// Copyright 2013 The Chihaya Authors. All rights reserved. // Use of this source code is governed by the BSD 2-Clause license, // which can be found in the LICENSE file. // Package config implements the configuration and loading of Chihaya configuration files. package config import ( "encoding/json" "log" "os" "...
package libpassword import "golang.org/x/crypto/bcrypt" // Hash - Hash password using Bcrypt func Hash(password string) (string, error) { bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14) return string(bytes), err } // CheckHash - Check if password and hash password is valid func CheckHash(password, ...
package main import ( "fmt" "github.com/ProfessorMc/Recipe/spoilers/dish" ) var dishes []*dish.Dish func lab5() { dishes = make([]*dish.Dish, 0) for _, friend := range friends { cakeRecipe, err := cookbook.GetRecipe("cake") if err != nil { panic(err) } order := dish.NewDish(*friend, *cakeRecipe) di...
package main import ( "context" "fmt" "html/template" "log" "net/http" "strings" "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/translate" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/...
package golog import ( "testing" ) func TestLog(t *testing.T) { Start(DebugLevel, AlsoStdout) Start(InfoLevel, AlsoStdout, LogFilePath("./temp"), EveryDay) // GeneralInit() Debugf("debug") Infof("info") }
package network import ( "fmt" "net" "reflect" "encoding/binary" pb "code.google.com/p/goprotobuf/proto" "sofa/proto" ) func init() { } type IDispatcher interface { Dispatch(cliConn *ClientConnection, request interface{}) Disconnect(cliConn *ClientConnection) } type GameServer ...
package main import ( "io/ioutil" "os" "reflect" "testing" ) func TestWordCount(t *testing.T) { f1, err := ioutil.TempFile(".", "tmp") if err != nil { t.Error(err) } defer f1.Close() defer os.Remove(f1.Name()) f1.Write([]byte("test case")) f1.Seek(0, 0) type args struct { f *os.File } tests := []s...
package gomailer type TemplateMessage struct { Message } func NewTemplateMessage(message *Message, template *Template, data interface{}) (*TemplateMessage, error) { body, err := template.Parse(data) if err != nil { return nil, err } message.Body = body return &TemplateMessage{ Message: *message, }, nil }
package torbula import ( "math" "path/filepath" "strconv" "strings" ) func isTorrent(file string) bool { return strings.ToLower(filepath.Ext(file)) == ".torrent" } func roundUp(input float64, places int) (newVal float64) { var round float64 pow := math.Pow(10, float64(places)) digit := pow * input round = m...
package config type RouterSpec struct { Name string `default:"gorilla" mapstructure:"name"` RouterOpts map[string]string `default:"{}" mapstructure:"options"` } func (r RouterSpec) Validate() error { validationError := RouterValidationError{} isValid := true if r.Name == "" { validationError....
package schema_test import ( "encoding/json" "reflect" "testing" schema "github.com/Kangaroux/go-map-schema" "github.com/stretchr/testify/require" ) type mismatch schema.FieldMismatch type missing schema.FieldMissing type TestStruct struct { Foo string Bar int Baz float64 } type TestStructEmbedded struct {...
package main import ( "encoding/json" "log" "net/http" "strconv" "puzzle-maker/puzzle" "github.com/gorilla/mux" ) type toGo struct { Cells []int DepthBFS []int Fitness int Iterations int Solution []string } func main() { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/genal...
package scan import ( "fmt" "unicode" ) type CharSet struct { Pattern } func newCharSet(p Pattern) CharSet { c := CharSet{p} singleLiteralToCharClass(c.Regexp) if !c.isCharSet() { panic(fmt.Errorf("Pattern %s is not a character set.", c.String())) } return c } func Char(p string) CharSet { return newChar...
package main import ( "database/sql" "fmt" "formation/api" "formation/serverweb" _ "github.com/lib/pq" "net/http" ) func main() { /* fmt.Println("Hello Arnaud") a := 4 b := 12 a += b fmt.Println("a += b = ", a) var x int = 50 var y float32 = 30.5 fmt.Printf("x...
/* Copyright [2015] Alex Davies-Moore 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, soft...
package collector import ( "os" "github.com/prometheus/client_golang/prometheus" ) func init() { registerCollector("dbsize", true, NewDBSizeCollector) } const ( dbSizeCollectorSubsystem = "dbsize" ) var ( dbSize = prometheus.NewDesc( prometheus.BuildFQName(namespace, dbSizeCollectorSubsystem, "db_size"), ...
package main import "fmt" func main() { constFunction() //1 } func constFunction() { //#1 const firstName string = "john" //const adalah variable yang tidak bisa diubah(tetap) const lastName = "wick" //teknik interface pada konstanta fmt.Print("halo", firstName, lastName) //fmt.Print tidak ...
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use ...
/* In the fewest bytes, generate the dictionary of keypresses for any letter (as described in https://code.google.com/codejam/contest/351101/dashboard#s=p2) In Python, the dictionary literal itself: {'a':2,'c':222,'b':22,'e':33,'d':3,'g':4,'f':333,'i':444,'h':44,'k':55,'j':5,'m':6,'l':555,'o':666,'n':66,'q':77,'p':7...
package fmm import ( "testing" "github.com/stretchr/testify/require" ) func TestNewDependency(t *testing.T) { tests := []struct { input string name string version *Version kind DependencyKind req VersionCmpRes }{ {"flib", "flib", nil, DependencyRequired, VersionAny}, } for _, test := ra...
package oc import ( "context" "fmt" "github.com/nmiculinic/observe" "github.com/sirupsen/logrus" "go.opencensus.io/examples/exporter" "go.opencensus.io/exporter/prometheus" "go.opencensus.io/stats/view" "go.opencensus.io/trace" "log" "math/rand" "net/http" "sync" "time" ) func g() int { fmt.Println("sid...
package open import "testing" func TestOpenError(t *testing.T) { FileUrlName := "kek111" reader, err := Open(FileUrlName) defer reader.Close() if err == nil { t.Error("There is a problem with opening files") } }
// Copyright 2021 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...