text
stringlengths
11
4.05M
/* Create a function that takes a string and returns a new string with each new character accumulating by +1. Separate each set with a dash. Examples accum("abcd") ➞ "A-Bb-Ccc-Dddd" accum("RqaEzty") ➞ "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" accum("cwAt") ➞ "C-Ww-Aaa-Tttt" Notes Capitalize the first letter of eac...
package main import ( "fmt" "listing74/entities" ) func main() { a := entities.Admin{Rights: 10} a.Name = "Bill" a.Email = "bill@email.com" fmt.Printf("사용자: %v\n", a) }
package main import ( "fmt" "log" "os" "time" "gopl.io/ch4/github" ) func timeSince(date time.Time) string { MONTH, _ := time.ParseDuration(fmt.Sprintf("%dh", 24*30)) YEAR, _ := time.ParseDuration(fmt.Sprintf("%dh", 24*365)) since := time.Since(date) if since <= MONTH { return "less than a month" } els...
package generateParenthesis import "fmt" func generateParenthesis(n int) []string { res := []string{} if n <= 0 { return res } generate("", 0, 0, n, &res) return res } func generate(s string, left, right, n int, res *[]string) { if right >= n { *res = append(*res, s) return } if left >= n { for i := ...
package leetcode /*Let's call an array A a mountain if the following properties hold: A.length >= 3 There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A...
package backend import ( "sync" "testing" "time" "github.com/square/beancounter/deriver" . "github.com/square/beancounter/utils" "github.com/stretchr/testify/assert" ) func TestNonExistantFixtureFile(t *testing.T) { b, err := NewFixtureBackend("testdata/badpath") assert.Nil(t, b) assert.Error(t, err) } fun...
package main import ( "flag" "log" "net/http" "os" "path" "time" "github.com/gorilla/handlers" "github.com/ProjectBorealis/ArcticAnalyticsServer/server" ) const ( sharedSecretEnv = "SHARED_SECRET" adminPasswordEnv = "ADMIN_PASSWORD" ) var ( behindProxy = flag.Bool("behind-proxy", false, "whether server ...
func largeGroupPositions(S string) [][]int { s, e := 0, 0 res := [][]int{} for e < len(S) { if S[e] != S[s] { if e-s >= 3 { res = append(res, []int{s, e - 1}) } s = e } e++ } if e-s>=3{ res = append(res,[]int{s,e-1}) } return res }
/* Copyright (c) 2017-2018 Simon Schmidt 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, publish, distribu...
package scalars import ( "bytes" "fmt" "strconv" "time" ) // Value struct contains a single scalar value type Value struct { //wall_time, step, value WallTime time.Time Step int Value float64 } // MarshalJSON marshal to Tensorboard scalar format func (sv *Value) MarshalJSON() ([]byte, error) { b := b...
package main import ( "testing" ) func TestNew(t *testing.T) { color, _ := NewHexColor("aB1FE0") if color.GetCode() != "ab1fe0" { t.Fatalf("NewHexColor: expected initialized code to be lower case, got %s", color.GetCode()) } } func TestVerify(t *testing.T) { if _, errs := NewHexColor("012"); errs != nil { ...
package core import ( "er" "fwb" "sgs" "sort" ) func pgfInit(me *gameImp) *er.Err { me.lg.Dbg("Enter Game Finish phase") playerRematch := make(map[int]bool) me.pd = &playerRematch gameRank := makeGameRank(me) me.setDCE(fwb.CMD_REMATCH, pgfOnRematch) me.setTimer(10000, pgfOnTimeOut) printRank(me, gameRa...
package seccomp import ( "testing" specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pjbgf/go-test/should" ) func TestGetSystemCalls_FromTemplate(t *testing.T) { assertThat := func(assumption string, name ProfileTemplate, expected *specs.LinuxSyscall, expectedErr error) { should := should....
package todo import ( "net/http" ) type Transport interface { CreateItem(w http.ResponseWriter, r *http.Request) GetAllItems(w http.ResponseWriter, r *http.Request) GetItem(w http.ResponseWriter, r *http.Request) UpdateItem(w http.ResponseWriter, r *http.Request) DeleteItem(w http.ResponseWriter, r *http.Reques...
package rpmmd import ( "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "sort" "strconv" "strings" "time" "github.com/gobwas/glob" ) type repository struct { Name string `json:"name"` BaseURL string `json:"baseurl,omitempty"` Metalink string `json:"metalink,...
package main import ( "fmt" prose "gopkg.in/jdkato/prose.v2" ) func main() { text := "European authorities fined Google a record $5.1 billion on Wednesday for abusing its power in the mobile phone market and ordered the company to alter its practices" fmt.Println("Text:", text) // The document-creation process...
package post import ( "github.com/pkg/errors" "net/http" "github.com/go-playground/validator" "github.com/labstack/echo" "github.com/hofstadter-io/examples/blog/lib/types" // HOFSTADTER_START import // HOFSTADTER_END import ) /* API: server Name: post Route: post Resource: type.lib.types.Po...
package models import ( "time" ) type Transfer struct { Id int64 `xorm:"pk autoincr"` NodeId string `xorm:"varchar(255) notnull unique"` RxTotalBytes uint64 `xorm:"default(0)"` RxMaxBitrate uint64 `xorm:"default(0)"` RxMinBitrate uint64 `xorm:"default(0)"` RxAvgBitrate uint64 ...
package sand type browserUser struct { Email string `json:"email"` RefreshToken string `json:"refresh_token"` SheetID string `json:"sheet_id"` Session string `json:"session"` } //TODO update GSheet when Exits //Recover from GSheet to Start Server //Update Local Database //Recover from local Da...
package peerstore import ( "fmt" "sync" peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer" ) var _ Peerstore = (*peerstore)(nil) type peerstore struct { Metrics KeyBook AddrBook PeerMetadata // lock for protocol information, separate from datastore lock protolock sync.Mutex } /...
package servecmd import ( "os" "os/signal" "syscall" "github.com/UnnecessaryRain/ironway-core/pkg/mud/game" "github.com/UnnecessaryRain/ironway-core/pkg/mud/interpreter" "github.com/UnnecessaryRain/ironway-core/pkg/network/client" "github.com/UnnecessaryRain/ironway-core/pkg/network/server" log "github.com/s...
package deposits import ( "Pinjem/businesses/deposits" "context" "time" "gorm.io/gorm" ) type DepositRepository struct { Conn *gorm.DB } func NewDepositRepository(conn *gorm.DB) deposits.DomainRepository { return &DepositRepository{Conn: conn} } func (d *DepositRepository) GetAll(ctx context.Context) ([]depo...
/* SPDX-License-Identifier: Apache-2.0 Copyright Contributors to the Submariner project. 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...
package docker import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" "golang.org/x/net/context" "log" ) var cli *client.Client func init() { var err error cli, err = client.NewClientWithOpts(client.WithVersion("1.39")) if err != nil { log.Fatal("New Client failed.") } } func Serv...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-14 10:01 # @File : lt_74_search-a-2d-matrix.go # @Description : 在二叉树矩阵中查询一个数 # @Attention : 将二维数组转为一维数组即可 注意,在获取中间值的时候,使用的是 matrix[mid/cols][mid%cols] 列的值 */ package half func searchMatrix(matrix [][]int, target int) bool { if len(matrix)==0 || len(ma...
package main import ( "github.com/chenxin0723/asics_footer_parser/asics_parser" ) func main() { asics_parser.WirteDir = "./asics_parser/" asics_parser.ParseECHtml("http://www.asics.com/us/en-us/") }
/* Copyright © 2021 SUSE LLC 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 dist...
package frida_go type FrontmostQueryOptions struct { Scope FridaScope }
package main import ( "fmt" "math" "os" "strings" "time" "io" "image" "image/color" "sync" "math/rand" "golang.org/x/tour/pic" "golang.org/x/tour/reader" "golang.org/x/tour/tree" "golang.org/x/tour/wc" ) //Concurrent Pattern: func that returns a channel func boring(msg string) <-chan string { //re...
// Copyright 2021 Clivern. All rights reserved. // Use of this source code is governed by the MIT // license that can be found in the LICENSE file. package cmd import ( "bytes" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "strconv" "strings" "github.com/clivern/peanut/core/controller" "github.co...
package order_handler //******** //Have a routine to receive local button pushes. If they are cab calls they are handled in the package. Hall calls are transmitted to all elevators. //******** import ( "fmt" "time" elevio "../elev_driver" network "../network_module" slog "../sessionlog" statemachine "../stateM...
package core import ( "net/http" "github.com/gin-gonic/gin" ) // addBlockLikes godoc // @Summary Add a like // @Description Adds a like to a thread block // @Tags blocks // @Produce application/json // @Param id path string true "block id" // @Success 201 {object} pb.Like "like" // @Failure 400 {string} string "Ba...
package cloudmessage import ( "github.com/qor/transition" "github.com/satori/go.uuid" "github.com/tppgit/we_service/entity/order" "github.com/tppgit/we_service/entity/user" "time" ) type MobilePlatformType int const ( iOS = MobilePlatformType(1) Android = MobilePlatformType(2) ) type NotificationType int...
package classify import ( "testing" ) func TestClassifyValid(t *testing.T) { oc(t, "Hello, world!", true) oc(t, `"We've got a lot of work to do," McCabe said.`, true) oc(t, `Tigers general manager Al Avila today said that no decision has been made.`, true) } func TestClassifyTrailingLines(t *testing.T) { oc(t, ...
package main import "fmt" func main() { ss := Constructor() fmt.Println(ss.Next(100)) fmt.Println(ss.Next(80)) fmt.Println(ss.Next(60)) fmt.Println(ss.Next(70)) fmt.Println(ss.Next(60)) fmt.Println(ss.Next(75)) fmt.Println(ss.Next(85)) } type StockSpanner struct { st [][2]int cur int } func Constructor...
package main import ( "fmt" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter3/currency" ) func main() { // start with our user input // of fifteen dollars and 93 cents userInput := "15.93" pennies, err := currency.ConvertStringDollarsToPennies(userInput) if err != nil { panic(err)...
package gonba import ( "fmt" "time" ) const endpointPlayByPlayV2 = "v1/%s/%s_pbp_%d.json" const playbyplayV2DateFormat = "20060102" func (c *Client) GetPlayByPlayV2(gameDate time.Time, gameId string, periods ...int) (PlayByPlayV2, int) { params := map[string]string {"version": "3"} dateString := gameDate.Format(...
package TDUBus import ( "fmt" "testing" ) func TestGetTimeSchedyle(t *testing.T) { timetable := GetTimeSchedules() fmt.Println(timetable[2].Down.Takasaka["10"]) } func TestNext(t *testing.T) { B := Cli{} result, vacation := B.NextDown("takasaka") fmt.Println(result, vacation) }
package component import ( "github.com/Azer0s/quacktors" "github.com/gofrs/uuid" ) type actorPidTuple struct { name string pid *quacktors.Pid } type dynamicSupervisorComponent struct { supervisor quacktors.Actor supervisorPid *quacktors.Pid actorPids []*quacktors.Pid mapping []actorPidTuple } ...
package controllers import ( "encoding/json" "fmt" "github.com/mikerjacobi/poker/server/models" ) func CheckStartHoldem(game models.Game) error { if len(game.Players) < 2 { return fmt.Errorf("holdem: too few players") } gameJSON, err := json.Marshal(game) if err != nil { return fmt.Errorf("holdem: jsonmars...
package main import ( "fmt" "os" "strings" "time" ) func main() { start := time.Now() fmt.Println("start:", start) var s string for i := 1; i < len(os.Args); i++ { s += os.Args[i] } s = "" fmt.Printf("end: %.3fs", time.Since(start).Seconds()) fmt.Println("\n----------------------------------------------...
package models import ( "time" "github.com/jungju/circle_manager/modules" ) var _ = time.Time{} // gen:qs type KeyEvent struct { ID uint `description:""` CreatedAt time.Time `description:"등록일"` UpdatedAt time.Time `description:"수정일"` Name string `description:"이름"` Description stri...
package moitessier import ( "github.com/likestripes/kolkata" "github.com/likestripes/pacific" ) const ( Shared = 1000 Private = 1001 Handler = 1002 ) func Dispatch(context *pacific.Context, person *kolkata.Person, scope, text string, args...interface{}) ([]interface{}, []Listener, error) { message := Message...
package main import ( "bytes" "context" "encoding/json" "flag" "fmt" "html/template" "io/ioutil" "log" "os" "path" "path/filepath" "strings" ui "github.com/gizak/termui/v3" Boot "github.com/u-root/u-root/pkg/boot" "github.com/u-root/u-root/pkg/mount" "github.com/u-root/u-root/pkg/mount/block" "github...
/* Copyright 2021 RadonDB. 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 distri...
package sol func search(nums []int, target int) int { if len(nums) == 0 { return -1 } if nums[0] == target { return 0 } size := len(nums) - 1 i, j := 0, size for i <= j { m := (i + j) / 2 if nums[m] == target { return m } // sorted if nums[i] <= nums[m] { if nums[i] <= target && target ...
/* Links * http://ysugonuf.github.com/1.html * http://ysugonuf.github.com/2.html * http://ysugonuf.github.com/3.html * http://ysugonuf.github.com/4.html * http://ysugonuf.github.com/5.html * http://ysugonuf.github.com/6.html * http://ysugonuf.github.com/7.html * http://ysugonuf.github.com/8.html * http://ysugonuf.githu...
package main import "fmt" func RequestAutoScout24(config conf) []string { fmt.Println("Checking autoscout24 ...") results := []string{"www.autoscout24.de/0", "www.autoscout24.de/1"} return results }
package main import ( "bytes" "errors" "flag" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "path" "path/filepath" "strings" "time" "moul.io/http2curl" ) const ( version = "0.9.5" ) func init() { flag.Usage = func() { h := "Usage:\n" h += " bozr [OPTIONS] (DIR|FILE)\n\n" h += "Options:\n...
package main import "fmt" // Interface kosong adalah interface yang tidak memiliki deklarasi method satupun, hal ini membuat secara otomatis semua tipe data akan menjadi implementasinya // Interface kosong biasa digunakan untuk menampung tipe data yg dynamic /*cara membuat interface kosong -> interface{} atau sama d...
package server import "cloud.google.com/go/logging" // Create a generic interface that allows logging measurement type Measurement interface { Log(name string, timeMillis int64) // log a measurement } // a model that represents a single measurement type MeasurementModel struct { Name string // a name to identify t...
package main import "fmt" type N int func main() { var n N = 5 n.test() n.test1() } func (N) test() { fmt.Println("test...") } func (n N) test1() { fmt.Println(n) }
// Generated from AdlWo.g4 by ANTLR 4.7. package adlwo // AdlWo // See base listener file for example implementations //import "github.com/wxio/goantlr" // import "generate package" //type AdlWoVisitor struct { // *antlr.BaseParseTreeVisitor // indent string //} //var _ antlr.ParseTreeVisitor = &AdlWoVisitor...
package refImpl_test import ( "testing" authConfig "github.com/go-ocf/cloud/authorization/service" authService "github.com/go-ocf/cloud/authorization/test/service" "github.com/go-ocf/cloud/grpc-gateway/refImpl" "github.com/kelseyhightower/envconfig" "github.com/stretchr/testify/require" ) func TestInit(t *test...
package db import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" _ "github.com/jinzhu/gorm/dialects/sqlite" _ "github.com/lib/pq" "github.com/naughtydevelopment/todo-go/config" "os" ) var db *gorm.DB var err error func Init() { c := config.GetConfig() user := c.GetString("db....
package enum type DataChnID int const ( DataChnID_APP_STORE DataChnID = 1 // 软件商店 DataChnID_NOT_APP_STORE DataChnID = 2 // 非软件商店 DataChnID_UNION DataChnID = 3 // 联盟 )
package db func (B *dbImpl) RetrieveQuestionAnswers(channel string) ([]QuestionAnswer, error) { rows, err := B.db.Query("SELECT id, channel, question, answer FROM questions WHERE channel=$1", channel) if err != nil { return nil, err } defer rows.Close() var ch, question, answer string var id int qas := []Qu...
package main import ( "fmt" "net/http" "net/url" goemon "github.com/gentom/goemon" ) func main() { api := goemon.New() api.GET("/", root) api.GET("/hello", hello) api.GET("/langs/:lang", programmingLangs) api.GET("/langs/:lang/framework", framework) api.Start(5000) } func root(w http.ResponseWriter, r *ht...
package humanity import ( "SoftwareGoDay1/Day1/data" "errors" "fmt" "strconv" ) type Human struct { Name string Age int Country string } func NewHumanFromCSV(csv []string) (*Human, error) { newage, err := strconv.Atoi(csv[1]) if err != nil { return nil, errors.New("age is not an int") } h := Huma...
package main import "fmt" import "sync" var wg sync.WaitGroup func main() { wg.Add(2) // means that we add 2 items tot he WaaitGroup go foo() go bar() wg.Wait() // we wait to the WaitGroup to get to 0 } func foo() { for i := 0; i < 45; i++ { fmt.Println("Foo:\t", i) } wg.Done() // "says done and take one...
// Copyright (c) 2020 Blockwatch Data Inc. // Author: alex@blockwatch.cc package index import ( "context" "errors" "github.com/jinzhu/gorm" "github.com/zyjblockchain/sandy_log/log" "tezos_index/puller/models" ) const ( SnapshotPackSizeLog2 = 15 // =32k packs SnapshotJournalSizeLog2 = 17 // =128k entries S...
package main import ( "bytes" "github.com/gin-gonic/gin" "io/ioutil" "net/http" ) func main(){ r:=gin.Default() r.POST("/test", func(context *gin.Context) { bodyBytes, err := ioutil.ReadAll(context.Request.Body) if err!=nil { context.String(http.StatusBadRequest, err.Error()) context.Abort() } /...
package main import ( "encoding/binary" "github.com/golang/protobuf/proto" ) type NetMsg struct { t uint32 session uint32 data []byte } func (m *NetMsg) getMsgType() int { return MSG_NET } func packMsg(m *NetMsg) []byte { l := len(m.data) + 8 pack := make([]byte, l) binary.BigEndian.PutUint32(pack...
// Binary tpm2-ekcert reads an x509 certificate from a specific NVRAM index. package main import ( "crypto/x509" "flag" "fmt" "io/ioutil" "os" "github.com/google/go-tpm/tpm2" "github.com/google/go-tpm/tpmutil" ) var ( tpmPath = flag.String("tpm-path", "/dev/tpm0", "Path to the TPM device (character device or...
package upstream_notify import ( "github.com/tal-tech/go-zero/rest/httpx" "net/http" "tpay_backend/payapi/internal/common" logic "tpay_backend/payapi/internal/logic/upstream_notify" "tpay_backend/payapi/internal/svc" "github.com/tal-tech/go-zero/core/logx" ) func XPayPayHandler(ctx *svc.ServiceContext) http.H...
package main import ( "encoding/json" "errors" "os" ) type configRoot struct { HTTP configHTTP `json:"http"` Streams []configStream `json:"streams"` } type configHTTP struct { Listen string `json:"listen"` } //go:generate stringer -type configStreamKind config.go type configStream struct { Description...
package config import ( "fmt" "io/ioutil" "strings" "time" "github.com/caarlos0/env/v6" "gopkg.in/yaml.v3" ) type Config struct { Debug Debug Year int `env:"PLANNER_YEAR"` WeekStart time.Weekday ClearTopRightCorner bool AMPMTime bool Pages Pages Layout Layout } ty...
package slack type channelMembersResponse struct { OK bool `json:"ok"` Members []string `json:"members"` Err string `json:"error,omitempty"` } type userRespsone struct { OK bool `json:"ok"` User slackUser `json:"user"` Err string `json:"error,omitempty"` } type slackUser struct { Nam...
package ch01 // Given and array of 0s, 1s, and 2s. When need to stort it so that all the 0s are before all the 1s and all the 1s are before 2s. // Hint: same ass above first think of 0s and 1s as one groupd and move all the 2s on the right side. Then do a second pass over the array to sort 0s and 1s. func Sort_0_1_2(i...
package main import ( "fmt" "sync" ) var bold_red = "\x1B[1;31m" var bold_purple = "\x1B[1;35m" var bold_blue = "\x1B[1;34m" var reset_color = "\x1B[0m" type logger struct { mux *sync.Mutex } func new_logger() *logger { return &logger{&sync.Mutex{}} } func (l *logger) ok(format string, a ...interface{}) (int, ...
package cloudflare import ( "context" "encoding/json" "fmt" "net/http" "time" ) // AccessApplicationType represents the application type. type AccessApplicationType string // These constants represent all valid application types. const ( SelfHosted AccessApplicationType = "self_hosted" SSH AccessAppl...
/* main function */ /* file name: db_action.go */ /* link: */ /* */ /* update: 20181122 */ package database import ( //"fmt" "encoding/base64" "fmt" "log" "loranet20181205/exception" "strconv" _ "github.com/go-sql-driver/mysql" //"encoding/hex" //"n...
package config const ( OperatorName string = "splunk-forwarder-operator" OperatorNamespace string = "openshift-splunk-forwarder-operator" SplunkAuthSecretName string = "splunk-auth" // #nosec G101 -- This is a false positive )
package models import ( "time" "github.com/astaxie/beego/orm" ) /*SysFriends 好友请求表信息 */ type SysFriendsAsk struct { Id int `orm:"auto" json:"id" required:"false" description:"好友关系id"` SourceUid int `json:"sourceUid" required:"false" description:"源用户id"` TargetUid int `json:"targetUid...
package generator import ( "errors" "reflect" "text/template" ) // ErrSliceElementIsPtr indicates that the element is a pointer type var ErrSliceElementIsPtr = errors.New("slice element can't be a pointer") type sliceType struct { Name string Type string ReturnType string Complex bool Comp...
package workqueue import ( "time" ) func (q *QueueWatcherConfig) CopyFrom(other *QueueWatcherConfig) { q.CheckInterval = other.CheckInterval q.MaxRetryJobChecks = other.MaxRetryJobChecks q.FileSystemName = other.FileSystemName q.Namespace = other.Namespace q.RunID = other.RunID q.SnapshotName = other.Snapsho...
package gorequests import ( "io" "os" "testing" "github.com/fvbock/gorequests" ) var ( requestbinURL = "http://requestb.in/106jnln1" ) func TestGet(t *testing.T) { url := requestbinURL r := gorequests.Get(url, nil, nil, -1) if r.Error != nil { t.Fail() t.Log(r.Error) } t.Log(r.Request.Params()) t.Log...
package humanize import "go/ast" // IdentType is the normal type name type IdentType struct { pkg *Package Ident string } func (i *IdentType) String() string { return i.Ident } // Package get the package of ident func (i *IdentType) Package() *Package { return i.pkg } // Equal check if two ident are equal fu...
/* Copyright 2022 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...
// +build arm,linux /* * Copyright 2017 StreamSets 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 app...
// Package privileges provides all of the tools needed to implement *nix style // file permissions in an application, user and group database and all. package privileges import "database/sql" // Privileged provides an interface that can be implemented by any object to be // automatically tied to the privileges system...
/* Package riak is a riak-client, inspired by the Ruby riak-client gem and the riakpbc go package from mrb. It implements a connection to Riak using protobuf. */ package riak import ( "errors" "fmt" "io" "net" "sync" "time" "code.google.com/p/goprotobuf/proto" "github.com/cupcake/go-riak/pb" ) /* To generate...
package main /* 函数作为类型传递案例 */ import ( "fmt" ) func isOdd(value int) bool{ if value%2 == 0{ return false } return true } func isEven(value int) bool{ if value%2 == 0{ return true } return false } type boolFunc func(int) bool func filter(slice []int,ff boolFunc) []int{ var result []int for _,value :...
package m3u8 import ( "fmt" "log" "testing" "time" ) //func onGeneratorError(gen *M3u8Generator, err error) { // log.Printf("%s error: %s", gen.m3u8FullName, err.Error()) //} //func onM3u8Generated(m3u8FullName string, tsArray []*Ts) { // str := m3u8FullName + " with: " // for _, ts := range tsArray { // str +=...
package main import ( "fmt" ) func main() { // Here we create a multi-dimensional array, a 3x4 matrix (3 rows, 4 columns) myMatrix := [3][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} // Let's print a value from a cell in each row of hte matrix fmt.Println("Value at [0][0]: ", myMatrix[0][0]) fmt.Println...
package _interface import ( "context" "github.com/golang/protobuf/ptypes/empty" pb "github.com/muhammadisa/vanilla-microservice/protobuf" ) type TodoService interface { CreateTodo(ctx context.Context, todo *pb.Todo) (*empty.Empty, error) RetrieveTodos(ctx context.Context, blank *empty.Empty) (*pb.Todos, error) }...
// Copyright 2019 GoAdmin Core Team. All rights reserved. // Use of this source code is governed by a Apache-2.0 style // license that can be found in the LICENSE file. package language import ( "html/template" "strings" "github.com/GoAdminGroup/go-admin/modules/config" "golang.org/x/text/language" ) var ( EN ...
package phys import ( "fmt" "math" "github.com/tanema/amore/gfx" ) type World struct { width float32 height float32 cell_width float32 cell_height float32 numWidth float32 numHeight float32 grid [][]*Cell } func NewWorld(width, height, cell_size float32) *World { cell_width := nex...
package datetime import "time" const ( Day = time.Hour * 24 Week = Day * 7 ) // BeginOfThisWeek returns 00:00:00 of this Monday. func BeginOfThisWeek(ts time.Time) time.Time { offset := int(time.Monday - ts.Weekday()) if offset > 0 { offset = -6 } ts = ts.AddDate(0, 0, offset) return time.Date(ts.Year(), t...
package filter import ( "bufio" "context" "io" "net" "regexp" "strings" "github.com/coredns/coredns/plugin" "github.com/miekg/dns" "github.com/sirupsen/logrus" ) var fqdnRegex = regexp.MustCompile(`(\w+)\.\w+\.?$`) type Filter struct { Next plugin.Handler Blacklist map[string]bool log *logrus...
package global import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" "log" "os" ) func Init() { var err error File, err = os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) if err != nil { log.Fatal(err) } InfoLog...
package spotty import ( "github.com/zmb3/spotify" "log" "fmt" ) func SearchTrack( authorName string, trackName string, ) (spotify.FullTrack, bool) { var track spotify.FullTrack searchQuery := authorName + " " + trackName results, err := client.Search(searchQuery, spotify.SearchTypeTrac...
/* In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index va...
package function import ( "encoding/json" "testing" ) func Test_Handle(t *testing.T) { res := Handle([]byte("test1234")) result := result{} err := json.Unmarshal([]byte(res), &result) if err != nil { t.Errorf("unable to unmarshal response, error: %s", err) t.Fail() } if result.Found == 0 { t.Errorf("e...
package install import ( "fmt" "strconv" "time" log "github.com/sirupsen/logrus" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "github.co...
package main type ItemOwner struct { Reputation int `json:"reputation"` UserId int `json:"user_id"` UserType string `json:"user_type"` ProfileImage string `json:"profile_image"` DisplayName string `json:"display_name"` Link string `json:"link"` } type SearchItem struct { Tags ...
package main import ( "net/http" _ "fmt" ) func simple(w http.ResponseWriter, r *http.Request){ w.Write([]byte("Recieved on "+r.Host)) } func main(){ go func(){http.ListenAndServe(":50001",http.HandlerFunc(simple))}() go func(){http.ListenAndServe(":50002",http.HandlerFunc(simple))}() go func(){http.ListenAnd...
package pathrename type Flag uint8 const ( UFile Flag = 1 << iota HFile UDirectory HDirectory URecursive HRecursive Override ) func GetFlag() Flag { return 0 }
// Copyright 2014 The Sporting Exchange Limited. All rights reserved. // Use of this source code is governed by a free license that can be // found in the LICENSE file. // Package forwarder forwards events to the aggregator. package forwarder import ( "expvar" "time" "opentsp.org/cmd/collect-statse/aggregator" "...
package dbhandlers import ( "technodb-final/app/db" "technodb-final/app/models" ) func Status() (*models.Status, error) { var status models.Status if err := db.Database.QueryRow("Stats").Scan( &status.Post, &status.Thread, &status.User, &status.Forum); err != nil { return nil, err } return &status, ni...