text
stringlengths
11
4.05M
package pathfileops import ( "os" "testing" ) func TestFileMgr_MoveFileToNewDir_01(t *testing.T) { fh := FileHelper{} setupSrcFile := fh.AdjustPathSlash("../../logTest/FileMgmnt/TestFile003.txt") srcFile := fh.AdjustPathSlash("../../checkfiles/TestFile003.txt") destDir := fh.AdjustPathSlash("../../createF...
package recursion import ( "fmt" "testing" ) func Test_canPartitionKSubsets(t *testing.T) { res := canPartitionKSubsets([]int{4, 3, 2, 3, 5, 2, 1}, 4) fmt.Println(res) }
package main import ( "fmt" ) //引用类型包括:channel slice map //内置函数 new() 计算类型大小,为其分配零值内存 返回指针 //make 会被编译器翻译成具体的函数,为其分配内存和初始化成员结构 返回对象而非指针 //类型转换 显示转换 不支持隐式转换 //字符串是不可变值类型 内部用指针指向UTF-8字节数组 //默认值是"" //用索引号访问某字节 如s[i] //不能用序列号获取字节元素指针 如:&s[i] 非法 //不可变类型,无法修改字节数组 //字节数组尾部不能包含NULL func main() { //s := "abc" //b ...
package util import ( "errors" "net" ) var invertTable [256]byte func init() { for value := 0; value < 256; value++ { invertTable[value] = invertByte(byte(value)) } } func compareIPs(left, right net.IP) bool { leftVal, err := ipToValue(left) if err != nil { return false } rightVal, err := ipToValue(righ...
package model import "sort" func SliceEq(a, b []string) bool { if (a == nil) != (b == nil) { return false } if len(a) != len(b) { return false } sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) sort.Slice(b, func(i, j int) bool { return b[i] < b[j] }) for i := range a { if a[i] != b[i]...
// Copyright 2017 Xiaomi, 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 in...
package weather_domain type Weather struct { Latitude float64 `json:"latitude"` Longitude float64 `json:"longitude"` TimeZone string `json:"timezone"` Currently CurrentlyInfo `json:"currently"` } type CurrentlyInfo struct { Temperature float64 `json:"temperature"` Summary string `json:"summary"` DewPoint float...
package main import ( "fmt" "io" "io/ioutil" "log" "net/http" "os" "regexp" "runtime" "strconv" "strings" "text/template" "time" ) type Page struct { Title string SubTitle string ListTitle string FileList string PoweredBy string } type Filelist struct { No string Filename string Aut...
package authentication import ( "github.com/go-ldap/ldap/v3" ) // ProductionLDAPClientFactory the production implementation of an ldap connection factory. type ProductionLDAPClientFactory struct{} // NewProductionLDAPClientFactory create a concrete ldap connection factory. func NewProductionLDAPClientFactory() *Pro...
package app import ( "createorder/controllers/order" "createorder/logger" "github.com/gin-gonic/gin" ) var router = gin.Default() func Start() { router.POST("/Order/CreateOrder", order.CreateOrder) router.POST("/Order/CompleteOrder/:order_id", order.CompleteOrder) router.GET("/Order/GetOrder/:order_id", order....
package main import ( "database/sql" "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" "time" ) // gorm v2 安装和连接 mysql var ( sqlDB *sql.DB gormDB *gorm.DB ) func InitDB() { // driverName driverName := "mysql" // DSN dbUser := "root" dbPassword := "root" protocol := "tcp" dbHost := "127.0.0.1" dbPort := "3...
package main import ( "log" "os" "html/template" ) type user struct { Name, Email, Emoji string Colors []string } // We'll want a pointer to a Template object to be able to execute our // templates later. var templates *template.Template // For convenience, load templates in the init(). func i...
// Copyright 2013 Walter Schulze // // 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 model type UtcTiming struct { // The server to get the time from Value string `json:"value,omitempty"` // The scheme id to use. Please refer to the DASH standard. SchemeIdUri string `json:"schemeIdUri,omitempty"` }
// Copyright 2017 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...
// Copyright 2020 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 livereload implements server for LiveReload protocol 7. // // Everything in this package is safe for concurrent use by multiple goroutines. package livereload import ( "net/http" "path/filepath" "github.com/gorilla/websocket" "github.com/powerman/tr/pkg/broadcast" ) const defaultServerName = "Go" //...
package memoryCacheChan import "testing" import "net/http" import "io/ioutil" var cache *MemoryCacheChan func GetUrl(key string)(interface{}, error) { resp, err := http.Get(key) if err != nil { return nil, err } else { body, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() return body, err } } f...
// 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 in wr...
package problems1to50 import ( "fmt" ) // Problem1 : Multiples of 3 and 5 // Description: https://projecteuler.net/problem=1 func Problem1() { i := 1 result := 0 // All the multiples of 3 or 5 below 1000 for i <= 1000 { if i%3 == 0 || i%5 == 0 { result += i } i++ } fmt.Println(result) }
package main /* * @lc app=leetcode id=148 lang=golang * * [148] Sort List */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ // Solution 1:归并排序 func mergeLists(l1, l2 *ListNode) *ListNode { dummy := new(ListNode) cur := dummy ...
package client import ( "log" "math/rand" "time" jsoniter "github.com/json-iterator/go" "github.com/valyala/fasthttp" ) var ( // A high-performance 100% compatible drop-in replacement of "encoding/json" json = jsoniter.ConfigCompatibleWithStandardLibrary // extraction of json marshaller to allow for testing ...
package utils import ( "../config" "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/firehose" "github.com/aws/aws-sdk-go/service/kinesis" ) var ( AwsSession *session.Session AwsKinesis *kinesis.Kinesis Aws...
package mhfpacket import ( "errors" "github.com/Andoryuuta/Erupe/network" "github.com/Andoryuuta/Erupe/network/clientctx" "github.com/Andoryuuta/byteframe" ) /* 00 58 // Opcode 00 00 00 00 00 00 00 4e 00 04 // Count 00 00 // Skipped(padding?) 00 01 00 00 00 00 00 00 00 02 00 00 5d fa 14 c0 00 03 00 00 5...
package problems_test import ( "encoding/json" "errors" "fmt" "github.com/team-bonitto/bonitto/internal/problems" "io" "io/ioutil" "net/http" "strings" "testing" ) var DB = make([]problems.P8UserStruct, 0) func add(u problems.P8UserStruct) { DB = append(DB, u) } func find(id string) (problems.P8UserStruct...
package vgform import ( "sort" "strings" ) // KeyLister provides a list keys as a string slice. // Keys are used in the `value` attribute of HTML option tags (with a select). type KeyLister interface { KeyList() []string } // KeyListerFunc implements KeyLister as a function. type KeyListerFunc func() []string //...
package Problem0301 import ( "fmt" "sort" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { s string ans []string }{ {"(a)())()", []string{"(a)()()", "(a())()"}}, {"()())()", []string{"()()()", "(())()"}}, {"()())())", []string{"(()())", "(())()", "()(())", "(...
package services import ( "database/sql" "github.com/tianhphahai2/hello-grpc" ) type Test_rgpcServiceServer struct { db * sql.DB } func (s *Test_rgpcServiceServer) checkAPI(api string) error { if len(api) > 0 { if } } //func (HelloServiceImpl) Hello(ctx context.Context, rq *hello.HelloRequest) (*hello.Hello...
package types import ( "io/fs" "time" ) type Filesystem interface { Root() string Protocol() string ModTime() time.Time Chdir(string) (Directory, error) MkdirAll(string) (Directory, error) Close() error } type Directory interface { fs.FileInfo fs.DirEntry Path() string Chdir(string) (Directory, erro...
package main import ( "fmt" "net/http" // "io" "bytes" "strings" // "log" "time" "sync" "io/ioutil" "github.com/qiniu/api.v7/auth/qbox" "github.com/qiniu/api.v7/storage" "github.com/gin-gonic/gin" // "encoding/json" // "strconv" ) var ( accessKey = "" s...
package core type Session struct { parent Space } func (s *Session) Shutdown() { }
package clockface import ( "math" "time" ) const ( halfClockSeconds = 30 clockSeconds = halfClockSeconds * 2 halfClockMinutes = 30 clockMinutes = halfClockMinutes * 2 halfClockHours = 6 clockHours = 12 ) type Point struct { X float64 Y float64 } func secondHandPoint(tm time.Time) Point { ...
/* SPDX-License-Identifier: MIT * * Copyright (C) 2019 WireGuard LLC. All Rights Reserved. */ package router import ( "bytes" "encoding/binary" "errors" "fmt" "log" "net" "sort" "time" "unsafe" ole "github.com/go-ole/go-ole" winipcfg "github.com/tailscale/winipcfg-go" "github.com/tailscale/wireguard-g...
package simple import ( "testing" ) func TestPrepend(t *testing.T) { e := []int{2, 4, 6, 8, 10, 12, 14, 16} s := []int{10, 12, 14, 16} s = Prepend(s, 2, 4, 6, 8) if len(s) != len(e) { t.Error("Expected slice len to be 8, got", len(e)) } for i := range s { if s[i] != e[i] { t.Error("Not expecting", s[i]...
package controllers type Hub struct { clients map[*client]bool broadcast chan []byte register chan *client unregister chan *client content []byte } var h = Hub{ broadcast: make(chan []byte), register: make(chan *client), unregister: make(chan *client), clients: make(map[*client]bool), } func In...
package main import ( "container/heap" "fmt" "sort" ) func main() { fmt.Println(maxScore([]int{ 1, 3, 3, 2, }, []int{ 2, 1, 3, 4, }, 3)) } func maxScore(nums1, nums2 []int, k int) int64 { type pair [2]int a := make([]pair, len(nums1)) sum := 0 for i, x := range nums1 { a[i] = pair{x, nums2[i]} } ...
package middlewares import ( "context" "github.com/go-playground/validator/v10" "github.com/jybbang/go-core-architecture/core" ) type validationMiddleware struct { core.Middleware validate *validator.Validate } func NewValidationMiddleware() *validationMiddleware { return &validationMiddleware{ validate: va...
package main import ( "fmt" "io/ioutil" "log" "math/rand" "ms/sun/shared/helper" "ms/sun/servises/file_service_old" "net/http" "time" ) var cnt int = 1 var size int = 0 func main() { Insert_many(0) file_service_old.Run() http.HandleFunc("/hi", func(writer http.ResponseWriter, r *http.Request) { write...
package main type Animal interface { Move() } // Cat is a concrete animal since it implements the method Move type Cat struct{} func (c *Cat) Move() {} // and somewhere in the code we need to use the crocodile type which is often not our code and this Crocodile type does not implement the Animal interface // but w...
package handler import ( "github.com/gin-gonic/gin" "log" "os" ) func strToBool(s string) bool { if s == "true" { return true } return false } func deleteImg (imgSrc string) error { err := os.Remove(imgSrc) if err != nil { log.Println("Error: while deleting image. Error is ", err) return err } retur...
package repository import ( "github.com/kiryalovik/gameoflife/cellular/model" ) type DummyRepo struct { currentField model.BinaryField } func NewDummyRepo() *DummyRepo { return &DummyRepo{} } // ToDo replace every create with Upsert func (r *DummyRepo) Create(field model.BinaryField) error { r.currentField = fi...
package main import ( "fmt" "net/http" "os" controller "github.com/danielTiringer/Go-Many-Ways/rest-api/controller" router "github.com/danielTiringer/Go-Many-Ways/rest-api/http" repository "github.com/danielTiringer/Go-Many-Ways/rest-api/repository" service "github.com/danielTiringer/Go-Many-Ways/rest-api/serv...
// colly define the flow to file collecting // and cache policy package colly import ( "os" "log" "fmt" "sync" "context" "io/ioutil" "github.com/pkg/errors" "github.com/go-redis/redis" "gopkg.in/natefinch/lumberjack.v2" "github.com/smileboywtu/FileColly/common" "time" ) var logger *log.Logger type Collect...
package bybus import ( "bylib/bylog" "bylib/byutils" "encoding/binary" "errors" "fmt" "github.com/tbrandon/mbserver" "sync" ) type MBTcpServer struct{ mbserv *mbserver.Server //modbus 服务器 holdMux sync.Mutex readWriteHandler map[uint16]*ModbusReadWriteHandler } func (s *MBTcpServer) RegisterHandler(addr, q...
package examples import ( "fmt" "time" ) func worker_(id int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Println("worker ", id, "started job ", j) time.Sleep(time.Second) fmt.Println("worker", id, "finished job", j) results <- j * 2 } } func init() { const numJobs = 5 jobs := make...
package main import ( "fmt" "unsafe" "strconv" ) func main() { a := float32(0.1) fmt.Printf("float32(0.1): %032s\n", strconv.FormatUint((uint64)(*(*uint32)(unsafe.Pointer(&a))),2)) a = 0.2 fmt.Printf("float32(0.2): %032s\n", strconv.FormatUint((uint64)(*(*uint32)(unsafe.Pointer(&a))),2)) a = 0.3 fmt.Printf("...
/* 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...
// https://leetcode-cn.com/problems/remove-element/ package main import "fmt" func main() { nums := []int{2} val := 3 n := len(nums) i := 0 for i < n { if nums[i] == val { nums[i] = nums[n-1] n-- } else { i++ } } fmt.Println(n, nums) } func removeElement1() { // nums := [...
package models type Kitchens struct { Name string `json:"name"` Id uint `json:"id"` Status bool `json:"status"` } type Admin struct { Email string `json:"email"` Passwd string `json:"password"` } type User struct { Id int `json:"id"` FirstName string `json:"firstName"` LastName string `...
package intervalIntersection import ( "reflect" "testing" ) func Test_intervalIntersection(t *testing.T) { type args struct { A [][]int B [][]int } tests := []struct { name string args args wantC [][]int }{ // TODO: Add test cases. { name: "first", args: args{ A: [][]int{ {0, 2}, ...
package main import ( "net/http" "restapi/controllers" "github.com/gin-gonic/gin" validator "github.com/gobeam/custom-validator" ) func main() { router := gin.Default() validate := []validator.ExtraValidation{ {Tag: "number", Message: "Invalid %s Format!"}, {Tag: "email", Message: "Invalid %s Format!"}, ...
package database import ( "database/sql" "fmt" _ "github.com/lib/pq" "github.com/super-link-manager/models" "github.com/super-link-manager/utils" "os" ) func ConnectDB() *sql.DB { var host = os.Getenv("POSTGRES_HOST") var port = os.Getenv("POSTGRES_PORT") var user = os.Getenv("POSTGRES_USERNAME") var passwo...
package gauth import ( "math" "strconv" ) // Returns a boolean indicating if the provided otp string is valid for // the provided secret at the current time. The secret should be base32 // encoded. func ValidateOTP(otp, secret string) bool { correctOTP, err := GetOTP(secret) return (otp == correctOTP) && (err == ...
// Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved. // Use of this source code is governed by the MIT-license that can be // found in the LICENSE file. package main import ( "context" "fmt" "os" "strings" "github.com/spf13/pflag" ) var ErrNoCmd = fmt.Errorf("no cmd") type Command struct { ...
package main import ( "bytes" "fmt" "log" "study-go--mercaridoc/07.エラー処理/エラー処理をまとめる/util" ) func main() { bf := bytes.NewBufferString("ハローworld!") s := util.NewRuneScanner(bf) for s.Scan() { rune := s.Rune() fmt.Printf("%s", string(rune)) } if err := s.Err(); err != nil { log.Fatal(err.Error()) } }
package e2e import ( "context" "fmt" "strings" "time" "github.com/blang/semver/v4" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/stretchr/testify/require" authorizationv1 "k8s.io/api/authorization/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apiextensions-apis...
package main import ( "context" "fmt" "log" "github.com/go-playground/mold/v4" ) func main() { tform := mold.New() tform.Register("set", transformMyData) type Test struct { StringField string `mold:"set"` } tt := Test{StringField: "string"} err := tform.Struct(context.Background(), &tt) if err != nil...
package resource // File holds information about a file. type File struct { ID ID `json:"id"` Version Version `json:"version"` FileData }
// Copyright 2015 The Chromium 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 lhttp implements HTTP client helper code (JSON, automatic retries, // authentication, etc). // // 'l' stands for luci. package lhttp
/* Mexican Wave Simulator The wave (known as a Mexican wave in the English-speaking world outside North America) is an example of metachronal rhythm achieved in a packed stadium when successive groups of spectators briefly stand, yell, and raise their arms. Create a function that takes a string and turns it into a M...
package self import ( "fmt" "io/ioutil" "net" "time" _ "github.com/lucas-clemente/quic-clients" // download clients quic "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go" "gx/ipfs/QmU44KWVkSHno7sNDTeUcL4FBgxgoidkFuTUyTXWJPXXFJ/quic-go/integrationtests/tools/proxy" "gx/ipfs/QmU44KWVkSHno7sNDTeUc...
/* Copyright 2011 Google 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 in writing, software di...
package main import ( "bytes" "fmt" "io" "net/http" "testing" "github.com/slack-go/slack" "github.com/slack-go/slack/slackevents" "github.com/slack-go/slack/socketmode" "go.uber.org/zap" ) type dummySocketmodeClient struct{} func (d dummySocketmodeClient) Ack(_ socketmode.Request, _ ...interface{}) {} func...
package sources import ( "path/filepath" dcapi "github.com/mudler/docker-companion/api" "github.com/lxc/distrobuilder/shared" ) // DockerHTTP represents the Docker HTTP downloader. type DockerHTTP struct{} // NewDockerHTTP create a new DockerHTTP instance. func NewDockerHTTP() *DockerHTTP { return &DockerHTTP{...
package podstatus import ( "encoding/json" "github.com/square/p2/pkg/launch" "github.com/square/p2/pkg/store/consul/podstore" "github.com/square/p2/pkg/store/consul/statusstore" "github.com/square/p2/pkg/types" "github.com/square/p2/pkg/util" "github.com/hashicorp/consul/api" context "golang.org/x/net/contex...
// 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 ...
/* Copyright 2020 The Kubernetes 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, ...
package fs import ( "bytes" "errors" "io" "io/ioutil" "os" "path/filepath" "reflect" "testing" ) func TestOSFilesystemImplementsFS(t *testing.T) { var fs Filesystem fs = OS{} _ = fs } func TestOSFindFilesSuccess(t *testing.T) { dir := tempdir(t) defer os.RemoveAll(dir) logdir := filepath.Join(dir, "lo...
package main import ( "fmt" "log" "time" ) func threeSecond() { time.Sleep(3000 * time.Millisecond) fmt.Println("3 seconds passed") } func oneSecond() { time.Sleep(1000 * time.Millisecond) fmt.Println("1 second passed") } func twoSecond() { time.Sleep(2000 * time.Millisecond) fmt.Println("2 second passed")...
package uaaclient import ( "fmt" "net/http" ) // Session ... type Session struct { ID string Cookie http.Cookie } // SetSessionCookie creates a new session and writes it in a cookie. func (o *UaaClient) SetSessionCookie(w http.ResponseWriter, r *http.Request) string { id := fmt.Sprintf("%s.%s", simpleUUID()...
package util import ( "context" "database/sql" "fmt" "strings" "github.com/elgris/sqrl" "github.com/alewgbl/fdwctl/internal/database" "github.com/alewgbl/fdwctl/internal/logger" "github.com/alewgbl/fdwctl/internal/model" ) func GetServers(ctx context.Context, dbConnection *sql.DB) ([]model.ForeignServer, er...
package commands import ( "fmt" "sync" "strconv" "encoding/json" "github.com/JFrogDev/artifactory-cli-go/utils" ) // Downloads the artifacts using the specified download pattern. // Returns the AQL query used for the download. func Download(downloadPattern string, flags *utils.Flags) string { if flags.A...
package timer import ( "time" msg "../messageTypes" ) func SendWithDelayInt(delay time.Duration, ch chan<- int, message int) { go sendWithDelayIntFunction(delay, ch, message) } func sendWithDelayIntFunction(delay time.Duration, ch chan<- int, message int) { <-time.After(delay) ch <- message } func SendWithDel...
/* 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...
// 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 law or agreed to in writing...
package ufile import ( "context" "fmt" model "github.com/cloudreve/Cloudreve/v3/models" "github.com/cloudreve/Cloudreve/v3/pkg/cache" "github.com/cloudreve/Cloudreve/v3/pkg/filesystem/fsctx" "github.com/cloudreve/Cloudreve/v3/pkg/request" ufsdk "github.com/ufilesdk-dev/ufile-gosdk" "testing" ) func TestDriver_...
package energy_resources import ( "net/http" httplib "gitlab.com/semestr-6/projekt-grupowy/backend/go-libs/http-lib" ) func GetRoutes() (routes httplib.Routes) { routes = httplib.Routes{ httplib.Route{ HttpMethod: http.MethodPost, Route: "/add-energy-resource-attribute", HandlerFunc: addEnergyRe...
package medkit import ( "fmt" "github.com/spf13/cobra" "github.com/spf13/viper" ) // showConfigCmd represents the showConfig command var showConfigCmd = &cobra.Command{ Use: "config", Short: "display the MEDKIT configuration", Long: ` Display the current MEDKIT configuration. This command takes into account ...
/* You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit. Return the minimum number of bo...
package main import ( "fmt" "os" ) var cwd string func init() { var err error cwd, err = os.Getwd() if err != nil { fmt.Fprintf(os.Stderr, "os.Getwd failed: %v", err) } //fmt.Printf("Current work directory: %s\n", cwd) } /* func main() { x := "hello!" fmt.Printf("hello addr %v\n", &x) for _, x := range ...
package admin import "firstProject/app/dto" type AdminContract interface { Register(dto dto.AdminDto) error Login(dto dto.AdminDto) error }
package handlers import ( "encoding/json" "net/http" "strconv" "strings" "github.com/rest_service_task/impl/errors" "github.com/rest_service_task/impl/structs" ) // A errorResponse is the default error message that is generated. // // swagger:response errorResponse type GenericError struct { // in: body Body...
//go:build go1.21 // +build go1.21 package main import ( "github.com/go-playground/log/v8" stdlog "log" "log/slog" ) func main() { // This example demonstrates how to redirect the std log and slog to this logger by using it as // an slog.Handler. log.RedirectGoStdLog(true) log.WithFields(log.G("grouped", log...
package main import ( "context" "log" "time" ) func main() { go consume() if err := produce(context.Background()); err != nil { log.Fatalf("Error producing messages to kafka: %v", err) } time.Sleep(3*time.Second) }
package store import ( "github.com/david-sorm/montesquieu/article" "github.com/david-sorm/montesquieu/users" "html/template" ) // import "github.com/lib/pq" // StoreConfig contains data passed to a Store implementation type StoreConfig struct { Host string Database string Username ...
/** * Copyright 2019 Innodev LLC. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ package errors import ( "fmt" "runtime" "github.com/jinzhu/copier" ) func _copy(e interface{}) *Err { switch err := e.(type) { case *Err: if err...
package main import ( "github.com/gin-gonic/gin" "net/http" ) // IndexGet redirects to sparrho.com func IndexGet(c *gin.Context) { c.Redirect(http.StatusSeeOther, "http://www.sparrho.com/") } // SuccessJSON returns a JSON saying which method was used. func SuccessJSON(c *gin.Context) { c.JSON(http.StatusOK, gin....
package vending_machine import "spark_networks_assessment/pkg/repositories/products" type Service interface { Charge(coins []int) bool Select(product *products.Product) bool Balance() int } type service struct { userCoins []int productRepo products.Repository } func New(productRepo products.Repository) Servi...
package main import ( "flag" "log" "os" "path/filepath" ) var startDir string func main() { flag.StringVar(&startDir, "d", ".", "starting directory") flag.Parse() log.Printf("Walking tree based at %q\n", startDir) filepath.Walk(startDir, walker) } func walker(path string, info os.FileInfo, inErr error) (o...
package main import ( "fmt" "io/ioutil" "log" "net/http" "github.com/gin-gonic/gin" ) func callMicro2(ctx *gin.Context) string { tracingHeaders := []string{ "x-request-id", "x-b3-traceid", "x-b3-spanid", "x-b3-sampled", "x-b3-parentspanid", "x-b3-flags", "x-ot-span-context", } headersToSend := ...
package site import ( "fmt" "net/http" ) func Abort(status int, w http.ResponseWriter, r *http.Request) { switch status { case 404: w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "404 page error") case 301: // case 302: // } }
package model import "time" type Precipitation struct { Id int64 `json:"id"` Value float32 `json:"value"` Timestamp time.Time `json:"timestamp"` } type Precipitations []Precipitation func (this Precipitation) GetId() (int64) { return this.Id } func (this Precipitation) GetValue() (float32) {...
package game_map import ( "github.com/faiface/pixel/pixelgl" ) type BlockUntilEvent struct { UntilFunc func() bool } func BlockUntilEventCreate(untilFunc func() bool) *BlockUntilEvent { return &BlockUntilEvent{ UntilFunc: untilFunc, } } func (b BlockUntilEvent) Update(dt float64) { } func (b BlockUntilEvent...
package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/andschneider/goqtt" "github.com/andschneider/goqtt/packets" influxdb2 "github.com/influxdata/influxdb-client-go" ) // config contains the necessary information to create clients for both // Influx and goqtt. It also holds an InfluxD...
package controlplane import ( "context" "fmt" "time" "github.com/cenkalti/backoff/v4" "github.com/google/uuid" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" "github.com/pomerium/pomerium/internal/log" "github.com/pomerium/pomerium/pkg/grpc" databrokerpb ...
package routes import "github.com/tedsuo/rata" const ( Ping = "PING" Env = "ENV" InstanceIndex = "INDEX" StartedAt = "STARTED_AT" ListExperiments = "LIST_EXPERIMENTS" Experiments = "EXPERIMENTS" Hello = "HELLO" Exit = "EXIT" MakeTmpFile = "MAKE_TMP_...
package auth import ( "errors" "fmt" "net/http" "os" "strings" "time" "github.com/majid-cj/go-docker-mongo/util" "github.com/dgrijalva/jwt-go" ) // TokenInterface ... type TokenInterface interface { CreateJWTToken(string, string) (*TokenDetail, error) ExtractJWTTokenMetadata(*http.Request) (*AccessDetail,...
package apis import "encoding/json" /** * api结构体, 所有API基于此结构体. */ type Api struct{} func (this Api) StatusCode(status int, message string, data interface{}) string { result := make(map[string]interface{}) result["status"] = status result["message"] = message result["data"] = data jsonString, _ := json.Marsha...
package main import ( "delay" "fmt" "math/rand" "rtos" "display/eve" "display/eve/ft80" "stm32/evedci" "stm32/hal/dma" "stm32/hal/exti" "stm32/hal/gpio" "stm32/hal/irq" "stm32/hal/spi" "stm32/hal/system" "stm32/hal/system/timer/systick" ) var dci *evedci.SPI func init() { system.Setup168(8) systic...
package pie // Keys returns the keys in the map. All of the items will be unique. // // Due to Go's randomization of iterating maps the order is not deterministic. func Keys[K comparable, V any](m map[K]V) []K { // Avoid allocation l := len(m) if l == 0 { return nil } i := 0 keys := make([]K, len(m)) for key...