text
stringlengths
11
4.05M
package worker import ( "testing" ) func Test_Resolve_1(t *testing.T) { array := [6][2]string{ {"126.com", "ns"}, {"126.com", "mx"}, {"126.com", "txt"}, {"8.8.8.8", "ptr"}, {"mail.126.com", "a"}, {"mail.126.com", "cname"}, } for _, v := range array { addr, rtype := v[0], v[1] result := Resolve(&ad...
/* Copyright © 2021 Joe Kralicky 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, software ...
package launchpad import ( "gitlab.com/gomidi/midi" ) type scrollingTextBuilderMK2 struct { Seq []byte outputStream midi.Out } func (l *LaunchpadMK2) Text(color Color) ScrollingTextBuilder { return l.text(color, false) } func (l *LaunchpadMK2) TextLoop(color Color) ScrollingTextBuilder { return l.text...
// +build !js package main import ( "flag" "fmt" "io" "log" "net/http" "os" "os/exec" "path/filepath" "strings" "time" "github.com/fsnotify/fsnotify" "github.com/gobwas/glob" ) //arrayFlags is an array of string flags. type arrayFlags []string func (i *arrayFlags) String() string { return "ArrayFlags"...
package tunnel import ( "fmt" "github.com/asppj/cnbs/net-bridge/options" ) func init() { // 校验 if p, _ := NewBuffWithPrefix(options.HeartbeatNet, 0); len(p) != options.PrefixLen { panic(fmt.Errorf("前缀长度与规定不匹配:PrefixLen(%d)!=NewBuffWithPrefix(%d)", options.PrefixLen, len(p))) } }
package getui_model import ( "fmt" "testing" ) func TestSingle(t *testing.T) { var p Single p.Cid = "2326fbc31ef63427a82e667b74353341" p.Message.Appkey = "al0zZ6nvSO9tvxPPrTVHD9" p.Message.IsOffline = false p.Message.Msgtype = "notification" p.Message.OfflineExpireTime = 1000000 p.Notification.Style.Type =...
package response import ( "time" "github.com/agusbasari29/Skilltest-RSP-Akselerasi-2-Backend-Agus-Basari/entity" "gorm.io/gorm" ) type ResponseTransaction struct { ID uint `json:"id"` ParticipantId int `json:"participant_id"` CreatorId int `json:...
package main import "testing" func TestGetJumps(t *testing.T){ pairStrings := []string{"0", "0", "1", "0", "0", "1", "0"} returnValue := GetJumps(pairStrings, 7) if (!(returnValue == 4)){ t.Error() } pairStrings = []string{"0", "0", "0", "0", "1", "0"} returnValue = GetJumps(pairStrings, 6) if (!(returnVal...
package worker import ( "testing" ) func Test_HttpRequest_1(t *testing.T) { array := [...][2]string{ {"http://www.baidu.com", "GET"}, {"https://www.alipay.com/", "HEAD"}, // {"https://mail.163.com", "HEAD"}, // {"http://www.sina.com", "HEAD"}, // {"https://mail.126.com", "GET"}, // {"https://mail.qq.com...
package domain // Geolocation holds latitude and longtitude type Geolocation struct { Latitude float32 Longitude float32 }
package goSolution import "strings" func findDuplicate(paths []string) [][]string { contents := make(map[string][]string) for _, path := range paths { seg := strings.Split(path, " ") dir := seg[0] for _, file := range seg[1:] { p := strings.Index(file, "(") path, content := file[:p], file[p:len(file)-...
package redis import ( "strings" "github.com/go-redis/redis" ) type redisClient struct { client *redis.Client } func NewRedisClient(config Config) RedisClient { r := redisClient{} r.client = redis.NewClient(&redis.Options{ Addr: "localhost:32768", }) return &r } func (r *redisClient) GetTranslation(t Ge...
package gsettings import ( "errors" "sync" ) var ( mu = &sync.RWMutex{} s = make(map[string]string) ErrNotFound = errors.New("Key not found") ) func Reset() { s = make(map[string]string) } func Set(key, value string) { mu.Lock() s[key] = value mu.Unlock() } func Get(key string) (string, error) { mu.RLo...
package translator import ( "github.com/sirupsen/logrus" "io/ioutil" "net/http" "net/url" "regexp" "strings" ) const translateURL = "http://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=uk&dt=t&q=" func TranslateText(text string) string { resp, err := http.Get(translateURL + url.QueryEscape...
package main import ( "github.com/danitw/api-em-go/database" "github.com/danitw/api-em-go/routes" "gopkg.in/macaron.v1" ) func main() { db := database.Connection() defer db.Close() database.Migrate(db) m := macaron.Classic() routes.Routes(m) m.Run() }
package mwords import ( "crypto/sha256" "errors" "math/big" "strings" ) type MnemonicSentence []string func (ms MnemonicSentence) String() string { return strings.Join(ms, " ") } func (ms MnemonicSentence) IsValid() bool { if len(ms)%sentenceMultiple != 0 || len(ms) < sentenceMinWords || len(ms) > sentenceM...
// RAINBOND, Application Management Platform // Copyright (C) 2014-2017 Goodrain Co., Ltd. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your opt...
// Copyright (c) 2019-2021 Leonid Kneller. All rights reserved. // Licensed under the MIT license. // See the LICENSE file for full license information. package rnames import ( "errors" "github.com/reconditematter/mym" "math" "math/rand" "time" ) // HumanName -- the name and gender of a person. type HumanName s...
package main import ( "log" "net/http" "strconv" "onikur.com/text-to-img-api/api" "onikur.com/text-to-img-api/utils" "onikur.com/text-to-img-api/conf" ) func main() { conf.Init() utils.Fonts().CacheFonts() mux := http.NewServeMux() mth := &api.MakeTextHandler{} mux.Handle("/-/", mth) mux.Handle("/api/t...
package parser import ( "bytes" "github.com/bouncepaw/mycomarkup/v2/blocks" "github.com/bouncepaw/mycomarkup/v2/mycocontext" ) // Call only if there is a list item on the line. func nextList(ctx mycocontext.Context) (list blocks.List, eof bool) { var contents []blocks.Block rootMarker, rootLevel, _ := markerOnNe...
package twch import ( "fmt" "net/http" "reflect" "testing" ) func TestListBlocks(t *testing.T) { setup() defer teardown() mux.HandleFunc("/users/test_user1/blocks", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{ "_links": { "next": "https://api.twitch.tv/kraken/use...
package main import "fmt" func normalFunction() { println("normalFunction") } func argument(text string) { println("text") } func arguments(a, b int, c string) { fmt.Printf("%d mas %d es igual a %s\n", a, b, c) } func returned(number int) int { return number * 2 } func multiReturn(a int) (b, c, d int) { retu...
/* * Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. * * file: main.go * details: Entry point for Query API Server, the binary creates Command * Line Interface (CLI) utility to run the application. * */ package main import ( "net/http" "os" dbhandler "github.com/Juniper/collector/query-a...
package imageutil import ( "bytes" "encoding/hex" "crypto/sha256" "testing" ) func TestReadRgbaPng(t *testing.T) { goldImageHash := "d333fb91aa05709483df2d00f62e3caa91db0be1b30ff72e8e829f3264cb30b9" image, err := ReadRgbaPng("test_data/fruits.png") if err != nil { t.Fatal(err) } if image...
package urlmanipulations import ( "context" "fmt" "github.com/go-chi/chi/v5" "io" "log" "net" "net/http" "net/url" "os" "github.com/rs/zerolog" ) //go:generate mockgen --source=./url_manipulations.go --destination=./url_manipulations_mocks_test.go --package=urlmanipulations_test type CallerURL interface {...
package main import ( "bufio" "flag" "fmt" "math" "os" ) const maximumSum = 10000 type coordinate struct { w, h float64 } func main() { filePath := flag.String("p", "input.txt", "Input's file path") flag.Parse() f, err := os.Open(*filePath) if err != nil { fmt.Fprintf(os.Stderr, "Opening input file: %v...
package main import "fmt" type IPhone interface { LoginQQ() } type IPhone7 struct{} func (p *IPhone7) LoginQQ() { fmt.Println("正在使用 IPhone7 登陆QQ") } type IPhone13 struct{} func (p *IPhone13) LoginQQ() { fmt.Println("正在使用 IPhone13 登陆QQ") } type IPhone110 struct{} func (p *IPhone110) LoginQQ() { fmt.Println("...
package kuu import ( "testing" ) func TestGetXAxisNames(t *testing.T) { _10 := GetXAxisNames(10) if _10[len(_10)-1] != "J" { t.Errorf("wrong x-axis name: %v\n", _10) } else { t.Log(_10) } _27 := GetXAxisNames(27) if _27[len(_27)-1] != "AA" { t.Errorf("wrong x-axis name: %v\n", _27) } else { t.Log(_27...
package main import ( "fmt" "log" "os" "github.com/godbus/dbus" "github.com/godbus/dbus/introspect" "pault.ag/go/config" "pault.ag/go/wmata" ) var wifiMetroMap = map[string][]string{ "Dolcezza Dupont - Guest": []string{"A03"}, "Pretty Fly for a WiFi": []string{"B35"}, } type WMATADbusInterface struct{} ...
package main import ( ".." // pulse-simple "fmt" ) func main() { fmt.Printf("Channel Map Test\n") fmt.Printf("================\n") fmt.Printf("CHANNELS_MAX: %v\n", pulse.CHANNELS_MAX) fmt.Printf("\nMono\n") fmt.Printf("----\n") mono := &pulse.ChannelMap{} mono.InitMono() print_info(mono) fmt.Printf("\nSt...
package group import ( "Open_IM/pkg/common/config" "Open_IM/pkg/common/db" "Open_IM/pkg/common/db/mysql_model/im_mysql_model" "Open_IM/pkg/common/log" pbGroup "Open_IM/pkg/proto/group" "Open_IM/pkg/utils" "context" ) func (s *groupServer) QuitGroup(ctx context.Context, req *pbGroup.QuitGroupReq) (*pbGroup.Comm...
package model type ResourceLimit struct { // 资源限制 Memory int64 `json:"memory"` CpuShare uint64 `json:"cpuShares"` Timeout int `json:"timeout"` // 超时时间 }
package routes import ( "fmt" "log" "net/http" "sort" "strconv" "github.com/codegangsta/martini" "github.com/coopernurse/gorp" "github.com/zachlatta/southbayfession/misc" "github.com/zachlatta/southbayfession/models" ) type School struct { Id int `json:"id"` Name string `json:"nam...
// vi:nu:et:sts=4 ts=4 sw=4 // See License.txt in main repository directory (Public Domain) // Test Go's object capabilities and how it works. // Actually, inheritacne works pretty much the same as in other // Object Oriented Programming languages. We have upward in- // heritance as normal. However, there is no way...
package esclient import ( "log" elastigo "github.com/mattbaird/elastigo/lib" ) //CreateESClient create ElasticSearch client func CreateESClient(esAddress, esPort string) (*elastigo.Conn, error) { ec := elastigo.NewConn() ec.Domain = esAddress ec.Port = esPort ec.RequestTracer = func(method, url, body string) {...
// 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 utils import ( "bytes" "encoding/binary" ) func Str2Byte(str string) []byte { var ret []byte = []byte(str) return ret } func Byte2Str(data []byte) string { //var str string = string(data[:len(data)]) var str string = string(data[:]) return str } func MergeSlice(s1 []byte, s2 []byte) []byte { slice :...
package aoc2020 // day17_hypercube is a helper for day17 to isolate the "hypercube" component (part 2). import ( "strings" "github.com/pkg/errors" ) // conwaHypercube represents a Conway hypercube type conwayHypercube [][][][]bool func (hcube conwayHypercube) String() string { var sb strings.Builder for ww := ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/9/1 8:43 上午 # @File : lt_53_最大子序和.go # @Description : # @Attention : */ package offer func maxSubArray(nums []int) int { if len(nums) == 0 { return 0 } max := nums[0] for index := 1; index < len(nums); index++ { if nums[index]+nums[index-1] > nums[ind...
package player import ( "fmt" "github.com/kataras/iris/core/errors" "goslib/gen_server" "goslib/logger" "goslib/scene_utils" "goslib/session_utils" ) const SERVER = "__player_manager_server__" /* GenServer Callbacks */ type PlayerManager struct { } func StartPlayerManager() { gen_server.Start(SERVER, new(...
// 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...
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this f...
/** *@Author: haoxiongxiao *@Date: 2018/10/5 *@Description: CREATE GO FILE queue */ package queue import ( "testing" "fmt" ) func TestArraryQueue_EnQueue(t *testing.T) { arraryQueue := InitNoParam() for i := 0; i < 10; i++ { arraryQueue.EnQueue(i) } fmt.Println(arraryQueue.ToString()) arraryQueue.DeQueue() ...
/* Copyright 2020 The Qmgo 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, sof...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/10/15 9:10 上午 # @File : lt_134_加油站.go # @Description : # @Attention : */ package offer // 解题关键: // 遍历所有的加油站,判断是否都能够到达 func canCompleteCircuit(gas []int, cost []int) int { n := len(cost) for i := 0; i < n; { count := 0 // 当前走过的加油站 sumOfCas := 0 // 总...
package main import ( "fmt" log "github.com/sirupsen/logrus" "io" "os" "sync" "time" ) // buildVersion should be populated at build time by build ldflags var buildVersion string func init() { Apps = make(map[Application]Metric) } func main() { start := time.Now() var flag Flag flag.Version = buildVersion...
package dto import ( "bytes" "encoding/binary" ) //This interface is used for additional data that could be send with some aggregations type AggregationData interface { Encoder Size() int GetBucketCount() int32 } //This structure keeps additional data for histogram by value aggregation type HistogramValueData s...
package connlib import ( "bufio" "io" "regexp" "strconv" "strings" ) var fieldSeparator = regexp.MustCompile("\\s+") // ParseEndpoint - Parses and hexadecimal IPv4 endpoint (eg.: "0100007F:1F90") func ParseEndpoint(endpoint string) (*Endpoint, error) { parts := strings.Split(endpoint, ":") ip, err := strconv...
package main import ( "fmt" _ "image/jpeg" _ "image/png" "os" "strconv" "time" "github.com/deluan/bring" "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/sirupsen/logrus" "golang.org/x/image/colornames" ) const ( windowTitle = "Bring it on!" defaultWidth = 1024 defaultHeight...
/* 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...
// Copyright 2016 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 main import ( "flag" "fmt" "log" "os" "github.com/fatih/color" "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/config" "gopkg.in/src-d/go-git.v4/plumbing" ) func flagInit() (int, string) { color.Set(color.Bold) prID := flag.Int("n", -1, color.HiRedString("number of pull request you want to fet...
package handler import ( "log" "net/http" "github.com/google/uuid" "github.com/gorilla/mux" . "2019_2_IBAT/pkg/pkg/models" ) func (h *Handler) CreateFavorite(w http.ResponseWriter, r *http.Request) { //+ w.Header().Set("Content-Type", "application/json; charset=UTF-8") authInfo, ok := FromContext(r.Context(...
package main import ( "fmt" "os" "strconv" "time" "github.com/actions-go/toolkit/core" ) var now = func() time.Time { return time.Now() } func runMain() { sleep := os.Getenv("INPUT_MILLISECONDS") core.Debug(fmt.Sprintf("Waiting %s milliseconds", sleep)) core.Debug(now().String()) delay, err := strconv.Ato...
package ionic import ( "bytes" "encoding/json" "fmt" "github.com/ion-channel/ionic/risk" ) // GetScores takes one or more purl or other software ids, then performs a request for scores // against the Ion API, returning a set of scores based on the ids func (ic *IonClient) GetScores(ids []string, token string) ([]...
/* * VMaaS Webapp * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * API version: 1.3.2 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package vmaas import ( _context "context" _ioutil "io/ioutil" _nethttp "net/http" _ne...
package middlewares import ( "fmt" "encoding/hex" "net/http" "github.com/bitly/go-simplejson" "github.com/pkg/errors" ) //string to HEX func stringToHex(input string) string{ result := hex.EncodeToString([]byte(input)) return result } //将数字转化为16进制表示 func getlength(length int) string{ //防止返回0 if length == ...
package main import ( "context" "github.com/BukkitAPI-Translation-Group/docsbox/conf" "github.com/BukkitAPI-Translation-Group/docsbox/router" "github.com/BukkitAPI-Translation-Group/docsbox/updater" "github.com/BukkitAPI-Translation-Group/docsbox/util" "github.com/labstack/echo/middleware" "github.com/labstack/...
package main import ( "fmt" "io/ioutil" "log" "os" "github.com/google/uuid" ) const machineIDFilePath = "/etc/insights-client/machine-id" func getMachineID() string { if _, err := os.Stat(machineIDFilePath); os.IsNotExist(err) { UUID, err := uuid.NewUUID() if err != nil { log.Fatal(err) } file, err...
package craft import ( "archive/tar" "archive/zip" "bytes" "context" "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "text/tabwriter" "time" "github.com/danhale-git/craft/internal/files" "github.com/danhale-git/craft/mcworld" docker "github.com/docker/docker/api/types" "github.com/d...
package main import ( "fmt" "time" ) /** * author: will fan * created: 2020/4/14 11:15 * description: */ func main() { switch time.Now().Weekday() { case time.Saturday: fmt.Println("Today is Saturday") case time.Sunday: fmt.Println("Today is Sunday") default: fmt.Println("Today is weekday") } // h...
package mmcore // #cgo CFLAGS: -I../MMCoreC // // #include "MMCoreC.h" import "C" import ( "fmt" ) type Error int func statusToError(status C.MM_Status) error { if int(C.int(status)) == 0 { return nil } return Error(int(C.int(status))) } func (e Error) Error() string { s := errText[e] if s == "s" { retur...
package soapboxd import ( "database/sql" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "github.com/adhocteam/soapbox/proto" gpb "github.com/golang/protobuf/ptypes/timestamp" "github.com/pkg/errors" "golang.org/x/net/context" ) func (s *Server) ListConfigurations(ctx context.Context, ...
// Code generated from /Users/renyunyi/go_project/gengine/internal/iantlr/gengine.g4 by ANTLR 4.9. DO NOT EDIT. package parser // gengine import "github.com/antlr/antlr4/runtime/Go/antlr" type BasegengineVisitor struct { *antlr.BaseParseTreeVisitor } func (v *BasegengineVisitor) VisitPrimary(ctx *PrimaryContext) i...
package problem0155 // MinStack 最小栈 type MinStack struct { data []int size int capacity int min int } // Constructor  构造器 func Constructor() MinStack { return MinStack{ data: make([]int, 10), capacity: 10, size: 0, min: 0, } } // Push 入栈 func (stack *MinStack) Push(x int) { i...
package qingstor import ( "context" "strings" "github.com/pengsrc/go-shared/convert" "github.com/sirupsen/logrus" "github.com/yunify/qingstor-sdk-go/v3/service" "github.com/yunify/qscamel/model" "github.com/yunify/qscamel/utils" ) // List implement source.List func (c *Client) List(ctx context.Context, j *mo...
package handler import ( "testing" "github.com/stretchr/testify/assert" ) func TestHelper_getPageQueryParam(t *testing.T) { page := getPageQueryParam("10") assert.Equal(t, 10, page) page = getPageQueryParam("no number") assert.Equal(t, 1, page) page = getPageQueryParam("") assert.Equal(t, 1, page) }
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" "strconv" "github.com/gorilla/mux" ) type image struct { Name string `json:"name"` ID int `json:"id"` } type images []image type album struct { Name string `json:"name"` ID int `json:"id"` List images `json:"list"`...
package server import( "golang.org/x/net/context" empty "github.com/golang/protobuf/ptypes/empty" vending "github.com/dalin-williams/shoppersshop-protoc-dalinwilliams-com/vending" ) func (s *vendingServer) SessionCreateUser(ctx context.Context, msg *vending.SessionCreateUserRequest) (*vending.SessionCreateUserR...
package consensus import ( "io" "github.com/hashicorp/raft" ) // FSM implements the raft FSM interface // and holds a state type FSM struct { state state } // NewFSM creates a new FSM with // start state of "first" func NewFSM() *FSM { return &FSM{state: first} } // Apply updates our FSM func (f *FSM) Apply(r ...
package main import ( "flag" "fmt" "log" "net" "os" "sync" "syscall" "time" dd "github.com/yawn/doubledash" ) const app = "sw" var ( build = "undefined" version = "unreleased" ) var ( sleep time.Duration timeout time.Duration ) func init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage...
package main import ( "fmt" // "strings" ) func conta_vogais (s string, c chan int) { soma := 0 for i := 0; i < len(s); i++ { if s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u'{ soma++ } } c <- soma } func main () { s := "yuri oliveira franco" c := make(chan int) meio := le...
package gcalbot import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "net/url" "strings" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat" "github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1" "github.com/malware-unicorn/managed-bots/base" "golang.org/x/oauth2" ) type Handler str...
package strings import ( "testing" ) func TestAllCharsUnique(t *testing.T) { tests := []struct { in string expected bool }{ {"abcdefg", true}, {"abcdefgfedcba", false}, } for _, test := range tests { actual := allCharsUnique(test.in) if actual != test.expected { t.Errorf("Expected: %v, got:...
package models import( "app/services" "github.com/spf13/viper" "github.com/jinzhu/gorm" validator "github.com/asaskevich/govalidator" _ "github.com/jinzhu/gorm/dialects/mysql" "math/rand" "strings" "strconv" "fmt" "time" ) type DbMethods struct { DB *gorm.DB } var instance *gorm.DB var dmInstance *DbMetho...
// Copyright © 2022 IN2P3 Computing Centre, IN2P3, CNRS // Copyright © 2018 Philippe Voinov // // Contributor(s): Remi Ferrand <remi.ferrand_at_cc.in2p3.fr>, 2021 // // This software is governed by the CeCILL license under French law and // abiding by the rules of distribution of free software. You can use, // modify...
package printer import ( "strconv" "github.com/davyxu/tabtoy/util" "github.com/davyxu/tabtoy/v2/i18n" "github.com/davyxu/tabtoy/v2/model" ) func valueWrapperJson(t model.FieldType, node *model.Node) string { switch t { case model.FieldType_String: return util.StringEscape(node.Value) case model.FieldType_E...
package main import ( "fmt" ) func main() { number := 10 if number == 10 { fmt.Println("true") } else { fmt.Println("false") } fmt.Println("==================") // khởi tạo kết hợp so sánh if a := 100; a > 100 { fmt.Println("a>100") } else { fmt.Println("a <= 100") } fmt.Println("==============...
package main type Config struct { MongoDB struct { Host string `yaml:"host"` } `yaml:"mongodb"` WWW struct { Home string `yaml:"home"` } Url struct { Port int `yaml:"port"` Base string `yaml:"base"` } }
package main import ( "context" "fmt" "os/exec" "time" ) type result struct { output []byte err error } func main() { // 基于context实现协程通信 var ( ctx context.Context cancel context.CancelFunc cmd *exec.Cmd resultChan chan *result // 下面利用channel实现协程之间通信 res *result ) ctx, ...
package goose import ( "fmt" "time" "github.com/evelritual/goose/graphics" "github.com/evelritual/goose/input" ) const ( defaultImage = "../../logo.png" ) // Game declares all methods required to run a game type Game interface { Close() error Draw() error FixedUpdate(time.Duration) error Init() error Upda...
package main import ( "encoding/json" "fmt" "log" "sync" "github.com/gordonrehling2/web-scrape-go/webscraper" ) // USER STORY // // As a software developer // I want to consume product item data from a web page and recompose it in JSON // So that it can be more easily re-purposed // GOL was updated on Mon 27-M...
package main import "fmt" func use(fruits ...string) { allFruits := append(fruits, fruits...) for idx, fruit := range allFruits { fmt.Println(idx, " => ", fruit) } } func main() { var fruits = []string { "apple", "banana", "cherry", } use(fruits...) } //OUT...
// time: O(n) (O(100n)), space: O(n) func numSquares(n int) int { psq := make([]int, 0, 100) for i := 1; i * i <= 10000; i++ { psq = append(psq, i*i) } m := make([]int, n+1) for i := 1; i <= n; i++ { step := m[i-psq[0]] + 1 for j := 1; j < len(psq); j++ { if psq[j...
package main import ( "fmt" "math/rand" "time" ) func main() { var name string fmt.Println("Welcome to rock, paper, scissor!") options := [3]string{"rock", "paper", "scissor"} fmt.Println("The options are:", options) fmt.Printf("Please choose an option: ") fmt.Scanf("%s", &name) fmt.Println("You chose: ", n...
package config import ( "errors" "github.com/mitchellh/go-homedir" "github.com/sirupsen/logrus" "io" "os" "path/filepath" ) var errNotFound = errors.New("cannot find config file") var triedPaths []string var ( // ClientConfigFile Filename of client configuration ClientConfigFile string = "client-config.yml"...
package utilz import ( "encoding/csv" "github.com/faiface/pixel" "github.com/faiface/pixel/imdraw" "github.com/golang/freetype/truetype" "golang.org/x/image/font" "image" "image/color" "image/png" _ "image/png" "io" "io/ioutil" "math" "math/rand" "os" "strconv" "time" ) /* e.g. usage : heroFrames :=...
package False_Sharing import "sync/atomic" type MyAtomic interface { Increase() } type NoPad struct { a uint64 b uint64 c uint64 } func (atm *NoPad) Increase() { atomic.AddUint64(&atm.a,1) atomic.AddUint64(&atm.b,1) atomic.AddUint64(&atm.c,1) } type Pad struct { a uint64 _p1 [8]uint64 b uint64 _p2 [8]u...
package router import ( "time" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" // "github.com/spf13/viper" "github.com/corentindeboisset/golang-api/app/controller" ) func GetRouter() (*chi.Mux, error) { r := chi.NewRouter() // Use some middleware r.Use(middleware.RequestID) r.Use(middleware.Real...
package game var ( explosionWidth float32 = 150 explosionHeight float32 = explosionWidth explosionMaxPushSpeed float32 = 300 ) func newExplosion(grenade *Grenade) { x, y := grenade.GetCenter() l, t, w, h := x-explosionWidth/2, y-explosionHeight/2, explosionWidth, explosionHeight gameMap := grenade....
package inmemory import ( "github.com/Tanibox/tania-core/src/assets/repository" "github.com/Tanibox/tania-core/src/assets/storage" "github.com/gofrs/uuid" ) type FarmEventRepositoryInMemory struct { Storage *storage.FarmEventStorage } func NewFarmEventRepositoryInMemory(s *storage.FarmEventStorage) repository.Fa...
package writer import ( "bytes" "fmt" "io" "os" "strconv" "strings" "github.com/goldeneggg/ipcl/lib/parser" ) var ( Out io.Writer = os.Stdout fpf = fmt.Fprintf headers = []string{"source_cidr", "network", "mask", "host_num", "min_address", "max_address", "broadcast"}...
package service import ( "2019_2_IBAT/pkg/app/notifs/notifsproto" // . "2019_2_IBAT/pkg/pkg/models" "context" "testing" "github.com/google/uuid" ) func TestUserService_SendNotification(t *testing.T) { h := Service{ NotifChan: make(chan NotifStruct, 5), } ctx := context.Background() msg := notifsproto.Sen...
package types // DONTCOVER import ( sdk "github.com/cosmos/cosmos-sdk/types" ) // query endpoints supported by the NFT Querier const ( QuerySupply = "supply" QueryOwner = "owner" QueryCollection = "collection" QueryDenoms = "denoms" QueryDenom = "denom" QueryNFT = "nft" ) // QuerySup...
package gasprice import ( "crypto/rand" "log" "math/big" "sync" "time" ) // Randomizer randomly calculates a new gas price within a range at regular intervals type Randomizer struct { randomizeInterval time.Duration maxGasPrice *big.Int minGasPrice *big.Int running bool mu sync.RWMutex ...
// Copyright 2018 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"...
/* Copyright 2021 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 forkexec import ( "os" "syscall" "testing" "github.com/criyle/go-sandbox/pkg/mount" ) func TestFork_DropCaps(t *testing.T) { t.Parallel() r := Runner{ Args: []string{"/bin/echo"}, CloneFlags: syscall.CLONE_NEWUSER, DropCaps: true, } _, err := r.Start() if err != nil { t.Fatal(err) }...
package db import ( "encoding/json" "html/template" "strconv" "sync" "time" "github.com/Jleagle/steam-go/steam" "github.com/gosimple/slug" "github.com/steam-authority/steam-authority/helpers" "github.com/steam-authority/steam-authority/logging" "github.com/steam-authority/steam-authority/memcache" ) // tod...
package env import ( "fmt" "os" "strconv" ) // GetUint32 extracts uint32 value from env. if not set, returns default value. func GetUint32(key string, def uint32) uint32 { s, ok := os.LookupEnv(key) if !ok { return def } v, err := strconv.ParseUint(s, decimalBase, bitSize32) if err != nil { return def }...