text
stringlengths
11
4.05M
package handler import ( "net/http" "github.com/krostar/httpw" ) // NotFound handles unhandled routes. func NotFound(r *http.Request) (*httpw.R, error) { return nil, &httpw.E{Status: http.StatusNotFound} }
/* Copyright 2019 Cloudera, Inc. 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...
/* Given the length of side a of a triangle and the distances from the centroid (the point of concurrence of the medians - red in the picture) to all sides: a, b and c, calculate this triangle's area and the distance (blue line) from the orthocenter (the point of concurrence of the heights - green in the picture) to t...
package apptime import ( "log" "time" ) type Apptime struct { timeFunc func() time.Time } const TimeFormat = "2006-01-02 15:04:05" func New() *Apptime { return &Apptime{ timeFunc: time.Now, } } func (a *Apptime) Now() time.Time { return a.timeFunc() } func (a *Apptime) Set(t time.Time) { a.timeFunc = fun...
package main import ( "html/template" "net/http" //"net/url" "fmt" "path" "runtime" //"encoding/json" "log" //"strings" //"strconv" //"errors" ) const ( OkAnsver = "OK" SERVER_VERSION = "0.0.1" ) type HaderPageData struct { Version string } var currentPath string var fileserverHandler http.Handler f...
//+build integration package keyvalue_test import ( "context" "math/rand" "strconv" "sync" "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/assert" "github.com/rwool/saas-interview-challenge1/pkg/service/internal/redistest" "github.com/rwool/saas-interview-challenge1/pk...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //405. Convert a Number to Hexadecimal //Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement meth...
package main import "fmt" func main() { // 保存某个变量的地址, 需要用类型指针 *int 保存 int 的地址 var a int = 10 var p *int p = &a // 方法一 fmt.Println("a is : \n", a) fmt.Printf("p is type: %T\n", p) *p = 200 fmt.Println("a is updated to : ", a) p2 := new(int) // 方法二 但需要重要的是 需要指向什么类型的指针, 比如这里是int p2 = &a *p2 = 666 fmt.P...
package e2e import ( "context" "fmt" operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1" corev1 "k8s.io/api/core/v1" k8serror "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" utilerrors "k8s.io/apimachinery/pkg/u...
// cantainer list. // TODO: fix package main import ( "container/list" "fmt" ) func main() { l := list.New() fmt.Println("l:", l) // duplication var exl list.List exl = *l fmt.Println("exl:", exl) fmt.Printf("%p\n%p\n%p\n%+v\n%+v\n", &l, &exl, l, exl, *l) // &exl is point to entity // l e := l.PushFront...
package shared import ( "testing" ) // import ( // "ioutil" // ) // func AssertFileContent(t *testing.T, expected string, actualPath string) { // actual, err := ioutil.ReadFile(actualPath) // if err != nil { // t.Errorf("actual file %s not found", actualPath) // } // if expected != string(actual) { // t.E...
package main import "fmt" func swap(x ,y string) (string,string){ return x,y } func main(){ a,b := swap("hello","wordl") fmt.Println(a) fmt.Println(b) }
package utils import ( "fmt" "math" "math/big" ) const ( PRECISION_ONG = 9 PRECISION_ONT = 0 ) //FormatAssetAmount return asset amount multiplied by math.Pow10(precision) to raw float string //For example 1000000000123456789 => 1000000000.123456789 func FormatAssetAmount(amount uint64, precision byte) string { ...
package encrypter import ( "context" "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1" ) type EncrypterMock struct { IsError bool KeyID string KeyName string } func (e *EncrypterMock) Encrypt(ctx context.Context, key, plaintext string) (string, error) { return plaintext, nil } func (e *EncrypterMock) Enc...
package model //Category specifies the purpose of purchasing tha product type Category string const ( dividend = "DIVIDEND" value = "VALUE" fii = "FII" )
package models import ( "time" "github.com/jinzhu/gorm" ) type Comment struct { gorm.Model Text string `gorm:"size:255"` Parent *Comment Score int32 Posted time.Time Children []*Comment Post Post Hash string `gorm:"not null;unique;size:255"` }
package pkg type Data struct { X float64 Y float64 } func Hello(s string) string { switch s { case "": return "Hello you!" default: return "Hello " + s + "!" } }
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package services import ( "strconv" "github.com/andrewesteves/taskee-api/entities" "github.com/andrewesteves/taskee-api/validations" "github.com/gofiber/fiber" "github.com/jinzhu/gorm" ) // TaskService type type TaskService struct { DB *gorm.DB } // Store new resource func (t TaskService) Store(ctx *fiber.Ctx...
package fbmessenger // MessageEntryHandler functions are for handling individual interactions with a user. type MessageEntryHandler func(cb *MessagingEntry) error /* CallbackDispatcher routes each MessagingEntry included in a callback to an appropriate handler for the type of entry. Note that due to webhook batching,...
package keeper import ( "github.com/irisnet/irishub/codec" "github.com/irisnet/irishub/modules/distribution/types" "github.com/irisnet/irishub/modules/params" sdk "github.com/irisnet/irishub/types" ) // keeper of the stake store type Keeper struct { storeKey sdk.StoreKey cdc *codec.Codec paramSpace ...
package cron import ( "fmt" "testing" "time" "github.com/stretchr/testify/assert" // "time" "strconv" ) type MyType struct { val string } var isErr = true func (mt *MyType) CronRun() { isErr = false fmt.Printf("COMMAND RAN: %s", mt.val) } func TestCron(t *testing.T) { cron := NewCron() j := NewJob(&MyT...
package master import ( "fmt" "log" "net" ) var ( Address = "localhost:1234" ) func init() { Addr, err := net.ResolveTCPAddr("tcp", Address) if err != nil { log.Fatal(err) } listener, err := net.ListenTCP("tcp", Addr) if err != nil { log.Fatal(err) } defer listener.Close() for { conn, err := list...
package DCP import "fmt" func logLn(loggerDisabled bool, a ...interface{}) { if !loggerDisabled { fmt.Println(a...) } } func logf(loggerDisabled bool, format string, a ...interface{}) { if !loggerDisabled { fmt.Printf(format, a...) } }
package sdk import ( "github.com/brigadecore/brigade/sdk/v3/restmachinery" ) // APIClient is the general interface for the Brigade API. It does little more // than expose functions for obtaining more specialized clients for different // areas of concern, like User management or Project management. type APIClient int...
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package demoArchive import ( "bufio" "bytes" "encoding/hex" "fmt" "io/ioutil" "log" "os" "regexp" "strconv" "strings" "testing" ) func writeBuf() bytes.Buffer { var buf bytes.Buffer var w = bufio.NewWriter(&buf) w.WriteString("hello,") w.WriteRune('W') w.WriteByte('o') w.Write([]byte("rld!")) w.Flus...
package main import ( "fmt" "strings" ) func main() { var keys, values string var keysArr, valuesArr []string fmt.Println("CONVERT CSV TO MAP") for { fmt.Println("Input: ") fmt.Print("keys (ex:name,age)= ") _, _ = fmt.Scanln(&keys) fmt.Print("values (ex:Aang,12)= ") _, _ = fmt.Scanln(&values) keys...
package run import floc "gopkg.in/workanator/go-floc.v1" /* Unless runs the job if the condition is not met. Summary: - Run jobs in goroutines : NO - Wait all jobs finish : YES - Run order : SEQUENCE Diagram: +-------------+ | YES | --(CONDITIO...
package sheets import ( "testing" ) var posTests = []struct { pos CellPos expected string }{ {CellPos{0, 0}, "A1"}, {CellPos{1, 0}, "A2"}, {CellPos{0, 1}, "B1"}, {CellPos{1, 1}, "B2"}, {CellPos{10, 10}, "K11"}, {CellPos{0, 25}, "Z1"}, {CellPos{0, 26}, "AA1"}, {CellPos{0, 27}, "AB1"}, {CellPos{0, 52},...
package lib // PageSize is a convenience type for selecting the page size in the account List request. // To avoid using pointers for page size when the defaults are used, a special // constant PSNone can be used to omit page size from List requests. type PageSize int const ( // PSNone signals that page size should ...
package admin import ( "glsamaker/pkg/app/handler/authentication" "glsamaker/pkg/app/handler/authentication/utils" "glsamaker/pkg/database/connection" "glsamaker/pkg/models/users" "net/http" "strconv" ) // Show renders a template to show the landing page of the application func ResetPassword(w http.ResponseWrit...
// Copyright 2015 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 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 applicable law or agreed...
package main import ( "fmt" ) func q1(l int, x []int, d []bool) int { s := 0 finish := 0 for { // アリをひっくり返す for i := 0; i < len(x); i++ { p := 0 if d[i] == true { p = x[i] + 1 } else { p = x[i] - 1 } for j := i + 1; j < len(x); j++ { if p == x[j] && d[j] != d[i] { d[i] = !d[i] ...
package controllers import ( "../core" "../models" "encoding/json" "github.com/asaskevich/govalidator" "net/http" ) func LoginHandler(w http.ResponseWriter, r *http.Request) { requestUser := new(models.User) decoder := json.NewDecoder(r.Body) decoder.Decode(&requestUser) //Validating params. Refer models/us...
package handlers import ( "encoding/json" "log" "net/http" "path" "strconv" "strings" "time" "github.com/assignments-fixed-ssunni12/servers/gateway/models/users" "github.com/assignments-fixed-ssunni12/servers/gateway/sessions" ) //TODO: define HTTP handler functions as described in the //assignment descript...
// -*- Mode: Go; indent-tabs-mode: t -*- // // Copyright (C) 2018 Canonical Ltd // Copyright (C) 2018-2019 IOTech Ltd // // SPDX-License-Identifier: Apache-2.0 // Package driver this package provides a simple example implementation of // ProtocolDriver interface. // package driver import ( "fmt" "time" dsModels "...
package commandlinegenerators import ( "flag" "strings" "github.com/BrunoMCBraga/HayMaker/globalstringsproviders" ) var option *string var configFile *string var kubeconfigFile *string func PrepareCommandLineProcessing() { optionHelp := globalstringsproviders.GetOptionsMenu() option = flag.String("command", ...
/* * Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors * * SPDX-License-Identifier: Apache-2.0 * * 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://...
package flarmport import ( "bufio" "bytes" "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var testData = ` Connection closed by foreign host. @@@ Child "./ogn-decode" started at: Thu Apr 22 13:40:56 2021 @@@ 0 user(s) and 0 logger(s) connected (plus you) 0....
package main import "fmt" func main() { // divide the string into equal parts. inputString := "truetruetrue" if len(inputString)%2 != 0 { fmt.Println("false") return } split := len(inputString) / 2 splitText := inputString[:split] splitText += splitText if splitText == inputString { fmt.Println("t...
// 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 main import "fmt" func add(x, y int) int { return x + y } func returnArgs(x, y int) (int, int) { return x, y } func multi(x, y int) (z int) { z = x * y return } func pow(x, y int) (res int) { for res = 1; y > 0; y -= 1 { res *= x } return } func main() { fmt.Println(add(1, 2)) fmt.Pri...
package main import ( "fmt" "strings" ) func main() { s := "JhBkPBaozMnBqEWiIaOEje" strBuild := string(s[0]) for _, x := range s[1:] { if x >= 65 && x <= 90 { strBuild += " " //strBuild += string(x) } strBuild += string(x) } finalStr := strings.ToLower(strBuild) fmt.Println(strBuild) fmt.P...
package logger import ( "log" "os" ) var infoLog Logger var errorLog Logger type Logger interface { log() *log.Logger } type Infolog struct { Infolog *log.Logger } type Errorlog struct { Errorlog *log.Logger } func (i Infolog) log() *log.Logger { log := i.Infolog return log } func (e Errorlog) log() *log....
package entity import ( "os" "path/filepath" "runtime" ) var ( templateDir = "template" blockDir = "block" configDir = "config" peerDir = filepath.Join(configDir, "peer") OrdererDir = filepath.Join(configDir, "orderer") channelDir = filepath.Join(configDir, "channel") mspDir = filepath.Join(...
package handlers import ( "bytes" "fmt" "image" _ "image/gif" _ "image/jpeg" _ "image/png" "net/http" "path" "strings" "time" "github.com/gin-gonic/gin" "github.com/go-xweb/log" "github.com/spf13/viper" "file-upload-srv/handlers/requests" "file-upload-srv/utils/app" "file-upload-srv/utils/ffprobe" u...
package livereload import ( "sync" "github.com/gorilla/websocket" "github.com/powerman/tr/pkg/broadcast" ) // Conn implements server side of LiveReload connection. type Conn struct { ws *websocket.Conn handshake chan struct{} msgc chan interface{} shutdown chan struct{} shutdownOnce...
package realm import ( "archive/zip" "bytes" "errors" "fmt" "io/ioutil" "mime" "net/http" "github.com/10gen/realm-cli/internal/utils/api" ) const ( exportPathPattern = appPathPattern + "/export" exportQueryForSourceControl = "source_control" exportQueryIsTemplated = "template" exportQueryVersion ...
package model import "errors" //Getter interface signature type Getter interface { GetAll() []Building Get(id string) (Building, error) } //Adder interface signature type Adder interface { Add(item Building) } //Building define building data structure type Building struct { BuildingID string `json:"id"` Type ...
/* * @lc app=leetcode.cn id=66 lang=golang * * [66] 加一 */ // @lc code=start package main import "fmt" func plusOne(digits []int) []int { n := len(digits) i := n - 1 digits[i] = digits[i] + 1 for digits[i] >= 10 && i > 0 { digits[i] = digits[i] - 10 i-- digits[i]++ } if i == 0 && digits[i] >= 10 { ...
package fixtures import ( "reflect" "strconv" "strings" "testing" "time" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" "github.com/argoproj/argo/pkg/c...
package main import ( "fmt" "github.com/jolestar/go-commons-pool" "time" ) var pCommonPool *pool.ObjectPool type PoolTest struct{} func (this *PoolTest) Test() string { return "PoolTest" } func init() { // 初始化连接池配置项 PoolConfig := pool.NewDefaultPoolConfig() // 连接池最大容量设置 PoolConfig.MaxTotal = 1000 WithAban...
package api /* error转换成前端显示用语 */ import ( "database/sql" "github.com/pkg/errors" "week02/comDef" ) const ( NotFindAboutUserInfo = "没有找到相关用户信息" InputDataIsBadData = "输入信息错误" SurpriseError = "恭喜发现宝藏, 来当我测试吧" ) func ErrTranslate(err error) string { rootErr := errors.Cause(err) switch { case errors.I...
// // Copyright 2020 The AVFS 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 db import ( "strconv" "time" //"sub_account_service/app_server/protocol" "encoding/json" "sub_account_service/app_server_v2/model" "github.com/golang/glog" ) // 发布信息结构体 type PaiBan struct { Id uint "gorm:PRIMARY KEY" SubCode string `gorm:"type:text;not null` // 排班编号 Publisher str...
// Copyright 2020 Google 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
package week11 // 641. 设计循环双端队列 https://leetcode-cn.com/problems/design-circular-deque/ type MyCircularDeque struct { data []int // 指向队列头部第1个有效数据的位置; head int // 指向队列尾部的**下一个位置**,即下一个从队尾入队元素的位置。 tail int // 当前大小 size int // 容量 cap int } // NewMyCircularDeque Initialize your data structure here. Set the size...
package utils import ( "time" ) func ParseDateTimeStr(time_str string) (t time.Time,err error) { timeLayout := "2006-01-02 15:04:05" //转化所需模板 loc, _ := time.LoadLocation("Local") //重要:获取时区 t, err = time.ParseInLocation(timeLayout, time_str, loc) return }
// Copyright 2015 go-dockerclient 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 dockerutils import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io" "os" "os/exec" "path" "strings" docker "github.com/fsouza...
package template const TemplateTypeReceipt TemplateType = "receipt" type ReceiptTemplate struct { TemplateBase RecipientName string `json:"recipient_name"` Id string `json:"order_number"` Currency string `json:"currency"` PaymentMethod string `json:"pay...
package chart import ( "fmt" "io/ioutil" "os" "path" "github.com/juju/errors" "github.com/mkmik/multierror" "k8s.io/klog" "github.com/bitnami-labs/charts-syncer/api" "github.com/bitnami-labs/charts-syncer/pkg/helmcli" "github.com/bitnami-labs/charts-syncer/pkg/repo" "github.com/bitnami-labs/charts-syncer/...
package util import ( "encoding/json" "fmt" "os" "github.com/dgrijalva/jwt-go" ) var Secret = initSecret() func initSecret() []byte { return []byte(os.Getenv("SECRET")) } // GetParam ce face func GetParam(asd map[string][]string, element string) (string, error) { param := asd[element] if len(param) > 0 { ...
package go_mod_hello func SayHelloWorld() string { return "Hello World" } func SayHello(firstName string, lastName string) string { return "Hello " + firstName + " " + lastName }
/* Consider this file path: C:/Users/Martin/Desktop/BackupFiles/PC1/images/cars/new.png Your goal is to write a program that will return the file path starting from the folder after the last folder that contains a number till the filename. So, for the above file path, the program should return images/cars/new.png. O...
package config import ( "sync" "time" "golang.org/x/sync/singleflight" ) type Getter func() (string, error) type Validator func(raw string, v interface{}) error func validate(validator Validator, raw string, v interface{}) error { if validator == nil { return nil } return validator(raw, v) } type Config s...
package main import ( "eos-network/network" "fmt" "os" "os/signal" "runtime" "syscall" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) httpMgr := network.GetHttpMgr() httpMgr.Startup() connMgr := network.GetConnsMgr() connMgr.Startup() // catch system signal chSig := make(chan os.Signal) signal....
package main import ( "fmt" "github.com/jdxyw/skiplist-go" ) func main() { // If you pass the nil to `cmp` parameter, which would use the default comparactor (Bytes wise). s := skiplist.NewSkiplist(10, nil) // Use the Set to insert/update element in this list. // The `value` could be nil. s.Set([]byte("Hello"...
package problem0011 func maxArea(height []int) int { size := len(height) if size <= 1 { return 0 } i, j := 0, size-1 water := 0 for i < j { water = max(water, min(height[i], height[j])*(j-i)) if height[i] < height[j] { i++ } else { j-- } } return water } func max(a, b int) int { if a > b { ...
package gopd import ( "fmt" "net/url" "encoding/json" "bytes" ) const AUTH_URL = "https://app.pandadoc.com/oauth2/authorize?response_type=code&client_id=%s&redirect_url=%s&scope=%s" const ACCESS_TOKEN_URL = "https://api.pandadoc.com/oauth2/access_token" var credentials Credentials = Credentials{} type Auth stru...
package models import ( "bytes" "encoding/binary" ) type ResponseOk struct { ReturnCode int32 ClientID string ClientType int32 UserName string ExpiresIn int32 UserID int64 } type ResponseErr struct { ReturnCode int32 ErrorString string } type ResponseBody struct { ReturnCode int32 ErrorString...
package pipelines import "fmt" // unidirectional channel for sending only func counter(out chan<- int) { for i := 0; i < 100; i++ { out <- i } close(out) } // send only / read only func squarer(out chan<- int, in <-chan int) { for x := range in { out <- x * x } close(out) } func printer(in <-chan int) {...
package service import ( "context" "github.com/godcong/role-manager-server/config" "github.com/godcong/role-manager-server/proto" "github.com/json-iterator/go" "github.com/micro/go-micro" "github.com/micro/go-micro/registry/consul" log "github.com/sirupsen/logrus" "time" ) // GRPCServer ... type GRPCServer st...
package main import ( "fmt" ) /* 可变参数 一个函数 只能有一个可变参数 若参数列表中 还有其他类型的参数 , 则可变参数 写在所有参数的最后 */ func main_01() { sum, avg, count := GetScore(90, 50.5, 60.2, 62.9) fmt.Printf("count=%d, sum = %.2f, avg = %.2f", count, sum, avg) fmt.Println() scores := []float64{90, 50.5, 60.2, 62.9} sum, avg, count = GetS...
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "github.com/frk/gosql" ) func (q *SelectNotExistsWithFilterQuery) Exec(c gosql.Conn) error { var queryString = `SELECT NOT EXISTS(SELECT 1 FROM "test_user" AS u ` // ` filterString, params := q.Filter.ToSQL(0) queryStr...
package osbuild1 // The FSTabStageOptions describe the content of the /etc/fstab file. // // The structure of the options follows the format of /etc/fstab, except // that filesystem must be identified by their UUID and ommitted fields // are set to their defaults (if possible). type FSTabStageOptions struct { FileSys...
package entitas import "fmt" type Context interface { CreateEntity(cs ...Component) Entity // 创建entity Entities() []Entity // 获取pool创建的所有还在的entity Count() int // entity数量 HasEntity(e Entity) bool // 是否包含某个entity DestroyEntity(e Entity) // 删除entit...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //816. Ambiguous Coordinates //We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and sp...
/** * You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[...
package main /** 120. 三角形最小路径和 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。 例如,给定三角形: ``` [ [2], [3,4], [6,5,7], [4,1,8,3] ] ``` 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 说明: 如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。 */ /** 今天这道题好像以前做过了,有了思路就简单很多 *...
package ntp const ntpEpochOffset = 2208988800 const ( ntpV3 ntpVersion = iota ntpV4 ) const ( maskMode = 0xf8 maskVersion = 0xc7 maskLeap = 0x3f ) const ( modeClient = 3 ) const ( version3 = 3 version4 = 4 ) const ( leapUnknown = 3 )
package main import ( "fmt" log "github.com/sirupsen/logrus" "net/http" "runtime/debug" "strings" "time" ) type responseWriter struct { http.ResponseWriter status int wroteHeader bool header string } func wrapResponseWriter(w http.ResponseWriter) *responseWriter { return &responseWriter{Response...
package apiclient import ( "context" "google.golang.org/grpc" clusterworkflowtmplpkg "github.com/argoproj/argo/pkg/apiclient/clusterworkflowtemplate" "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1" ) type argoKubeWorkflowClusterTemplateServiceClient struct { delegate clusterworkflowtmplpkg.ClusterWorkflo...
package main import ( "fmt" "time" ) func main() { now := time.Now() // time.Time,2021-11-30 14:09:10.7117966 +0800 CST m=+0.002213001 fmt.Printf("%T,%v \n", now, now) // 获取日期 year := now.Year() month := now.Month() day := now.Day() hour := now.Hour() minute := now.Minute() second := now.Second() fmt.P...
package enigma import ( "github.com/RobinVerachtert/GoEnigma/rotor" "strings" ) type Enigma interface { Encode(text string, rotorPos string) string } type EnigmaClass struct { reflector Reflector plugboard Plugboard rotors [3]rotor.Rotor } func (e EnigmaClass) Encode(text string, rotorPos string) string { ...
package auth import ( "github.com/dgrijalva/jwt-go" "net/http" ) type ClaimHandler func(jwt.MapClaims, *http.Request, http.ResponseWriter) error func SetUserInHeaderHandler() ClaimHandler { return func(claims jwt.MapClaims, r *http.Request, w http.ResponseWriter) error { r.Header.Set("userId", claims["email"].(...
package logger import ( "os" "github.com/sirupsen/logrus" ) // Logger logs logs to stderr. This is primarily used for setting log levels // and making it easier to read them. var Logger = &logrus.Logger{ Out: os.Stderr, Formatter: new(logrus.TextFormatter), Hooks: make(logrus.LevelHooks), Level: ...
package main import ( "flag" "fmt" stdlog "log" "os" "path/filepath" "time" "github.com/3bl3gamer/tgclient" "github.com/3bl3gamer/tgclient/mtproto" "github.com/ansel1/merry" "github.com/fatih/color" ) type LogHandler struct { mtproto.ColorLogHandler ConsoleMaxLevel mtproto.LogLevel ErrorFileLoger *stdl...
package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // +k8s:openapi-gen=true // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +resource:path=vacuums // Vacuum's store the outcome of a cleaning run type Vacuum struct { metav1.TypeMeta `json:",inline"` ...
/* * @lc app=leetcode.cn id=1030 lang=golang * * [1030] 距离顺序排列矩阵单元格 */ // @lc code=start // package leetcode import ( "math" "sort" ) func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) [][]int { ret := make([][]int, rows * cols ) map_ := make(map[int][][]int) for i := 0; i < rows; i++ { f...
package game import ( "go-mod/util" "github.com/veandco/go-sdl2/sdl" ) type function func() // Update function updates the position of Ball func (b *Ball) Update(p1 *Paddle, p2 *Paddle, setStateStart function) { b.X += b.XV b.Y += b.YV if b.Y-b.Radius < 0 || b.Y+b.Radius > float32(util.WinHeight) { b.YV = -...
package cloud import ( "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config/versions/latest" "github.com/pkg/errors" ) // DeleteKubeContext removes the specified space from the kube context and providers.yaml func (p *provider) DeleteKubeContext(space *latest.Space) error { kubeContext := GetKubeContextNa...
// For problem background, go to: // http://rosalind.info/problems/hamm/ package main import ( "bufio" "os" ) func readFile(lineNumber int) string { f, _ := os.Open("test.txt") scanner := bufio.NewScanner(f) var line string i := 0 for scanner.Scan() { if i == lineNumber { line = scanner.Text() break ...
package mgopool import ( "testing" "time" mgo "github.com/globalsign/mgo" "github.com/stretchr/testify/assert" ) func TestCapped_Get(t *testing.T) { orig := session(t) defer orig.Close() p := NewCapped(orig, 1) defer p.Close() expected := p.Get() var actual *mgo.Session done := make(chan struct{}) go ...
package main import ( "fmt" "io/ioutil" "os" "strings" ) func main() { fmt.Println("You input: ") if len(os.Args) < 2 { fmt.Println("Missing input file parameter.") return } data, error := ioutil.ReadFile(os.Args[1]) if error != nil { fmt.Println("Can't read file: ", os.Args[1]) panic(error) } set ...
package collections // WorkWith is the struct we'll // be implementing collections for type WorkWith struct { Data string Version int } // Filter is a functional filter. It takes a list of // WorkWith and a WorkWith Function that returns a bool // for each "true" element we return it to the resultant // list fun...
// Copyright 2015-2018 trivago N.V. // // 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 ...
/* * MIT License * * Copyright (c) 2020 Tom Greasley * * 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, mod...
package tracer import ( "contrib.go.opencensus.io/exporter/jaeger" "go.opencensus.io/trace" ) const ( probabilitySampler = 1.0 ) func New(collectorEndpoint, serviceName string) error { je, err := jaeger.NewExporter(jaeger.Options{ CollectorEndpoint: collectorEndpoint, Process: jaeger.Process{ ServiceName...