text
stringlengths
11
4.05M
package profiler import ( "fmt" "math" "sync" "sync/atomic" "time" ) const MaxTryCntSwap = 3 var m sync.Mutex var mapProfiler map[string]*profiler type Profiler interface { Start() time.Time End(time.Time) time.Duration Info() string } type profiler struct { Name string // By priority atomics operations ...
package main import ( "log" "fmt" "github.com/viper" ) func main() { viper.SetConfigName("config") // name of config file (without extension) viper.AddConfigPath(".") // optionally look for config in the working directory err := viper.ReadInConfig() // Find and read the config fi...
package memtable type Node struct { key uint32 value uint32 } type KeyValue struct { key string value uint32 }
package main import "fmt" import "reflect" // slice 有两个特殊的属性 len, cap func main() { var s []int fmt.Println(s) s2 := make([]int, 50, 100) i := 10240000 fmt.Println(cap(s)) fmt.Println(cap(s2)) for j := 1; j <= i; j++ { s = append(s, j) } s2 = append(s2, 1) fmt.Println(cap(s2)) fmt.Println(cap(s)) ...
package main import ( "fmt" "io" "os" ) func main() { sum_i := 0 sum_f := 0.0 sum_a := make([]string, 0) for { var n int var m float64 var s string i, err := fmt.Scan(&n, &m, &s) if i == 3 { sum_i += n sum_f += m sum_a = append(sum_a, s) } else if i == 0 && err == io.EOF { break } el...
package main import ( "os"; "fmt"; "http"; "bytes"; ) func main() { fmt.Printf("***start http test***\n"); // TODO body data, AMF3 format Message // test for BlazeDS AMF data buf := [...]byte { 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x6E, 0x75, 0x...
package container import "reflect" // BindValue bind a value to container func (c *containerImpl) BindValue(key string, value interface{}) error { return c.bindValueOverride(key, value, false) } // HasBoundValue return whether the kay has bound to a value func (c *containerImpl) HasBoundValue(key string) bool { c....
package envkit import ( "bufio" "fmt" "io" "os" "sort" "strings" ) // Read to get environment map func Read(r io.Reader) map[string]string { m := make(map[string]string) sc := bufio.NewScanner(r) for sc.Scan() { line := sc.Text() if i := strings.IndexRune(line, '='); i >= 0 { m[line[:i]] = line[i+1:] ...
package main import ( "encoding/json" "log" "testing" ) type JsonUser struct { Id int `json:"id"` Name string `json:"name"` Address string `json:"address"` } func BenchmarkEncodingJson(b *testing.B) { var ( user JsonUser str string = `{"id":5,"name":"hoge","address":"東京"}` ) b.ResetTimer() ...
package callbacks import ( "regexp" "strconv" "strings" "../db" "../state" "github.com/bwmarrin/discordgo" ) const botID string = "439164276058488843" // Handles a MessageReactionAdd Discord event func MessageReactionAdd(s *discordgo.Session, m *discordgo.MessageReactionAdd) { // Ignore reactions on message...
package utils import ( "fmt" ) type Tree struct { Left *Tree Data int Right *Tree } func NewTree(v int) *Tree { return &Tree{nil, v, nil} } func InsertNodeToTree(t *Tree, v int) *Tree { if t == nil { return NewTree(v) } if v < t.Data { t.Left = InsertNodeToTree(t.Left, v) } else { t.Right = InsertN...
package qsort import "testing" func TestQuickSort1(t *testing.T) { values := [5]int {2, 3, 4, 1, 5} QuickSort(values[0:]) for i := 0; i < len(values) - 1; i++ { if values[i] > values[i+1] { t.Error("sorted1, result", values); } } } func TestQuickSort2(t *testing.T) { v...
// Copyright (C) 2017 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 t...
package main import ( "encoding/json" "fmt" "log" "net/http" "github.com/gorilla/mux" medium "github.com/medium/medium-sdk-go" "github.com/rs/cors" ) type ResponseResult struct { Code string `json:"code,omitempty"` Desc string `json:"desc,omitempty"` } var responseResult []ResponseResult type MediumRespon...
package semaphore // IPC_RMID: // Immediately remove the semaphore set and its associated semid_ds data // structure. Any processes blocked in semop() calls waiting on semaphores in // this set are immediately awakened, with semop() reporting the error EIDRM . // The arg argument is not required. //--------------- // ...
package sys import ( //"github.com/gen2brain/raylib-go/raylib" //"math/rand" ) func AllCollision(obj GameObject,list []GameObject) bool{ pre_list := &list[0] pre_obj := &obj for i := 0;i <= len(list) - 1;i++{ pre_list = &list[i] if DistanceCal(pre_list.x,pre_list.y,pre_obj.x,pre_obj.y) <= 8{ return true ...
package logger import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // NewProductionEncoderConfig returns an opinionated EncoderConfig for // production environments. func NewProductionEncoderConfig() zapcore.EncoderConfig { return zapcore.EncoderConfig{ LevelKey: "level", MessageKey: "msg", Stackt...
package api import ( "github.com/jiangmitiao/cali/app/models" "github.com/jiangmitiao/cali/app/rcali" "github.com/revel/revel" "strconv" ) type Tag struct { *revel.Controller } func (c Tag) Index() revel.Result { return c.RenderJSONP(c.Request.FormValue("callback"), models.NewOKApi()) } //all tags count func ...
package encrypt import ( "crypto" "crypto/ecdsa" "crypto/ed25519" "crypto/rand" "crypto/rsa" "errors" ) // Sign a message based on the given key. func Sign(key interface{}, message []byte) ([]byte, error) { switch key.(type) { case *rsa.PrivateKey: return signRsa(key.(*rsa.PrivateKey...
// Copyright 2015 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
/* Copyright © 2021 Author : mehtaarn000 Email : arnavm834@gmail.com */ package core import ( "bufio" "io/ioutil" "os" "ssc/utils" "strings" "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre" ) func validateBranchName(name string) bool { newmatcher, err := pcre.Compile("^(?!/|.*([/.]\\.|//|@\\{|\\\\))[^\0...
// Created by: Infinity de Guzman // Created on: May 2021 // // This program calculates your actual pay and what the government takes package main import ( "fmt" "github.com/leekchan/accounting" ) func main() { var hoursWorked float64 var hourlyRate float64 // input fmt.Println("This program gets a user's ac...
package model import ( "time" ) //Logging model for table loggings type Income struct { ID uint `gorm:"primary_key"` Username string `sql:"column:username" json:"username"` Income int `sql:"column:income" json:"income"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `sql:"index"` ...
// Copyright 2018 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package arc import ( "context" "io" "net/http" "net/http/httptest" "regexp" "time" "github.com/mafredri/cdp/protocol/target" "chromiumos/tast/common/testexec" "ch...
package datetime import ( "fmt" "github.com/project-flogo/core/data" "github.com/project-flogo/core/data/coerce" "github.com/project-flogo/core/data/expression/function" "github.com/project-flogo/core/support/log" "strings" ) // Deprecated type FormatDate struct { } func init() { function.Register(&FormatDate...
package main import ( "flag" "fmt" "github.com/astaxie/beego/httplib" "strconv" "tripod/convert" "webserver/common" "webserver/models" "webserver/models/dimension" "webserver/models/maccount" ) var Online bool var ItemName string var ItemType int var Opt int var UserId int var ItemId int func init() { flag...
package dataingest_mutation import ( "github.com/Dynatrace/dynatrace-operator/src/config" corev1 "k8s.io/api/core/v1" ) func addWorkloadInfoEnvs(container *corev1.Container, workload *workloadInfo) { container.Env = append(container.Env, corev1.EnvVar{Name: config.EnrichmentWorkloadKindEnv, Value: workload.kind}...
package types // Task struct represent a Task =] type Task struct { Text string `json:"text"` MissedWord string `json:"missed-word"` Options []string `json:"options"` }
package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { // get devuelve una url y un error si ocurre y sino lo devuelve nil res, error := http.Get("http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt") if error != nil { log.Fatalln(error) } // esto va a devolver en bs ...
package htmlparser // AttrStatus indicate a status of an attribute type AttrStatus uint8 const ( ASValid AttrStatus = iota ASDeprecated ASUnknown ) // Type of HTML Element according to the HTML 5.0 spec type HtmlElementType uint8 const ( HETPhrasing HtmlElementType = 0x1 // former "inline element" HETFlow ...
package compliancescan import ( "context" "time" "github.com/go-logr/logr" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachi...
package socks import ( "fmt" "io" "net" "strconv" ) const ( // version socks5Version = uint8(5) // commands https://tools.ietf.org/html/rfc1928#section-4 connectCommand = uint8(1) bindCommand = uint8(2) associateCommand = uint8(3) // address types ipv4Address = uint8(1) fqdnAddress = uint8(3) i...
package model import ( "strings" ) func TrySquash(runs []Cmd) []Cmd { newRuns := make([]Cmd, 0) for i := 0; i < len(runs); i++ { toSquash := []Cmd{} for j := i; j < len(runs); j++ { runJ := runs[j] if !runJ.IsShellStandardForm() { break } toSquash = append(toSquash, runJ) } if len(toSquas...
package actiontime import ( "fmt" "testing" ) func testStatsImpl(t *testing.T, csvFn string) { var obj statsImplWrap runner := testRunner{CsvFn: csvFn, Obj: &obj} t.Run(csvFn, runner.Run) } func testStats(t *testing.T, csvFn string) { var obj statsWrap runner := testRunner{CsvFn: csvFn, Obj: &obj} t.Run(csvF...
// SPDX-License-Identifier: ISC // Copyright (c) 2014-2020 Bitmark Inc. // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. // Package publish - this module handles publishing of events for add-on services // e.g. to maintain a database of transactions package publish
package Contains_Duplicate_III // similar to bucket sort func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { if t < 0 || k <= 0 || len(nums) < 2 { return false } buckets := make(map[int]int, len(nums)) for i := 0; i < len(nums); i++ { c := nums[i] if c < 0 { c -= t + 1 } key := c / (...
// Copyright 2018 The gVisor 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 2015 The Cockroach 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 ag...
package currency import ( "github.com/defaulteg/api/modules/core" "os" "encoding/csv" "bufio" "github.com/defaulteg/api/utils" "strings" ) func FetchBase() error { // Get id of elements from database for further push to it var currencyMap map[string]int var err error if currencyMap, err = core.GetElementI...
package JsRedis //哈希表,自选选DB块(0---15) //db import ( . "JsGo/JsLogger" "encoding/json" "errors" "github.com/gomodule/redigo/redis" ) //读取数据库 func Redis_hdbget(db int8, t, k string, v interface{}) error { c := g_pool.Get() if c == nil { Error("connect is nil") return errors.New("connect is nil") } c.Send("S...
package lowlevel /* #include <stdlib.h> #include <fmod.h> */ import "C" import ( "runtime" "unsafe" ) // The main object for the FMOD Low Level System. // When using FMOD Studio, this system object will be automatically instantiated as part of `StudioSystem.Initialize()`. type System struct { cptr *C.FMOD_SYSTEM }...
package user import ( "time" ) type AppUser struct { ID *string Username *string CreatedAt *time.Time UpdatedAt *time.Time passwordHash *string avatar *Avatar synced bool } func (a *AppUser) IsSynced() bool { return a.synced } func (a *AppUser) MarkSynced() { a.synced = tru...
package config import ( "github.com/go-errors/errors" "gopkg.in/yaml.v2" ) type Configuration struct { Host string `yaml:"host"` Port string `yaml:"port"` User string `yaml:"user"` Password string `yaml:"password"` Tls string `yaml:"tls"` Workers int `yaml:"workers"` } func InitConfig(f []byte) (*Configu...
package main import ( "fmt" "math" ) func main() { var r float64 fmt.Scan(&r) p := 2 * math.Pi * r s := math.Pi * r * r fmt.Printf("%f %f", s, p) }
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge...
// // 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 ...
package provider import ( "encoding/base64" "fmt" "github.com/kenlabs/pando/pkg/api/v1/model" "os" "github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/peer" "github.com/spf13/cobra" "github.com/kenlabs/pando/cmd/client/command/api" ) const registerPath = "/register" type providerInf...
/** * @website: https://vvotm.github.io * @author luowen<bigpao.luo@gmail.com> * @date 2017/12/16 10:19 * @description: */ package errhandle type AbsErrer interface { GetCode() int Error() string ErrorMsg() string } type SuperError struct { Code int `json:"code"` Message string `json:"message"` ErrMsg st...
// Copyright 2018 TriggerMesh, 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 t...
package main import ( "flag" "log" "github.com/valyala/fasthttp" ) // BAZINGA BAZINGA! const BAZINGA = "Bazinga!" var ( // version is a variable set while build to a known git branch and timestamp. version string // listener is the host:port to listen to listenAddr = flag.String("listener", ":8080", "host li...
package samplepackage import ( "testing" "github.com/stretchr/testify/assert" ) func Test_binarySearch(t *testing.T) { tests := []struct { name string array []int64 key int64 expectedValue int }{ { name: "When key present at start of an array", array: [...
package game import ( "log" "net/http" ) type Req interface { Resolve() []byte } type GameAnswer struct { Message string `json:"message"` Data interface{} `json:"data"` } func (this *Game) handleConnections(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != ni...
package runtime // A Module represents a group of Values in an Env type Module struct { // The environment in which the values are contained Env Env } // Wrap a given Env in a Module. func ModuleFrom(env Env) *Module { return &Module{env} } // Lookup a value in this module, or error if not found func (module *Mod...
package errors // ServiceError should be used to return business error message type ServiceError struct { Message string `json: "message"` }
package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "encoding/hex" "fmt" "io" "log" "os" "os/exec" "path/filepath" "strings" ) func main() { if len(os.Args) != 2 { fmt.Println("Usage: encrypt path") return } key := os.Getenv("ENCRYPTION_KEY") if key == "" { fmt.Pr...
// Copyright 2020 The Moov Authors // Use of this source code is governed by an Apache License // license that can be found in the LICENSE file. package wire import ( "encoding/json" "strings" "unicode/utf8" ) // SenderToReceiver is the remittance information type SenderToReceiver struct { // tag tag string //...
package main // I've named my bluetooth device 'Muse', so to get the muse device // to stream to port 5000, I use: // muse-io.exe --device Muse --osc osc.udp://localhost:5000 import ( "fmt" "github.com/hypebeast/go-osc/osc" "golang.org/x/net/websocket" "net/http" // "runtime" "time" ) const ( // From tes...
package translated import "github.com/stephens2424/php/passes/togo/internal/phpctx" func If(ctx phpctx.PHPContext) { if "hello" == "world" { } }
package v1 import ( kommonsv1 "github.com/flanksource/kommons/api/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +kubebuilder:object:root=true type ElasticsearchDB struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec ElasticsearchDBSpec `json:"spe...
package option var defaultAccountLevel = []int{1, 10, 100, 500} // AccountLevel is used for rank the accounts type AccountLevel struct { // account balance Threshold []int `yaml:"Threshold"` }
package tiered_cache import ( "fmt" "time" "github.com/minotar/imgd/pkg/cache" ) const MIN_RECACHE_TTL = time.Duration(1) * time.Minute type TieredCache struct { *TieredCacheConfig } type TieredCacheConfig struct { cache.CacheConfig Caches []cache.Cache } var _ cache.Cache = new(TieredCache) func NewTiered...
package config import ( "encoding/json" "io/ioutil" "log" ) var Config struct { VerifyURL string FromEmail string EmailSendingPasswd string AdminUser string Token string } func SetConfig(file string) { conf, err := ioutil.ReadFile(file) if err != nil { log.Fatalln(err.Err...
package transform import ( "encoding/json" "fmt" snapshot "github.com/pganalyze/collector/output/pganalyze_collector" "github.com/pganalyze/collector/state" uuid "github.com/satori/go.uuid" "google.golang.org/protobuf/types/known/timestamppb" ) func LogStateToLogSnapshot(server *state.Server, logState state.Tr...
package odoo import ( "fmt" ) // AccountPayment represents account.payment model. type AccountPayment struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` Amount *Float `xmlrpc:"amount,omptempty"` Communication *String `xmlrpc:"communication,omptem...
package main import ( "flag" "fmt" "net" "time" "github.com/khunafin/magazine/internal/producer" ) func main() { fmt.Println("Start client...") serverAddr := flag.String("server", ":7000", "server addr") count := flag.Int("count", 5, "message count") flag.Parse() conn, err := net.DialTimeout("tcp", *server...
package controller import ( "net/http" "strings" ) type KnownNodesRepository interface { Get() []string } type KnownNodesController struct { repository KnownNodesRepository } func NewKnownNodesController(repository KnownNodesRepository) *KnownNodesController { return &KnownNodesController{ repository: reposi...
package myloader import "github.com/mholt/caddy" func init(){ caddy.RegisterCaddyfileLoader("myloader", caddy.LoaderFunc(myLoader)) } func myLoader(serverType string)(caddy.Input, error){ return nil, nil }
package main import "fmt" func rangeBitwiseAnd(m int, n int) int { um := uint(m) un := uint(n) udiff := un - um now := uint(1) for now < udiff { now = now << 1 } return int(um & un & (^(now - 1))) } func main() { m := 0 n := 1 fmt.Println(rangeBitwiseAnd(m, n)) }
package storage import ( "errors" "fmt" "io" "path/filepath" "github.com/768bit/promethium/lib/common" "github.com/768bit/promethium/lib/images" "github.com/768bit/vutils" "github.com/gobuffalo/envy" gozfs "github.com/mistifyio/go-zfs" ) var ZFS_ROOT_PATH = envy.Get("PROMETHIUM_ZFS_ROOT_PATH", "nvmepool0/pr...
package main import ( "reflect" "testing" ) func TestDecomp(t *testing.T) { type args struct { n int } tests := []struct { name string args args want string }{ {name: "5", args: args{n: 5}, want: "2^3 * 3 * 5"}, {name: "14", args: args{n: 14}, want: "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"}, ...
// Copyright (C) 2017 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 t...
package main import "fmt" func main() { nums1 := []int{1, 2, 3, 0, 0, 0} nums2 := []int{2, 5, 6} m, n := 3, 3 merge(nums1, m, nums2, n) fmt.Println(nums1) } func merge(nums1 []int, m int, nums2 []int, n int) { // 合并后的nums1的指针 i := m + n - 1 // 分别指向两个数组最后 m-- n-- for m >= 0 && n >= 0 { if nums1[m] > nums2...
/* Name : Kamil KAPLAN Date : 25.07.2019 */ package models type Location struct { Version int32 `json:"Version,omitempty"` Key string `json:"Key,omitempty"` Type string `json:"Type,omitempty"` Ra...
package netutil import ( "math/big" "net" ) // IPAdd adds `val` to `ip`. // If `ip` is IPv4 address, the value returned is IPv4, or nil when over/underflowed. // If `ip` is IPv6 address, the value returned is IPv6, or nil when over/underflowed. func IPAdd(ip net.IP, val int64) net.IP { i := big.NewInt(val) ipv4 ...
package service import ( "database/sql" "time" "github.com/NYTimes/gizmo/config/mysql" "github.com/NYTimes/sqliface" ) type ( // SavedItemsRepo is an interface layer between // our service and our database. Abstracting these methods // out of a pure implementation helps with testing. SavedItemsRepo interface...
package main import ( "fmt" "time" ) func counter(n int, prefix string) { for i := 0; i < n; i++ { fmt.Println(prefix+":", i) time.Sleep(50 * time.Millisecond) } } func main() { counter(5, "Counter-A") go counter(5, "Counter-B") //normal function can be run asynchronously using goroutine go func(msg stri...
package pubsub import ( "time" "github.com/mylxsw/adanos-alert/internal/repository" "go.mongodb.org/mongo-driver/bson/primitive" ) // EventType 事件类型 type EventType string const ( // EventTypeAdd 新增事件 EventTypeAdd EventType = "added" // EventTypeUpdate 更新事件 EventTypeUpdate EventType = "updated" // EventTypeD...
package controller import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "github.com/nickchou/learn-go/app" ) //ZhuzherController zhuzher控制器 type ZhuzherController struct { app.App } //Project 获取zhuzher的project信息 func (con *ZhuzherController) Project() { var bf bytes.Buffer //table相关 bf.Writ...
package persistence import ( "database/sql" "github.com/Okaki030/hinagane-scraping/domain/repository" ) // wordCountPresistence はまとめ記事のワードの出現回数をカウントするための構造体 type wordCountDBPresistence struct { DB *sql.DB } // NewWordCountPersistence はwordCountPresistence型のインスタンスを生成するための関数 func NewWordCountDBPersistence(db *sql....
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package ash import ( "bytes" "context" "encoding/json" "fmt" "image" "image/png" "io/ioutil" "os" "path/filepath" "strings" "time" "chromiumos/tast/errors" "ch...
package main import ( "github.com/gorilla/mux" "log" "net/http" ) func main() { r := mux.NewRouter() r.HandleFunc("/api/select/tbluser", tbluser_All_Handler).Methods("GET") r.HandleFunc("/api/select/tbluser/{name}", tbluser_Single_Handler).Methods("GET") r.HandleFunc("/api/insert/tbluser/{name}/{age}", tbluser...
package main import "fmt" type Pill int // defining constants of the new type Pill // iota counts from 0 and increases in steps by 1 (in case you didn't know this feature) //go:generate stringer -type=Pill const ( Placebo Pill = iota Aspirin Ibuprofen Paracetamol NewPill Acetaminophen = Paracetamol // Acetamin...
/*------------------------------------------------------------------------- * * cycle_container_test.go * Test case for RingBuffer * * * Copyright (c) 2021, Alibaba Group Holding Limited * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with th...
package intset import ( "math/rand" "testing" ) func newIntSets() []IntSet { return []IntSet{NewMapIntSet(), NewBitIntSet(), NewBitInt32Set()} } func TestLenZeroInitially(t *testing.T) { for _, s := range newIntSets() { len := s.Len() if len != 0 { t.Errorf("%T.Len(): got %d, want 0", s, len) } } } fu...
/* Copyright 2021-2023 ICS-FORTH. 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 typeutils import ( "fmt" "reflect" "strings" ) const ( TypeField = "<type>" TypeFieldEscaped = "<type>" ) type FromMapFn func(from map[string]interface{}, to interface{}) error type ToMapFn func(from interface{}, to map[string]interface{}) error // Registry is the type registry interface. // A t...
package state // PostgresDatabase - A database in the PostgreSQL system, with multiple schemas and tables contained in it type PostgresDatabase struct { Oid Oid // ID of this database Name string // Database name OwnerRoleOid Oid // Owner of the database, usually the user who crea...
package purchasepersister import ( "context" "github.com/diegoholiveira/bookstore-sample/purchases" ) type ( PurchaserWithNewUser Purchaser PurchaserWithRegisteredUser Purchaser PurchaserService struct { newUser PurchaserWithNewUser registeredUser PurchaserWithRegisteredUser } ) func NewPur...
package main import "fmt" func main() { var avg = calculate(2, 4, 3, 5, 4, 3, 3, 5, 5, 3) var msg = fmt.Sprintf("Rata-rata : %.2f", avg) fmt.Println(msg) } func calculate(numbers ...int) float64 { var total int = 0 for _, number := range numbers { total += number } var avg = float64(total) / float64(len(...
package main import "fmt" // 定义全局变量字符串 var str string var str2 = "" func main() { fmt.Println(str, str2) }
// Copyright 2019 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, ...
package main import ( "testing" "github.com/maximepeschard/adventofcode2020/08_handheld/code" ) var testLines = []string{ "nop +0", "acc +1", "jmp +4", "acc +3", "jmp -3", "acc -99", "acc +1", "jmp -4", "acc +6", } func TestPart1(t *testing.T) { program, _ := code.ParseProgram(testLines) execution := c...
/* Copyright 2020 Docker Compose CLI 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 a...
package m2go type AttributeSet struct { AttributeSetID int `json:"attribute_set_id,omitempty"` AttributeSetName string `json:"attribute_set_name"` SortOrder int `json:"sort_order"` EntityTypeID int `json:"entity_type_id,omitempty"` ExtensionAttributes interfac...
package commons func AddNums(num1, num2 int) int { return num1 + num2 }
package proxy import ( "log" "net" "github.com/lflxp/goproxys/protocol" ) func RunProxy(types string) { if types == "httprp" { protocol.RunHttpProxy() } else { // cer, err := tls.LoadX509KeyPair("server.crt", "server.key") // if err != nil { // log.Fatal(err) // } // config := &tls.Config{Certifica...
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package accountmanager provides functions to manage accounts in-session. package accountmanager import ( "context" "time" "chromiumos/tast/common/action" androidui "...
package notification import ( "context" "github.com/caos/logging" sd "github.com/caos/zitadel/internal/config/systemdefaults" "github.com/caos/zitadel/internal/notification/repository/eventsourcing" "github.com/rakyll/statik/fs" _ "github.com/caos/zitadel/internal/notification/statik" ) type Config struct { R...
package main import "os" func main() { os.Chmod("/tmp/somefile", 0777) os.Chmod("/tmp/someotherfile", 0600) os.OpenFile("/tmp/thing", os.O_CREATE|os.O_WRONLY, 0666) os.OpenFile("/tmp/thing", os.O_CREATE|os.O_WRONLY, 0600) }
package main import ( "github.com/GO/Hafta2/2TwoDay/02-GO_GIN_REST_API/02/http/handler" "github.com/GO/Hafta2/2TwoDay/02-GO_GIN_REST_API/02/platform/newsfeed" "github.com/gin-gonic/gin" ) func main() { feed := newsfeed.New() r := gin.Default() // r.GET("/ping", handler.PingGet) 1 r.GET("/ping", handler.Pi...