text stringlengths 11 4.05M |
|---|
package main
import log "github.com/junwangustc/ustclog"
type Service interface {
Open() error
Close() error
}
type Server struct {
services []Service
cfg *Config
}
func (s *Server) Open() error {
if err := func() error {
for _, service := range s.services {
log.Println("start Opening service %T", service)
if err := service.Open(); err != nil {
return err
}
log.Println("opened Service %T:%s", service)
}
return nil
}(); err != nil {
s.Close()
return err
}
return nil
}
func (s *Server) Close() {
for _, service := range s.services {
log.Printf("D! closing service: %T", service)
err := service.Close()
if err != nil {
log.Printf("E! error closing service %T: %v", service, err)
}
log.Printf("D! closed service: %T", service)
}
}
func NewServer(cfg *Config) (srv *Server) {
srv = &Server{cfg: cfg}
return srv
}
func (s *Server) Run() (err error) {
if err = s.Open(); err != nil {
log.Println("[Error]open server fail", err)
return err
}
return nil
}
|
package color
import "math"
func Lighten(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.L += v
hsl.L = clamp(hsl.L)
return hsl.RGB()
}
func Darken(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.L -= v
hsl.L = clamp(hsl.L)
return hsl.RGB()
}
func Saturate(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.S += v
hsl.S = clamp(hsl.S)
return hsl.RGB()
}
func Desaturate(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.S -= v
hsl.S = clamp(hsl.S)
return hsl.RGB()
}
func FadeIn(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.A += v
hsl.A = clamp(hsl.A)
return hsl.RGB()
}
func FadeOut(c RGBA, v float64) RGBA {
hsl := c.HSL()
hsl.A -= v
hsl.A = clamp(hsl.A)
return hsl.RGB()
}
// Change hue of color by v centi-degrees (0-3.6)
func Spin(c RGBA, v float64) RGBA {
hsl := c.HSL()
v *= 100
hsl.H += v
if hsl.H < 0 {
hsl.H += 360
} else if hsl.H > 360 {
hsl.H -= 360
}
return hsl.RGB()
}
func Multiply(c RGBA, v float64) RGBA {
c.R = clamp(c.R * v)
c.G = clamp(c.G * v)
c.B = clamp(c.B * v)
return c
}
func Mix(c1, c2 RGBA, weight float64) RGBA {
w := weight*2 - 1
a := c1.A - c2.A
var w1 float64
if w*a == -1 {
w1 = (w + 1) / 2.0
} else {
w1 = ((w+a)/(1+w*a) + 1) / 2.0
}
w2 := 1 - w1
return RGBA{
R: c1.R*w1 + c2.R*w2,
G: c1.G*w1 + c2.G*w2,
B: c1.B*w1 + c2.B*w2,
A: c1.A*weight + c2.A*(1-weight),
}
}
func SetHue(c, hue RGBA) RGBA {
base := c.HuSL()
base.H = hue.HuSL().H
return base.RGB()
}
func clamp(v float64) float64 {
return math.Max(math.Min(v, 1.0), 0.0)
}
|
package shooting
type Component struct {
Cooldown uint
// ticks to armed
tta uint
BulletForce float64
BulletDamage float64
BulletLifetime uint
}
func (c Component) Armed() bool {
return c.tta == 0
}
type Controls struct {
Shooting bool
}
type Controller chan Controls
|
package generic
import "github.com/iotaledger/hive.go/objectstorage"
type StorableObjectFlags = objectstorage.StorableObjectFlags
|
package main
import (
"os"
"fmt"
"log"
"net"
"time"
"os/signal"
"io/ioutil"
"hash/crc32"
"encoding/binary"
)
func asyncAccept(listener *net.UnixListener) <-chan *net.UnixConn {
ch := make(chan *net.UnixConn)
go func() {
for {
conn, err := listener.AcceptUnix()
if err != nil {
log.Print(err)
time.Sleep(time.Second)
continue
}
ch <- conn
break
}
}()
return ch
}
func process(conn *net.UnixConn) (err error) {
if err = conn.SetDeadline(time.Now().Add(time.Second)); err != nil {
return
}
var header Header
if err = binary.Read(conn, binary.LittleEndian, &header); err != nil {
return
}
log.Printf("cmd %#x, crc %X, len %d", header.Cmd, header.Crc, header.Len)
body := make([]byte, header.Len)
for left := len(body); left > 0; {
n, err := conn.Read(body[len(body) - left:])
if err != nil {
return err
}
left -= n
}
if crc := crc32.ChecksumIEEE(body); crc != header.Crc {
if header.Cmd == JPEG {
ioutil.WriteFile("corrupted.jpeg", body, 0600)
} else {
ioutil.WriteFile("corrupted.file", body, 0600)
}
return fmt.Errorf("crc mismatch: found %X, expected %X", crc, header.Crc)
}
if header.Cmd == JPEG {
if err = ioutil.WriteFile("image.jpeg", body, 0600); err != nil {
return
}
} else {
if err = ioutil.WriteFile("recv.file", body, 0600); err != nil {
return
}
}
return
}
func main() {
addr, err := net.ResolveUnixAddr("unix", "/tmp/homework.sock")
if err != nil {
log.Panic(err)
}
listener, err := net.ListenUnix("unix", addr)
if err != nil {
log.Panic(err)
}
defer listener.Close()
listener.SetUnlinkOnClose(true)
ch := make(chan os.Signal)
signal.Notify(ch, os.Interrupt)
for {
select {
case conn := <-asyncAccept(listener):
if err = process(conn); err != nil {
log.Print(err)
}
conn.Close()
case <-ch:
return
}
}
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package filemanager
import (
"context"
"fmt"
"math/rand"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/local/chrome/uiauto/faillog"
"chromiumos/tast/local/chrome/uiauto/filesapp"
"chromiumos/tast/local/drivefs"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: DrivefsGoogleDoc,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Verify that a google doc created via Drive API syncs to DriveFS",
Contacts: []string{
"austinct@chromium.org",
"benreich@chromium.org",
"chromeos-files-syd@google.com",
},
SoftwareDeps: []string{
"chrome",
"chrome_internal",
"drivefs",
},
Attr: []string{
"group:mainline",
"informational",
},
Timeout: 5 * time.Minute,
Params: []testing.Param{{
Fixture: "driveFsStarted",
}, {
Name: "chrome_networking",
Fixture: "driveFsStartedWithChromeNetworking",
}},
})
}
func DrivefsGoogleDoc(ctx context.Context, s *testing.State) {
APIClient := s.FixtValue().(*drivefs.FixtureData).APIClient
tconn := s.FixtValue().(*drivefs.FixtureData).TestAPIConn
cr := s.FixtValue().(*drivefs.FixtureData).Chrome
mountPath := s.FixtValue().(*drivefs.FixtureData).MountPath
// Give the Drive API enough time to remove the file.
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 10*time.Second)
defer cancel()
// Current refresh period is 2 minutes, leaving buffer for UI propagation.
// TODO(crbug/1112246): Reduce refresh period once push notifications fixed.
const filesAppUITimeout = 3 * time.Minute
testDocFileName := fmt.Sprintf("doc-drivefs-%d-%d", time.Now().UnixNano(), rand.Intn(10000))
// Create a blank Google doc in the root GDrive directory.
file, err := APIClient.CreateBlankGoogleDoc(ctx, testDocFileName, []string{"root"})
if err != nil {
s.Fatal("Could not create blank google doc: ", err)
}
defer APIClient.RemoveFileByID(cleanupCtx, file.Id)
defer faillog.DumpUITreeOnError(cleanupCtx, s.OutDir(), s.HasError, tconn)
defer drivefs.SaveDriveLogsOnError(ctx, s.HasError, cr.NormalizedUser(), mountPath)
// Launch Files App and check that Drive is accessible.
filesApp, err := filesapp.Launch(ctx, tconn)
if err != nil {
s.Fatal("Could not launch the Files App: ", err)
}
// Navigate to Google Drive via the Files App ui.
if err := filesApp.OpenDrive()(ctx); err != nil {
s.Fatal("Could not open Google Drive folder: ", err)
}
// Check for the test file created earlier.
testFileNameWithExt := fmt.Sprintf("%s.gdoc", testDocFileName)
if err := filesApp.WithTimeout(filesAppUITimeout).WaitForFile(testFileNameWithExt)(ctx); err != nil {
s.Fatalf("Could not find the test file %q in Drive: %v", testFileNameWithExt, err)
}
}
|
package id3
import (
"encoding/binary"
"reflect"
"testing"
)
func TestParseID3TagSize(t *testing.T) {
result := parseID3TagSize([]byte{0, 0, 2, 1})
if result != 257 {
t.Fatalf("failed test")
}
}
func TestSizeFromUintToByte(t *testing.T) {
cases := []struct {
in size_t
expected []byte
}{
{in: 257, expected: []byte{0, 0, 2, 1}},
{in: 105, expected: []byte{0, 0, 0, 105}},
}
for _, cas := range cases {
result := sizeFromUintToByte(cas.in)
if !reflect.DeepEqual(result, cas.expected) {
t.Fatalf("failed test: %v\n", result)
}
}
}
func TestUTF16BytesToString(t *testing.T) {
cases := []struct {
in []byte
expected string
}{
{in: []byte{0, 97, 0, 97, 0, 97, 0, 98, 0, 98, 0, 98}, expected: "aaabbb"},
{in: []byte{48, 66, 48, 68, 48, 70}, expected: "あいう"},
{in: []byte{105, 28, 138, 60}, expected: "検証"},
}
for _, cas := range cases {
result := UTF16BytesToString(cas.in, binary.BigEndian)
if result != cas.expected {
t.Fatalf("failed test: %v\n", result)
}
}
}
func TestStringToUFT16Bytes(t *testing.T) {
cases := []struct {
in string
expected []byte
}{
{in: "aaabbb", expected: []byte{1, 254, 255, 0, 97, 0, 97, 0, 97, 0, 98, 0, 98, 0, 98}},
{in: "あいう", expected: []byte{1, 254, 255, 48, 66, 48, 68, 48, 70}},
{in: "検証", expected: []byte{1, 254, 255, 105, 28, 138, 60}},
}
for _, cas := range cases {
result := StringToUFT16Bytes(cas.in, binary.BigEndian)
if !reflect.DeepEqual(result, cas.expected) {
t.Fatalf("failed test: %v\n", result)
}
}
}
|
package util
type Queue interface {
Push(interface{})
Pop() interface{}
Peek() interface{}
Size() int
IsEmpty() bool
}
func NewQueue() *queueImpl {
return &queueImpl{
nil,
nil,
0,
}
}
//Single linked list node
type SNode struct {
Val interface{}
Next *SNode
}
// Not thread safe
type queueImpl struct {
head *SNode
tail *SNode
size int
}
func (q *queueImpl) Push(v interface{}) {
if q.size == 0 {
q.head = &SNode{Val: v}
q.tail = q.head
q.size++
return
}
added := &SNode{Val: v}
q.tail.Next = added
q.tail = added
q.size++
}
func (q *queueImpl) Pop() interface{} {
if q.size == 0 {
return nil
}
item := q.head.Val
q.head = q.head.Next
q.size--
return item
}
func (q *queueImpl) Peek() interface{} {
if q.head != nil {
return q.head.Val
}
return nil
}
func (q *queueImpl) Size() int {
return q.size
}
func (q *queueImpl) IsEmpty() bool {
return q.size == 0
}
|
// SPDX-FileCopyrightText: Copyright 2021 The Go Language Server Authors
// SPDX-License-Identifier: BSD-3-Clause
package jsonrpc2
import (
"fmt"
"github.com/segmentio/encoding/json"
)
// Version represents a JSON-RPC version.
const Version = "2.0"
// version is a special 0 sized struct that encodes as the jsonrpc version tag.
//
// It will fail during decode if it is not the correct version tag in the stream.
type version struct{}
// compile time check whether the version implements a json.Marshaler and json.Unmarshaler interfaces.
var (
_ json.Marshaler = (*version)(nil)
_ json.Unmarshaler = (*version)(nil)
)
// MarshalJSON implements json.Marshaler.
func (version) MarshalJSON() ([]byte, error) {
return json.Marshal(Version)
}
// UnmarshalJSON implements json.Unmarshaler.
func (version) UnmarshalJSON(data []byte) error {
version := ""
if err := json.Unmarshal(data, &version); err != nil {
return fmt.Errorf("failed to Unmarshal: %w", err)
}
if version != Version {
return fmt.Errorf("invalid RPC version %v", version)
}
return nil
}
// ID is a Request identifier.
//
// Only one of either the Name or Number members will be set, using the
// number form if the Name is the empty string.
type ID struct {
name string
number int32
}
// compile time check whether the ID implements a fmt.Formatter, json.Marshaler and json.Unmarshaler interfaces.
var (
_ fmt.Formatter = (*ID)(nil)
_ json.Marshaler = (*ID)(nil)
_ json.Unmarshaler = (*ID)(nil)
)
// NewNumberID returns a new number request ID.
func NewNumberID(v int32) ID { return ID{number: v} }
// NewStringID returns a new string request ID.
func NewStringID(v string) ID { return ID{name: v} }
// Format writes the ID to the formatter.
//
// If the rune is q the representation is non ambiguous,
// string forms are quoted, number forms are preceded by a #.
func (id ID) Format(f fmt.State, r rune) {
numF, strF := `%d`, `%s`
if r == 'q' {
numF, strF = `#%d`, `%q`
}
switch {
case id.name != "":
fmt.Fprintf(f, strF, id.name)
default:
fmt.Fprintf(f, numF, id.number)
}
}
// MarshalJSON implements json.Marshaler.
func (id *ID) MarshalJSON() ([]byte, error) {
if id.name != "" {
return json.Marshal(id.name)
}
return json.Marshal(id.number)
}
// UnmarshalJSON implements json.Unmarshaler.
func (id *ID) UnmarshalJSON(data []byte) error {
*id = ID{}
if err := json.Unmarshal(data, &id.number); err == nil {
return nil
}
return json.Unmarshal(data, &id.name)
}
// wireRequest is sent to a server to represent a Call or Notify operaton.
type wireRequest struct {
// VersionTag is always encoded as the string "2.0"
VersionTag version `json:"jsonrpc"`
// Method is a string containing the method name to invoke.
Method string `json:"method"`
// Params is either a struct or an array with the parameters of the method.
Params *json.RawMessage `json:"params,omitempty"`
// The id of this request, used to tie the Response back to the request.
// Will be either a string or a number. If not set, the Request is a notify,
// and no response is possible.
ID *ID `json:"id,omitempty"`
}
// wireResponse is a reply to a Request.
//
// It will always have the ID field set to tie it back to a request, and will
// have either the Result or Error fields set depending on whether it is a
// success or failure wireResponse.
type wireResponse struct {
// VersionTag is always encoded as the string "2.0"
VersionTag version `json:"jsonrpc"`
// Result is the response value, and is required on success.
Result *json.RawMessage `json:"result,omitempty"`
// Error is a structured error response if the call fails.
Error *Error `json:"error,omitempty"`
// ID must be set and is the identifier of the Request this is a response to.
ID *ID `json:"id,omitempty"`
}
// combined has all the fields of both Request and Response.
//
// We can decode this and then work out which it is.
type combined struct {
VersionTag version `json:"jsonrpc"`
ID *ID `json:"id,omitempty"`
Method string `json:"method"`
Params *json.RawMessage `json:"params,omitempty"`
Result *json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
|
package dcrlibwallet
import (
"github.com/asdine/storm"
)
const (
userConfigBucketName = "user_config"
LogLevelConfigKey = "log_level"
SpendUnconfirmedConfigKey = "spend_unconfirmed"
CurrencyConversionConfigKey = "currency_conversion_option"
IsStartupSecuritySetConfigKey = "startup_security_set"
StartupSecurityTypeConfigKey = "startup_security_type"
UseFingerprintConfigKey = "use_fingerprint"
IncomingTxNotificationsConfigKey = "tx_notification_enabled"
BeepNewBlocksConfigKey = "beep_new_blocks"
SyncOnCellularConfigKey = "always_sync"
NetworkModeConfigKey = "network_mode"
SpvPersistentPeerAddressesConfigKey = "spv_peer_addresses"
UserAgentConfigKey = "user_agent"
LastTxHashConfigKey = "last_tx_hash"
VSPHostConfigKey = "vsp_host"
PassphraseTypePin int32 = 0
PassphraseTypePass int32 = 1
)
type configSaveFn = func(key string, value interface{}) error
type configReadFn = func(key string, valueOut interface{}) error
func (mw *MultiWallet) walletConfigSetFn(walletID int) configSaveFn {
return func(key string, value interface{}) error {
walletUniqueKey := WalletUniqueConfigKey(walletID, key)
return mw.db.Set(userConfigBucketName, walletUniqueKey, value)
}
}
func (mw *MultiWallet) walletConfigReadFn(walletID int) configReadFn {
return func(key string, valueOut interface{}) error {
walletUniqueKey := WalletUniqueConfigKey(walletID, key)
return mw.db.Get(userConfigBucketName, walletUniqueKey, valueOut)
}
}
func (mw *MultiWallet) SaveUserConfigValue(key string, value interface{}) {
err := mw.db.Set(userConfigBucketName, key, value)
if err != nil {
log.Errorf("error setting config value for key: %s, error: %v", key, err)
}
}
func (mw *MultiWallet) ReadUserConfigValue(key string, valueOut interface{}) error {
err := mw.db.Get(userConfigBucketName, key, valueOut)
if err != nil && err != storm.ErrNotFound {
log.Errorf("error reading config value for key: %s, error: %v", key, err)
}
return err
}
func (mw *MultiWallet) DeleteUserConfigValueForKey(key string) {
err := mw.db.Delete(userConfigBucketName, key)
if err != nil {
log.Errorf("error deleting config value for key: %s, error: %v", key, err)
}
}
func (mw *MultiWallet) ClearConfig() {
err := mw.db.Drop(userConfigBucketName)
if err != nil {
log.Errorf("error deleting config bucket: %v", err)
}
}
func (mw *MultiWallet) SetBoolConfigValueForKey(key string, value bool) {
mw.SaveUserConfigValue(key, value)
}
func (mw *MultiWallet) SetDoubleConfigValueForKey(key string, value float64) {
mw.SaveUserConfigValue(key, value)
}
func (mw *MultiWallet) SetIntConfigValueForKey(key string, value int) {
mw.SaveUserConfigValue(key, value)
}
func (mw *MultiWallet) SetInt32ConfigValueForKey(key string, value int32) {
mw.SaveUserConfigValue(key, value)
}
func (mw *MultiWallet) SetLongConfigValueForKey(key string, value int64) {
mw.SaveUserConfigValue(key, value)
}
func (mw *MultiWallet) SetStringConfigValueForKey(key, value string) {
mw.SaveUserConfigValue(key, value)
}
func (mw *MultiWallet) ReadBoolConfigValueForKey(key string, defaultValue bool) (valueOut bool) {
if err := mw.ReadUserConfigValue(key, &valueOut); err == storm.ErrNotFound {
valueOut = defaultValue
}
return
}
func (mw *MultiWallet) ReadDoubleConfigValueForKey(key string, defaultValue float64) (valueOut float64) {
if err := mw.ReadUserConfigValue(key, &valueOut); err == storm.ErrNotFound {
valueOut = defaultValue
}
return
}
func (mw *MultiWallet) ReadIntConfigValueForKey(key string, defaultValue int) (valueOut int) {
if err := mw.ReadUserConfigValue(key, &valueOut); err == storm.ErrNotFound {
valueOut = defaultValue
}
return
}
func (mw *MultiWallet) ReadInt32ConfigValueForKey(key string, defaultValue int32) (valueOut int32) {
if err := mw.ReadUserConfigValue(key, &valueOut); err == storm.ErrNotFound {
valueOut = defaultValue
}
return
}
func (mw *MultiWallet) ReadLongConfigValueForKey(key string, defaultValue int64) (valueOut int64) {
if err := mw.ReadUserConfigValue(key, &valueOut); err == storm.ErrNotFound {
valueOut = defaultValue
}
return
}
func (mw *MultiWallet) ReadStringConfigValueForKey(key string) (valueOut string) {
mw.ReadUserConfigValue(key, &valueOut)
return
}
|
package divisible_test
import (
"testing"
"github.com/ifreddyrondon/go-workshop/santiago-nov2018/resources/src/13_testing/divisible"
)
func TestSum(t *testing.T) {
tt := []struct {
name string
top int
by []int
expect int
}{
{
name: "when top 0 expected 0",
top: 0,
by: []int{3},
expect: 0,
},
{
name: "when top 3 expected 3",
top: 3,
by: []int{3},
expect: 3,
},
{
name: "when top 15 expected 45",
top: 15,
by: []int{3},
expect: 45,
},
{
name: "when top 15 and by 3, and 5 expected 75",
top: 15,
by: []int{3, 5},
expect: 75,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
result := divisible.Sum(tc.top, tc.by...)
if tc.expect != result {
t.Errorf("test err: expected %v but got %v", tc.expect, result)
}
})
}
}
|
package animatedArr
import (
"math"
"time"
)
func (a *AnimArr) generateShellSortGaps() []int { // Generate A083318 gaps O(n^(3/2))
var out = []int{1} // Init with 1
for i, k := 0, 1; k < len(a.Data); i, k = i + 1, int(math.Ceil(math.Pow(2, float64(i)) + 1)) {
println(k, "k")
out = append(out, k)
}
return out
}
func (a *AnimArr) ShellSort() {
gapSequence := a.generateShellSortGaps()
for i, gap := len(gapSequence)-1, gapSequence[len(gapSequence)-1]; i >= 0; i, gap = i - 1, gapSequence[i] { // Go through array backwards
println("Gap:", gap)
for i := gap; !a.Sorted && i < len(a.Data); i++ {
temp := a.Data[i]
for a.Active = i; a.Active >= gap && a.Data[a.Active-gap] > temp; a.Active -= gap {
a.Comparisons++ // Remember, not counting Comparisons unless they compare an element of a.Data
a.Active2 = a.Active-gap
a.Data[a.Active] = a.Data[a.Active2]
time.Sleep(SHL_SLEEP)
a.totalSleepTime += SHL_SLEEP.Seconds()
a.ArrayAccesses += 3 // 2+ One in for loop
}
a.Data[a.Active] = temp
a.ArrayAccesses += 2
}
}
}
|
// Copyright (c) 2014-2018 Salsita Software
// Use of this source code is governed by the MIT License.
// The license can be found in the LICENSE file.
package pivotal
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/url"
)
const (
// LibraryVersion is used to give the UserAgent some additional context
LibraryVersion = "2.0.0"
defaultBaseURL = "https://www.pivotaltracker.com/services/v5/"
defaultUserAgent = "go-pivotaltracker/" + LibraryVersion
)
// ErrNoTrailingSlash is returned when URLs are missing the trailing slash
var ErrNoTrailingSlash = errors.New("trailing slash missing")
// Client wraps all Pivotal Tracker services with necessary auth contexts
type Client struct {
// Pivotal Tracker access token to be used to authenticate API requests.
token string
// HTTP client to be used for communication with the Pivotal Tracker API.
client *http.Client
// Base URL of the Pivotal Tracker API that is to be used to form API requests.
baseURL *url.URL
// User-Agent header to use when connecting to the Pivotal Tracker API.
userAgent string
// Me service
Me *MeService
// Project service
Projects *ProjectService
// Story service
Stories *StoryService
// Membership service
Memberships *MembershipService
// Iteration service
Iterations *IterationService
// Activity Service
Activity *ActivityService
// Epic Service
Epic *EpicService
}
// NewClient takes a Pivotal Tracker API Token (created from the project settings) and
// returns a default Client implementation
func NewClient(apiToken string) *Client {
baseURL, _ := url.Parse(defaultBaseURL)
client := &Client{
token: apiToken,
client: http.DefaultClient,
baseURL: baseURL,
userAgent: defaultUserAgent,
}
client.Me = newMeService(client)
client.Projects = newProjectService(client)
client.Stories = newStoryService(client)
client.Memberships = newMembershipService(client)
client.Iterations = newIterationService(client)
client.Activity = newActivitiesService(client)
client.Epic = newEpicService(client)
return client
}
// SetBaseURL overrides the defaultBaseURL in the default Client implementation.
func (c *Client) SetBaseURL(baseURL string) error {
u, err := url.Parse(baseURL)
if err != nil {
return err
}
if u.Path != "" && u.Path[len(u.Path)-1] != '/' {
return ErrNoTrailingSlash
}
c.baseURL = u
return nil
}
// SetUserAgent overrides the defaultUserAgent in the default Client implementation.
func (c *Client) SetUserAgent(agent string) {
c.userAgent = agent
}
// NewRequest takes an HTTP request definition and wraps it with the Client context.
func (c *Client) NewRequest(method, urlPath string, body interface{}) (*http.Request, error) {
path, err := url.Parse(urlPath)
if err != nil {
return nil, err
}
u := c.baseURL.ResolveReference(path)
buf := new(bytes.Buffer)
if body != nil {
if err := json.NewEncoder(buf).Encode(body); err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("X-TrackerToken", c.token)
return req, nil
}
// Do takes a request created from NewRequest and executes the HTTP round trip action.
func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
var errObject Error
if err := json.NewDecoder(resp.Body).Decode(&errObject); err != nil {
return resp, &ErrAPI{Response: resp}
}
return resp, &ErrAPI{
Response: resp,
Err: &errObject,
}
}
if v != nil {
err = json.NewDecoder(resp.Body).Decode(v)
}
return resp, err
}
|
package scraper
import (
"fmt"
"math"
"sync"
"time"
"github.com/sirupsen/logrus"
)
type Progress struct {
m sync.Mutex
count int
limit int
}
const CHUNK_SIZE int = 50
func (s Scraper) Start() {
progress := Progress{count: 0, limit: s.Args.Limit * len(s.Args.Years) * len(s.Args.Prefixes)}
for _, prefix := range s.Args.Prefixes {
for _, year := range s.Args.Years {
nimPrefix := fmt.Sprintf("%s%s", prefix, year)
for i := 0; i <= s.Args.Limit/CHUNK_SIZE; i++ {
go func(offset int, prefix string) {
batasAtas := int(math.Min((float64(offset)+1)*float64(CHUNK_SIZE), float64(s.Args.Limit)))
start := (offset * CHUNK_SIZE) + 1
isSkipping := false
notFoundStreak := 0
if start <= batasAtas {
for each := start; each <= batasAtas; each++ {
nim := fmt.Sprintf("%s%03d", prefix, each)
if isSkipping {
s.Failed <- nim
continue
}
student, err := s.GetByNIM(nim)
logrus.Debugf("Student: %s Error: %s", student, err)
if err != nil {
logrus.Warnf("Failed to fetch %s, reason: %s", nim, err)
s.Failed <- nim
notFoundStreak++
if notFoundStreak > 5 {
isSkipping = true
logrus.Warnf("Skipping %s - %s", nim, fmt.Sprintf("%s%03d", prefix, batasAtas))
}
continue
}
notFoundStreak = 0
s.Students <- student
}
logrus.Infof("Fetched %s - %s", fmt.Sprintf("%s%03d", prefix, start), fmt.Sprintf("%s%03d", prefix, batasAtas))
progress.m.Lock()
progress.count += batasAtas - start + 1
progress.m.Unlock()
}
}(i, nimPrefix)
}
}
}
go func() {
lastProgress := float64(0)
for {
progress.m.Lock()
currentProgress := float64(progress.count) * 100 / float64(progress.limit)
if lastProgress != currentProgress {
logrus.Infof("Progress %.2f%%", currentProgress)
lastProgress = currentProgress
}
progress.m.Unlock()
time.Sleep(3 * time.Second)
}
}()
}
|
package usecase
import (
"errors"
"marketplace/transactions/domain"
"marketplace/transactions/internal/infrastructure/accounts"
"marketplace/transactions/internal/infrastructure/ads"
"marketplace/transactions/internal/request"
"strings"
"github.com/gin-gonic/gin"
"github.com/go-pg/pg/v10"
"github.com/sirupsen/logrus"
)
type CreateTransactionCmd func(db *pg.DB, c *gin.Context, createTransaction *request.CreateTransactionRequest, user domain.Account) (domain.Transaction, error)
func CreateTransaction(adsFetcher ads.Fetcher, accountsFetcher accounts.Fetcher) CreateTransactionCmd {
return func(db *pg.DB, c *gin.Context, createTransaction *request.CreateTransactionRequest, user domain.Account) (domain.Transaction, error) {
if createTransaction.Bid > user.Balance {
return domain.Transaction{}, errors.New("too expensive")
}
ads, err := adsFetcher.GetAdsById(c, createTransaction.AdsId)
if err != nil {
if strings.Contains(err.Error(), "404") {
return domain.Transaction{}, errors.New("Not found")
}
return domain.Transaction{}, err
}
seller, err := accountsFetcher.GetUserById(c, ads.UserId)
if err != nil {
logrus.WithError(err).Error("Can not use the accountsFetcher to GetUserById")
return domain.Transaction{}, err
}
if seller.Id == user.Id {
return domain.Transaction{}, errors.New("You can not make an offer for an add that you created.")
}
transaction := domain.Transaction{
Buyer: &user,
BuyerId: user.Id,
Seller: &seller,
SellerId: seller.Id,
Ads: &ads,
AdsId: ads.Id,
Messages: []domain.Message{},
Bid: createTransaction.Bid,
Status: "PROPOSITION",
}
_, err = db.Model(&transaction).Insert()
if err != nil {
return domain.Transaction{}, nil
}
return transaction, nil
}
}
|
package main
import (
"flag"
"fmt"
"net"
"github.com/2beens/network-programming-with-go/my_tests/desktop_laptop_connection"
"github.com/eiannone/keyboard"
"github.com/kataras/golog"
)
func main() {
golog.SetLevel("debug")
listenAddr := flag.String("addr", "", "listen address, e.g. 192.168.178.1")
listenPort := flag.String("port", "9999", "listen port, e.g. 9999")
proxyAddr := flag.String("proxy", "", "route via proxy (empty for no proxy), e.g. 127.0.0.1:9998")
flag.Parse()
endpoint := fmt.Sprintf("%s:%s", *listenAddr, *listenPort)
golog.Infof("dialer starting [%s] ...", endpoint)
var (
err error
conn net.Conn
)
if *proxyAddr == "" {
conn, err = net.Dial("tcp", endpoint)
if err != nil {
golog.Fatal(err)
}
} else {
golog.Debug("connecting via proxy ...")
conn, err = net.Dial("tcp", *proxyAddr)
if err != nil {
golog.Fatal(err)
}
_, err = conn.Write([]byte("client"))
if err != nil {
golog.Fatal(err)
}
}
golog.Infof("connection established with %s", conn.RemoteAddr())
if err := keyboard.Open(); err != nil {
panic(err)
}
defer func() {
if err := keyboard.Close(); err != nil {
golog.Error(err)
}
}()
golog.Warn("press ESC to quit")
for {
keyRune, key, err := keyboard.GetKey()
if err != nil {
golog.Fatal(err)
}
switch {
case key == keyboard.KeyArrowUp:
golog.Debugf("^")
_, err = conn.Write([]byte(desktop_laptop_connection.ControlIncrease))
if err != nil {
golog.Error(err)
}
case key == keyboard.KeyArrowDown:
golog.Debugf("v")
_, err = conn.Write([]byte(desktop_laptop_connection.ControlDecrease))
if err != nil {
golog.Error(err)
}
case key == keyboard.KeyEsc,
keyRune == 113: // keyRune 113 = q
golog.Warn("closing connection")
if err := conn.Close(); err != nil {
golog.Error(err)
}
return
}
}
}
|
// 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 platform
import (
"context"
"fmt"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"unicode"
"chromiumos/tast/common/testexec"
"chromiumos/tast/local/rialto"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: PartitionSizes,
Desc: "Checks rootfs partition sizes",
Contacts: []string{"chromeos-systems@google.com"},
Attr: []string{"group:mainline"},
})
}
func PartitionSizes(ctx context.Context, s *testing.State) {
// Get the internal disk device's name, e.g. "/dev/sda".
const script = `
set -e
. /usr/sbin/write_gpt.sh
. /usr/share/misc/chromeos-common.sh
load_base_vars
get_fixed_dst_drive`
out, err := testexec.CommandContext(ctx, "sh", "-c", strings.TrimSpace(script)).Output(testexec.DumpLogOnError)
if err != nil {
s.Fatal("Failed to get device: ", err)
}
baseDev := filepath.Base(strings.TrimSpace(string(out)))
if baseDev == "." { // filepath.Base("") returns "."
baseDev = "sda"
s.Logf("Got empty device; defaulting to %q (running in VM?)", baseDev)
}
s.Log("Checking partitions on device ", baseDev)
// If the device ends in a digit, a "p" appears before the partition number.
partPrefix := baseDev
if unicode.IsDigit(rune(baseDev[len(baseDev)-1])) {
partPrefix += "p"
}
const gb = 1024 * 1024 * 1024
validSizes := []int64{
2 * gb,
4 * gb,
}
// Rialto devices may use 1 GB partitions.
if isRialto, err := rialto.IsRialto(); err != nil {
s.Error("Failed to check if device is rialto: ", err)
} else if isRialto {
validSizes = append(validSizes, 1*gb)
}
for _, partNum := range []int{3, 5} {
partDev := partPrefix + strconv.Itoa(partNum)
// This file contains the partition size in 512-byte sectors.
// See https://patchwork.kernel.org/patch/7922301/ .
sizePath := fmt.Sprintf("/sys/block/%s/%s/size", baseDev, partDev)
out, err := ioutil.ReadFile(sizePath)
if err != nil {
s.Errorf("Failed to get %s size: %v", partDev, err)
continue
}
sectors, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64)
if err != nil {
s.Errorf("Failed to parse %q from %s: %v", out, sizePath, err)
continue
}
bytes := sectors * 512
valid := false
for _, vs := range validSizes {
if bytes == vs {
valid = true
break
}
}
if valid {
s.Logf("%s is %d bytes", partDev, bytes)
} else if partNum == 5 && bytes < 10*1024*1024 {
// Test images tend to use a stub ROOT-B, so allow very small ones.
s.Logf("%s is %d bytes; ignoring stub partition", partDev, bytes)
} else {
s.Errorf("%s is %d bytes; valid sizes are %v", partDev, bytes, validSizes)
}
}
}
|
package common
import (
"debug/elf"
"encoding/json"
"io/ioutil"
)
type KernelMeta struct {
Machine string `json:"machine" yaml:"machine"`
Platform string `json:"platform" yaml:"platform"`
Version string `json:"version" yaml:"version"`
From string `json:"from" yaml:"from"`
}
func LoadKernelMeta(path string) (*KernelMeta, error) {
var km KernelMeta
ba, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
err = json.Unmarshal(ba, &km)
if err != nil {
return nil, err
}
return &km, nil
}
func LoadKernelElf(path string) (*elf.FileHeader, error) {
kf, err := elf.Open(path)
if err != nil {
return nil, err
}
return &kf.FileHeader, nil
}
|
// Copyright (c) KwanJunWen
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package estemplate
import "fmt"
// DatatypeShort Core Datatype for numeric value.
// A signed 16-bit integer with a minimum value of -32,768 and a maximum value of 32,767.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/number.html
// for details.
type DatatypeShort struct {
Datatype
name string
copyTo []string
// fields specific to short datatype
coerce *bool
boost *float32
docValues *bool
ignoreMalformed *bool
index *bool
nullValue *int
store *bool
}
// NewDatatypeShort initializes a new DatatypeShort.
func NewDatatypeShort(name string) *DatatypeShort {
return &DatatypeShort{
name: name,
}
}
// Name returns field key for the Datatype.
func (s *DatatypeShort) Name() string {
return s.name
}
// CopyTo sets the field(s) to copy to which allows the values of multiple fields to be
// queried as a single field.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/copy-to.html
// for details.
func (s *DatatypeShort) CopyTo(copyTo ...string) *DatatypeShort {
s.copyTo = append(s.copyTo, copyTo...)
return s
}
// Coerce sets whether if the field should be coerced, attempting to clean up
// dirty values to fit the datatype. Defaults to true.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/coerce.html
// for details.
func (s *DatatypeShort) Coerce(coerce bool) *DatatypeShort {
s.coerce = &coerce
return s
}
// Boost sets Mapping field-level query time boosting. Defaults to 1.0.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/mapping-boost.html
// for details.
func (s *DatatypeShort) Boost(boost float32) *DatatypeShort {
s.boost = &boost
return s
}
// DocValues sets whether if the field should be stored on disk in a column-stride fashion
// so that it can later be used for sorting, aggregations, or scripting.
// Defaults to true.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/doc-values.html
// for details.
func (s *DatatypeShort) DocValues(docValues bool) *DatatypeShort {
s.docValues = &docValues
return s
}
// IgnoreMalformed sets whether if the field should ignore malformed numbers.
// Defaults to false.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/ignore-malformed.html
// for details.
func (s *DatatypeShort) IgnoreMalformed(ignoreMalformed bool) *DatatypeShort {
s.ignoreMalformed = &ignoreMalformed
return s
}
// Index sets whether if the field should be searchable. Defaults to true.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/mapping-index.html
// for details.
func (s *DatatypeShort) Index(index bool) *DatatypeShort {
s.index = &index
return s
}
// NullValue sets a numeric value which is substituted for any explicit null values.
// Defaults to null.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/null-value.html
// for details.
func (s *DatatypeShort) NullValue(nullValue int) *DatatypeShort {
s.nullValue = &nullValue
return s
}
// Store sets whether if the field value should be stored and retrievable separately
// from the `_source` field. Defaults to false.
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/mapping-store.html
// for details.
func (s *DatatypeShort) Store(store bool) *DatatypeShort {
s.store = &store
return s
}
// Validate validates DatatypeShort.
func (s *DatatypeShort) Validate(includeName bool) error {
var invalid []string
if includeName && s.name == "" {
invalid = append(invalid, "Name")
}
if len(invalid) > 0 {
return fmt.Errorf("missing required fields: %v", invalid)
}
return nil
}
// Source returns the serializable JSON for the source builder.
func (s *DatatypeShort) Source(includeName bool) (interface{}, error) {
// {
// "test": {
// "type": "short",
// "copy_to": ["field_1", "field_2"],
// "coerce": true,
// "boost": 2,
// "doc_values": true,
// "ignore_malformed": true,
// "index": true,
// "null_value": 0,
// "store": true
// }
// }
options := make(map[string]interface{})
options["type"] = "short"
if len(s.copyTo) > 0 {
var copyTo interface{}
switch {
case len(s.copyTo) > 1:
copyTo = s.copyTo
break
case len(s.copyTo) == 1:
copyTo = s.copyTo[0]
break
default:
copyTo = ""
}
options["copy_to"] = copyTo
}
if s.coerce != nil {
options["coerce"] = s.coerce
}
if s.boost != nil {
options["boost"] = s.boost
}
if s.docValues != nil {
options["doc_values"] = s.docValues
}
if s.ignoreMalformed != nil {
options["ignore_malformed"] = s.ignoreMalformed
}
if s.index != nil {
options["index"] = s.index
}
if s.nullValue != nil {
options["null_value"] = s.nullValue
}
if s.store != nil {
options["store"] = s.store
}
if !includeName {
return options, nil
}
source := make(map[string]interface{})
source[s.name] = options
return source, nil
}
|
//go:build !darwin && !windows
// +build !darwin,!windows
package idle
// NewIdleGetter returns a new idle getter for windows
func NewIdleGetter() (Getter, error) {
return nil, &unsupportedError{}
}
|
package controllers
import (
"fmt"
"html/template"
"net/http"
"models"
"session"
)
// Index is top page action shows top page
func Index(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
fmt.Println(err)
}
token := session.Start(w, r)
tmpl.Execute(w, token)
}
// CreateTodo creates Todo and shows todo page
func CreateTodo(w http.ResponseWriter, r *http.Request) {
todo := models.CreateNewTodo()
http.Redirect(w, r, "/"+todo.UUID, http.StatusMovedPermanently)
}
|
package routes
import (
"commerce/auth"
"commerce/context"
"commerce/helpers"
"commerce/models"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func newMiddlewares(
models *models.Models,
jwt auth.Auth,
) *middlewares {
return &middlewares{
models: models,
jwt: jwt,
}
}
// Users router
type middlewares struct {
models *models.Models
jwt auth.Auth
}
func (m *middlewares) requireUser(c *gin.Context) {
bearer := c.GetHeader("Authorization")
if bearer == "" {
helpers.ErrResponse(c, nil, helpers.ErrInvalidToken, http.StatusUnauthorized)
c.Abort()
return
}
st := strings.Split(bearer, "Bearer")
token := strings.TrimSpace(st[1])
if token == "" {
helpers.ErrResponse(c, nil, helpers.ErrInvalidToken, http.StatusUnauthorized)
c.Abort()
return
}
userToken, err := m.jwt.VerifyToken(token)
if err != nil {
helpers.ErrResponse(c, nil, helpers.ErrInvalidToken, http.StatusUnauthorized)
c.Abort()
return
}
user, err := m.models.User.ByUsername(userToken.Username)
if err != nil {
helpers.ErrResponse(c, nil, helpers.ErrInvalidToken, http.StatusUnauthorized)
c.Abort()
return
}
user.Password = ""
context.SetUser(c, user)
c.Next()
}
func (m *middlewares) requireAdmin(c *gin.Context) {
user := context.GetUser(c)
if user.Role.ID != 0 && user.Role.Type == "admin" {
c.Next()
return
}
helpers.ErrResponse(c, nil, helpers.ErrAccessNotGranted, http.StatusUnauthorized)
c.Abort()
}
|
package etherscan
import (
"github.com/gin-gonic/gin"
"github.com/trustwallet/blockatlas/coin"
"github.com/trustwallet/blockatlas/pkg/blockatlas"
)
type Platform struct {
CoinIndex uint
RpcURL string
client Client
}
func Init(coin uint, api, rpc string) *Platform {
return &Platform{
CoinIndex: coin,
RpcURL: rpc,
client: Client{blockatlas.InitClient(api), 10},
}
}
func (p *Platform) Coin() coin.Coin {
return coin.Coins[p.CoinIndex]
}
func (p *Platform) RegisterRoutes(router gin.IRouter) {
router.GET("/balance/:address", func(c *gin.Context) {
p.getBalance(c)
})
router.GET("/address/:address", func(c *gin.Context) {
p.getTransactions(c)
})
router.GET("/current_block", func(c *gin.Context) {
p.getCurrentBlockNumber(c)
})
router.GET("/block/:block", func(c *gin.Context) {
p.getBlockByNumber(c)
})
router.GET("/gas/price", func(c *gin.Context) {
p.getGasPrice(c)
})
router.POST("/transaction/estimate", func(c *gin.Context) {
p.getEstimatedGas(c)
})
router.POST("/transaction/send", func(c *gin.Context) {
p.sendTransaction(c)
})
}
|
package main
import (
"finance/api/account"
"finance/api/business"
"finance/api/common"
_ "finance/models"
_ "finance/models/init"
"finance/plugins"
"finance/plugins/jwt_auth"
"github.com/gin-gonic/gin"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
if plugins.Config.GinMode == "release" {
gin.SetMode(gin.ReleaseMode)
}
jwt_auth.TokenSignKey = plugins.Config.SecretKey
router := gin.Default()
router.Use(jwt_auth.Cors())
BusinessApiRegistered(router)
CommonApiRegistered(router)
AccountApiRegistered(router)
DriverApiRegistered(router)
router.Run("127.0.0.1:8095")
}
// 注册业务api
func BusinessApiRegistered(engine *gin.Engine) {
//open := engine.Group("/business/")
relative_path := "/business"
auth := engine.Group(relative_path, jwt_auth.JWTAuth())
{
auth.GET("/order/list/", business.OrderList)
auth.GET("/order/info/", business.OrderInfo)
auth.GET("/query_receiver/", business.QueryReceiver)
auth.GET("/query_sender/", business.QuerySender)
}
{
auth.POST("/order/add/", business.AddOrder)
auth.POST("/order/edit/", business.OrderEdit)
}
{
auth.DELETE("/order/delete/", business.OrderDelete)
}
level_auth := engine.Group(relative_path, jwt_auth.LevelAuth(2))
{
level_auth.GET("/order/info/amount/", business.OrderAmount)
level_auth.GET("/sender/list/", business.SenderList)
level_auth.GET("/sender/info/", business.SenderInfo)
level_auth.GET("/receiver/list/", business.ReceiverList)
level_auth.GET("/receiver/info/", business.ReceiverInfo)
level_auth.GET("/receiver/product/list/", business.ProductList)
level_auth.GET("/receiver/product/info/", business.ProductInfo)
level_auth.GET("/receiver/product/query/", business.ProductQuery)
}
{
level_auth.POST("/order/amount/edit/", business.OrderAmountEdit)
level_auth.POST("/sender/edit/", business.SenderEdit)
level_auth.POST("/receiver/edit/", business.ReceiverEdit)
level_auth.POST("/receiver/product/add/", business.ProductAdd)
level_auth.POST("/receiver/product/edit/", business.ProductEdit)
}
{
level_auth.DELETE("/receiver/product/delete/", business.ProductDelete)
}
}
// 注册通用api
func CommonApiRegistered(engine *gin.Engine) {
open := engine.Group("")
{
open.POST("/send_sms/code/", common.SMSSend)
}
auth := engine.Group("", jwt_auth.JWTAuth())
{
auth.GET("/query_area/", common.QueryArea)
}
}
// 注册账号api
func AccountApiRegistered(engine *gin.Engine) {
open := engine.Group("/account")
{
open.POST("/registered/", account.Registered)
open.POST("/edit_password/", account.EditPassword)
open.POST("/sign_in/", account.SignIn)
}
auth := engine.Group("/account/", jwt_auth.JWTAuth())
{
auth.GET("/sign_out/", account.SignOut)
auth.GET("/factory/get_token/", account.GetFactoryToken)
}
}
// 注册驾驶员api
func DriverApiRegistered(engine *gin.Engine) {
level_auth := engine.Group("/driver", jwt_auth.LevelAuth(2))
{
level_auth.POST("/add/", business.AddDriver)
level_auth.POST("/edit/", business.DriverEdit)
level_auth.POST("/trips/add/", business.AddDriverTrips)
level_auth.POST("/trips/edit/", business.DriverTripsEdit)
level_auth.POST("/trips/order/add/", business.DriverTripsAddOrder)
level_auth.POST("/trips/order/amount/edit/", business.DriverTripsEditOrderAmount)
}
{
level_auth.GET("/info/", business.DriverInfo)
level_auth.GET("/list/", business.DriverList)
level_auth.GET("/trips/info/", business.DriverTripsInfo)
level_auth.GET("/trips/list/", business.DriverTripsList)
level_auth.GET("/trips/order/list/", business.DriverTripsOrderList)
}
{
level_auth.DELETE("/delete/", business.DeleteDriver)
level_auth.DELETE("trips/delete/", business.DeleteDriverTrips)
level_auth.DELETE("trips/order/delete/", business.DriverTripsDeleteOrder)
}
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package main
import (
"os"
log "github.com/sirupsen/logrus"
)
var logger *log.Logger
func init() {
logger = log.New()
logger.SetLevel(log.DebugLevel)
log.SetOutput(os.Stdout)
logger.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
})
}
func printSeparator() {
logger.Info("====================================================")
}
func printResults(results []string) {
printSeparator()
logger.Info("TEST RESULTS")
printSeparator()
for _, result := range results {
logger.Info(result)
}
printSeparator()
}
|
package main
import (
"fmt"
"math/rand"
"runtime"
"time"
)
func main() {
//print()
//award()
getNum()
}
func print() {
runtime.GOMAXPROCS(runtime.NumCPU())
chan_n := make(chan bool)
chan_c := make(chan bool, 1)
done := make(chan struct{})
go func() {
for i := 1; i < 11; i += 2 {
<-chan_c
fmt.Print(i)
fmt.Print(i + 1)
chan_n <- true
}
}()
go func() {
chan_seq := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"}
for i := 1; i < 10; i += 2 {
<-chan_n
fmt.Print(chan_seq[i])
fmt.Print(chan_seq[i+1])
chan_c <- true
}
done <- struct{}{}
}()
chan_c <- true
<-done
}
func GetAwardUserName(users map[string]int64) (name string) {
sizeOfUsers := len(users)
award_index := rand.Intn(sizeOfUsers)
var index int
for u_name, _ := range users {
if index == award_index {
name = u_name
return
}
index += 1
}
return
}
func award() {
var users map[string]int64 = map[string]int64{
"a": 10,
"b": 5,
"c": 13,
"d": 100,
"e": 23,
"f": 45,
}
rand.Seed(time.Now().Unix())
award_start := make(map[string]int64)
for i := 0; i < 1000; i++ {
name := GetAwardUserName(users)
if count, ok := award_start[name]; ok {
award_start[name] = count + 1
} else {
award_start[name] = 1
}
}
for name, count := range award_start {
fmt.Printf("user: %s,award count:%d\n", name, count)
}
return
}
func getNum() {
func1 := addNum()
fmt.Println(func1(1, 2))
fmt.Println(func1(2, 3))
fmt.Println(func1(3, 4))
func2 := addNum()
fmt.Println(func2(1, 3))
}
func addNum() func(int, int) int {
a := 0
return func(i int, j int) int {
a++
//fmt.Println(a)
return i + j + a
}
}
|
/*
Copyright 2019 Blood Orange
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package helm
import (
"bytes"
"compress/gzip"
"encoding/base64"
"encoding/json"
"errors"
"io/ioutil"
"strconv"
"strings"
"github.com/jenkins-x/jx-logging/v3/pkg/log"
"github.com/jenkins-x/octant-jx/pkg/common/viewhelpers"
rspb "helm.sh/helm/v3/pkg/release"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
type (
tempReleaseSummary struct {
Object *unstructured.Unstructured
RevisionNumber int
}
tempReleaseSummaryMap map[string]tempReleaseSummary
)
func UnstructuredListToHelmReleaseList(ul *unstructured.UnstructuredList) []*rspb.Release {
var releases []*rspb.Release
latestHelmReleases := getLatestHelmReleases(ul)
for _, summary := range latestHelmReleases {
secret, err := viewhelpers.ToSecret(summary.Object)
if err != nil {
log.Logger().Info(err)
continue
}
release, err := convertSecretToHelmRelease(secret)
if err != nil {
log.Logger().Info(err)
continue
}
releases = append(releases, release)
}
return releases
}
func UnstructuredListToAnyHelmReleaseList(ul *unstructured.UnstructuredList) []*rspb.Release {
var releases []*rspb.Release
for k := range ul.Items {
secret, err := viewhelpers.ToSecret(&ul.Items[k])
if err != nil {
log.Logger().Info(err)
continue
}
release, err := convertSecretToHelmRelease(secret)
if err != nil {
log.Logger().Info(err)
continue
}
releases = append(releases, release)
}
return releases
}
// List of secrets contains all revisions,
// so just get the latest revision for each release
func getLatestHelmReleases(ul *unstructured.UnstructuredList) tempReleaseSummaryMap {
latestHelmReleases := tempReleaseSummaryMap{}
for _, obj := range ul.Items {
name := obj.GetName()
tmp := strings.Split(name, ".")
if len(tmp) != 6 {
// Not a Helm-related secret
// Note: valid Helm release secrets look like: sh.helm.release.v1.myrelease.v8
continue
}
releaseName := tmp[4]
revisionNumber, err := strconv.Atoi(strings.TrimPrefix(tmp[5], "v"))
if err != nil {
log.Logger().Info(err)
continue
}
existingEntry, ok := latestHelmReleases[releaseName]
if !ok || existingEntry.RevisionNumber < revisionNumber {
latestHelmReleases[releaseName] = tempReleaseSummary{
Object: obj.DeepCopy(),
RevisionNumber: revisionNumber,
}
}
}
return latestHelmReleases
}
func convertSecretToHelmRelease(s *v1.Secret) (*rspb.Release, error) {
val, ok := s.Data["release"]
if !ok {
return nil, errors.New("secret does not contain a \"release\" field")
}
return decodeRelease(string(val))
}
// Rest of the code found below copied from:
// https://github.com/helm/helm/blob/9b42702a4bced339ff424a78ad68dd6be6e1a80a/pkg/storage/driver/util.go
var b64 = base64.StdEncoding
var magicGzip = []byte{0x1f, 0x8b, 0x08}
func decodeRelease(data string) (*rspb.Release, error) {
// base64 decode string
b, err := b64.DecodeString(data)
if err != nil {
return nil, err
}
// For backwards compatibility with releases that were stored before
// compression was introduced we skip decompression if the
// gzip magic header is not found
if bytes.Equal(b[0:3], magicGzip) {
r, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
return nil, err
}
b2, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
b = b2
}
var rls rspb.Release
// unmarshal protobuf bytes
if err := json.Unmarshal(b, &rls); err != nil {
return nil, err
}
return &rls, nil
}
|
package MySQL
import (
"AlgorithmPractice/src/common/Intergration/DB"
_ "github.com/go-sql-driver/mysql" // go grammar:在使用的地方需要隐式用到,不写会报错:err:sql: unknown driver "mysql" (forgotten import?)
"testing"
)
func TestNewDBMysqlCluster(t *testing.T) {
db := GetDBMysqlCluster()
df, _ := db.ExecQuery("DigitalTrans")
for _, entity := range df {
entity.Print()
}
}
func TestExecInsert(t *testing.T) {
db := GetDBMysqlCluster()
input := "input"
output := "output"
class_name := "class_name1"
db.ExecInsert(&DB.SQLTestDataEntity{
Input: &input,
Output: &output,
ClassName: &class_name,
InputDesc: nil,
OutputDesc: nil,
ClassDescribe: nil,
})
}
|
/*
Copyright 2021 The Skaffold 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, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package inspect
import (
"context"
"io"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/config"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/inspect"
"github.com/GoogleContainerTools/skaffold/v2/pkg/skaffold/util"
)
func ModifyGcbBuildEnv(ctx context.Context, out io.Writer, opts inspect.Options) error {
formatter := inspect.OutputFormatter(out, opts.OutFormat)
cfgs, err := inspect.GetConfigSet(ctx, config.SkaffoldOptions{ConfigurationFile: opts.Filename, ConfigurationFilter: opts.Modules, SkipConfigDefaults: true, MakePathsAbsolute: util.Ptr(false)})
if err != nil {
formatter.WriteErr(err)
return err
}
if opts.Profile == "" {
// empty profile flag implies that only modify the default pipelines in the target `skaffold.yaml`
cfgs = cfgs.SelectRootConfigs()
for _, cfg := range cfgs {
if cfg.Build.GoogleCloudBuild == nil {
if opts.Strict {
formatter.WriteErr(inspect.BuildEnvNotFound(inspect.BuildEnvs.GoogleCloudBuild, cfg.SourceFile, ""))
return err
}
continue
}
cfg.Build.GoogleCloudBuild = constructGcbDefinition(cfg.Build.GoogleCloudBuild, opts.BuildEnvOptions)
cfg.Build.LocalBuild = nil
cfg.Build.Cluster = nil
}
} else {
profileFound := false
for _, cfg := range cfgs {
index := -1
for i := range cfg.Profiles {
if cfg.Profiles[i].Name == opts.Profile {
index = i
break
}
}
if index < 0 {
continue
}
profileFound = true
if cfg.Profiles[index].Build.GoogleCloudBuild == nil {
if opts.Strict {
formatter.WriteErr(inspect.BuildEnvNotFound(inspect.BuildEnvs.GoogleCloudBuild, cfg.SourceFile, opts.Profile))
return err
}
continue
}
cfg.Profiles[index].Build.GoogleCloudBuild = constructGcbDefinition(cfg.Profiles[index].Build.GoogleCloudBuild, opts.BuildEnvOptions)
cfg.Profiles[index].Build.LocalBuild = nil
cfg.Profiles[index].Build.Cluster = nil
}
if !profileFound {
formatter.WriteErr(inspect.ProfileNotFound(opts.Profile))
return err
}
}
return inspect.MarshalConfigSet(cfgs)
}
|
package knowledge
import "testing"
func TestRegion(t *testing.T) {
const (
operationUnit PartyType = PartyType(1)
region PartyType = PartyType(2)
division PartyType = PartyType(3)
salesOffice PartyType = PartyType(4)
)
// commissionerになれるPartyType
commissioners := PartyTypes{operationUnit, region, division}
// responsibleになれるPartyType
responsibles := PartyTypes{region, division, salesOffice}
var (
salesOperation Party = Party{partyType: operationUnit}
productOperation Party = Party{partyType: operationUnit}
kanto Party = Party{partyType: region}
todaSalesOffice Party = Party{partyType: salesOffice}
)
regionStruct := AccountabilityType{commissioners, responsibles}
if regionStruct.IsSatisfiedWith(salesOperation, kanto) {
t.Log("salesOperationはcommisionerになれる, kantoはresponsibleになれる")
}
if !regionStruct.IsSatisfiedWith(todaSalesOffice, kanto) {
t.Log("todaSalesOfficeはcommisionerになれない")
}
if !regionStruct.IsSatisfiedWith(kanto, productOperation) {
t.Log("productOperationはresponsibleになれない")
}
// この構造では階層構造などの制約は実現できない(もっと詳細なモデルが必要)
}
|
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func shortestRep(q string) int {
r := 1
for i := 1; i < len(q); i++ {
if q[i] != q[i-r] {
r = i + 1
}
}
return r
}
func main() {
data, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer data.Close()
scanner := bufio.NewScanner(data)
for scanner.Scan() {
fmt.Println(shortestRep(scanner.Text()))
}
}
|
package to_test
import (
"testing"
"time"
"github.com/shandysiswandi/echo-service/pkg/to"
"github.com/stretchr/testify/assert"
)
func TestCurrentTimezone(t *testing.T) {
utc := time.Now().UTC()
act := to.CurrentTimezone("Asia/Jakarta", utc)
assert.NotEqual(t, utc, act)
act = to.CurrentTimezone("Asi/Jakarta", utc)
assert.Equal(t, utc, act)
}
|
package arbitration
import "github.com/go-trading/lightning/core"
func (b *Bot) onStatusChange(symbol *core.Symbol, status core.SymbolStatus) {
log.Errorf("TODO new status for %v is %v", symbol.Name(), status)
return
}
|
package converter
import (
"github.com/koki/short/converter/converters"
"github.com/koki/short/types"
serrors "github.com/koki/structurederrors"
admissionregv1alpha1 "k8s.io/api/admissionregistration/v1alpha1"
admissionregv1beta1 "k8s.io/api/admissionregistration/v1beta1"
apps "k8s.io/api/apps/v1"
appsv1beta1 "k8s.io/api/apps/v1beta1"
appsv1beta2 "k8s.io/api/apps/v1beta2"
autoscaling "k8s.io/api/autoscaling/v1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
batchv2alpha1 "k8s.io/api/batch/v2alpha1"
certificatesv1beta1 "k8s.io/api/certificates/v1beta1"
"k8s.io/api/core/v1"
exts "k8s.io/api/extensions/v1beta1"
policyv1beta1 "k8s.io/api/policy/v1beta1"
rbac "k8s.io/api/rbac/v1"
schedulingv1alpha1 "k8s.io/api/scheduling/v1alpha1"
settingsv1alpha1 "k8s.io/api/settings/v1alpha1"
storagev1 "k8s.io/api/storage/v1"
storagev1beta1 "k8s.io/api/storage/v1beta1"
apiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
apiregistrationv1beta1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
)
func DetectAndConvertFromKokiObj(kokiObj interface{}) (interface{}, error) {
switch kokiObj := kokiObj.(type) {
case *types.APIServiceWrapper:
return converters.Convert_Koki_APIService_to_Kube_APIService(kokiObj)
case *types.BindingWrapper:
return converters.Convert_Koki_Binding_to_Kube_Binding(kokiObj)
case *types.CertificateSigningRequestWrapper:
return converters.Convert_Koki_CSR_to_Kube_CSR(kokiObj)
case *types.ClusterRoleWrapper:
return converters.Convert_Koki_ClusterRole_to_Kube(kokiObj)
case *types.ClusterRoleBindingWrapper:
return converters.Convert_Koki_ClusterRoleBinding_to_Kube(kokiObj)
case *types.ConfigMapWrapper:
return converters.Convert_Koki_ConfigMap_to_Kube_v1_ConfigMap(kokiObj)
case *types.ControllerRevisionWrapper:
return converters.Convert_Koki_ControllerRevision_to_Kube(kokiObj)
case *types.CronJobWrapper:
return converters.Convert_Koki_CronJob_to_Kube_CronJob(kokiObj)
case *types.CRDWrapper:
return converters.Convert_Koki_CRD_to_Kube(kokiObj)
case *types.DaemonSetWrapper:
return converters.Convert_Koki_DaemonSet_to_Kube_DaemonSet(kokiObj)
case *types.DeploymentWrapper:
return converters.Convert_Koki_Deployment_to_Kube_Deployment(kokiObj)
case *types.EndpointsWrapper:
return converters.Convert_Koki_Endpoints_to_Kube_v1_Endpoints(kokiObj)
case *types.EventWrapper:
return converters.Convert_Koki_Event_to_Kube(kokiObj)
case *types.HorizontalPodAutoscalerWrapper:
return converters.Convert_Koki_HPA_to_Kube(kokiObj)
case *types.IngressWrapper:
return converters.Convert_Koki_Ingress_to_Kube_Ingress(kokiObj)
case *types.InitializerConfigWrapper:
return converters.Convert_Koki_InitializerConfig_to_Kube_InitializerConfig(kokiObj)
case *types.JobWrapper:
return converters.Convert_Koki_Job_to_Kube_Job(kokiObj)
case *types.LimitRangeWrapper:
return converters.Convert_Koki_LimitRange_to_Kube(kokiObj)
case *types.NamespaceWrapper:
return converters.Convert_Koki_Namespace_to_Kube_Namespace(kokiObj)
case *types.PersistentVolumeClaimWrapper:
return converters.Convert_Koki_PVC_to_Kube_PVC(kokiObj)
case *types.PersistentVolumeWrapper:
return converters.Convert_Koki_PersistentVolume_to_Kube_v1_PersistentVolume(kokiObj)
case *types.PodDisruptionBudgetWrapper:
return converters.Convert_Koki_PodDisruptionBudget_to_Kube_PodDisruptionBudget(kokiObj)
case *types.PodPresetWrapper:
return converters.Convert_Koki_PodPreset_to_Kube_PodPreset(kokiObj)
case *types.PodSecurityPolicyWrapper:
return converters.Convert_Koki_PodSecurityPolicy_to_Kube_PodSecurityPolicy(kokiObj)
case *types.PodTemplateWrapper:
return converters.Convert_Koki_PodTemplate_to_Kube(kokiObj)
case *types.PodWrapper:
return converters.Convert_Koki_Pod_to_Kube_v1_Pod(kokiObj)
case *types.PriorityClassWrapper:
return converters.Convert_Koki_PriorityClass_to_Kube_PriorityClass(kokiObj)
case *types.ReplicationControllerWrapper:
return converters.Convert_Koki_ReplicationController_to_Kube_v1_ReplicationController(kokiObj)
case *types.ReplicaSetWrapper:
return converters.Convert_Koki_ReplicaSet_to_Kube_ReplicaSet(kokiObj)
case *types.SecretWrapper:
return converters.Convert_Koki_Secret_to_Kube_v1_Secret(kokiObj)
case *types.ServiceWrapper:
return converters.Convert_Koki_Service_To_Kube_v1_Service(kokiObj)
case *types.ServiceAccountWrapper:
return converters.Convert_Koki_ServiceAccount_to_Kube_ServiceAccount(kokiObj)
case *types.StatefulSetWrapper:
return converters.Convert_Koki_StatefulSet_to_Kube_StatefulSet(kokiObj)
case *types.StorageClassWrapper:
return converters.Convert_Koki_StorageClass_to_Kube_StorageClass(kokiObj)
case *types.VolumeWrapper:
return &kokiObj.Volume, nil
case *types.MutatingWebhookConfigWrapper:
return converters.Convert_Koki_WebhookConfiguration_to_Kube_WebhookConfiguration(kokiObj, "MutatingWebhookConfiguration")
case *types.ValidatingWebhookConfigWrapper:
return converters.Convert_Koki_WebhookConfiguration_to_Kube_WebhookConfiguration(kokiObj, "ValidatingWebhookConfiguration")
default:
return nil, serrors.TypeErrorf(kokiObj, "can't convert from unsupported koki type")
}
}
func DetectAndConvertFromKubeObj(kubeObj runtime.Object) (interface{}, error) {
switch kubeObj := kubeObj.(type) {
case *apiregistrationv1beta1.APIService:
return converters.Convert_Kube_APIService_to_Koki_APIService(kubeObj)
case *v1.Binding:
return converters.Convert_Kube_Binding_to_Koki_Binding(kubeObj)
case *certificatesv1beta1.CertificateSigningRequest:
return converters.Convert_Kube_CSR_to_Koki_CSR(kubeObj)
case *rbac.ClusterRole:
return converters.Convert_Kube_ClusterRole_to_Koki(kubeObj)
case *rbac.ClusterRoleBinding:
return converters.Convert_Kube_ClusterRoleBinding_to_Koki(kubeObj)
case *v1.ConfigMap:
return converters.Convert_Kube_v1_ConfigMap_to_Koki_ConfigMap(kubeObj)
case *apps.ControllerRevision, *appsv1beta1.ControllerRevision, *appsv1beta2.ControllerRevision:
return converters.Convert_Kube_ControllerRevision_to_Koki(kubeObj)
case *batchv1beta1.CronJob, *batchv2alpha1.CronJob:
return converters.Convert_Kube_CronJob_to_Koki_CronJob(kubeObj)
case *apiext.CustomResourceDefinition:
return converters.Convert_Kube_CRD_to_Koki(kubeObj)
case *appsv1beta2.DaemonSet, *exts.DaemonSet:
return converters.Convert_Kube_DaemonSet_to_Koki_DaemonSet(kubeObj)
case *appsv1beta1.Deployment, *appsv1beta2.Deployment, *exts.Deployment:
return converters.Convert_Kube_Deployment_to_Koki_Deployment(kubeObj)
case *v1.Endpoints:
return converters.Convert_Kube_v1_Endpoints_to_Koki_Endpoints(kubeObj)
case *v1.Event:
return converters.Convert_Kube_Event_to_Koki(kubeObj)
case *autoscaling.HorizontalPodAutoscaler:
return converters.Convert_Kube_HPA_to_Koki(kubeObj)
case *exts.Ingress:
return converters.Convert_Kube_Ingress_to_Koki_Ingress(kubeObj)
case *admissionregv1alpha1.InitializerConfiguration:
return converters.Convert_Kube_InitializerConfig_to_Koki_InitializerConfig(kubeObj)
case *batchv1.Job:
return converters.Convert_Kube_Job_to_Koki_Job(kubeObj)
case *v1.LimitRange:
return converters.Convert_Kube_LimitRange_to_Koki(kubeObj)
case *v1.Namespace:
return converters.Convert_Kube_Namespace_to_Koki_Namespace(kubeObj)
case *v1.PersistentVolume:
return converters.Convert_Kube_v1_PersistentVolume_to_Koki_PersistentVolume(kubeObj)
case *v1.PersistentVolumeClaim:
return converters.Convert_Kube_PVC_to_Koki_PVC(kubeObj)
case *schedulingv1alpha1.PriorityClass:
return converters.Convert_Kube_PriorityClass_to_Koki_PriorityClass(kubeObj)
case *v1.Pod:
return converters.Convert_Kube_v1_Pod_to_Koki_Pod(kubeObj)
case *policyv1beta1.PodDisruptionBudget:
return converters.Convert_Kube_PodDisruptionBudget_to_Koki_PodDisruptionBudget(kubeObj)
case *settingsv1alpha1.PodPreset:
return converters.Convert_Kube_PodPreset_to_Koki_PodPreset(kubeObj)
case *exts.PodSecurityPolicy:
return converters.Convert_Kube_PodSecurityPolicy_to_Koki_PodSecurityPolicy(kubeObj)
case *v1.PodTemplate:
return converters.Convert_Kube_PodTemplate_to_Koki(kubeObj)
case *v1.ReplicationController:
return converters.Convert_Kube_v1_ReplicationController_to_Koki_ReplicationController(kubeObj)
case *appsv1beta2.ReplicaSet, *exts.ReplicaSet:
return converters.Convert_Kube_ReplicaSet_to_Koki_ReplicaSet(kubeObj)
case *v1.Secret:
return converters.Convert_Kube_v1_Secret_to_Koki_Secret(kubeObj)
case *v1.Service:
return converters.Convert_Kube_v1_Service_to_Koki_Service(kubeObj)
case *v1.ServiceAccount:
return converters.Convert_Kube_ServiceAccount_to_Koki_ServiceAccount(kubeObj)
case *appsv1beta1.StatefulSet, *appsv1beta2.StatefulSet:
return converters.Convert_Kube_StatefulSet_to_Koki_StatefulSet(kubeObj)
case *storagev1.StorageClass, *storagev1beta1.StorageClass:
return converters.Convert_Kube_StorageClass_to_Koki_StorageClass(kubeObj)
case *admissionregv1beta1.MutatingWebhookConfiguration:
return converters.Convert_Kube_WebhookConfiguration_to_Koki_WebhookConfiguration(kubeObj, types.MutatingKind)
case *admissionregv1beta1.ValidatingWebhookConfiguration:
return converters.Convert_Kube_WebhookConfiguration_to_Koki_WebhookConfiguration(kubeObj, types.ValidatingKind)
default:
return nil, serrors.TypeErrorf(kubeObj, "can't convert from unsupported kube type")
}
}
|
package hosts
import (
"github.com/jrapoport/gothic/core"
"github.com/jrapoport/gothic/hosts/rpc"
"github.com/jrapoport/gothic/hosts/rpc/account"
"github.com/jrapoport/gothic/hosts/rpc/health"
"github.com/jrapoport/gothic/hosts/rpc/user"
)
const rpcWebName = "rpc-web"
// NewRPCWebHost creates a new rpc host.
func NewRPCWebHost(a *core.API, address string) core.Hosted {
return rpc.NewHost(a, rpcWebName, address,
[]rpc.RegisterServer{
health.RegisterServer,
user.RegisterServer,
account.RegisterServer,
}, rpc.Authentication())
}
|
package main
import (
"errors"
"fmt"
"os"
)
func main() {
f, err := os.Open("file.txt")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(f)
}
// Custom errors
myError := errors.New("new error")
fmt.Println(myError)
attendance := map[string]bool{
"AAA": true,
"BBB": true}
attended, ok := attendance["AAA"] // Also know as - comma ok
if ok {
fmt.Println("AAA attended?", attended)
} else {
fmt.Println("No info for AAA.")
}
attended1, ok1 := attendance["CCC"]
if ok1 {
fmt.Println("AAA attended?", attended1)
} else {
fmt.Println("No info for CCC.")
}
}
|
package main
import (
"fmt"
balancer "github.com/fufuok/load-balancer"
)
func main() {
var choices []*balancer.Choice
// for RoundRobin/Random/ConsistentHash
nodes := []string{"A", "B", "C"}
choices = balancer.NewChoicesSlice(nodes)
// or
// choices = []*balancer.Choice{
// {Item: "A"},
// {Item: "B"},
// {Item: "C"},
// }
var lb balancer.Balancer
lb = balancer.New(balancer.ConsistentHash, choices)
// or
// lb = balancer.New(balancer.ConsistentHash, nil)
// lb.Update(choices)
// or
// lb = balancer.NewConsistentHash(choices...)
// or
// lb = balancer.NewConsistentHash()
// lb.Update(choices)
fmt.Println("balancer name:", lb.Name())
// C C C C C
for i := 0; i < 5; i++ {
fmt.Print(lb.Select("192.168.1.1"), " ")
}
fmt.Println()
}
|
package dbs
import (
"fmt"
"log"
"strconv"
"database/sql"
_ "github.com/lib/pq"
)
type Machine struct {
Id string
Nam string
Cpu string
Mem int
}
func dbConnectTest() (string){
return "user=postgres password=1111 dbname=postgres sslmode=disable"
}
func dbConnect(user string,password string,dbname string,sslmode string) (string){
res :="user="+user+" password="+password+" dbname="+dbname+" sslmode="+sslmode
return res
}
func DbOpen() (*sql.DB/*, error*/) {
str :=dbConnect("postgres","1111","postgres","disable")
fmt.Println(str)
sq, err := sql.Open("postgres", str)
if err != nil {
log.Fatal(err)
}
fmt.Println("opened")
return sq/*, err*/
}
func DbGetId(sq *sql.DB)([]int){
resul, err := sq.Query("SELECT COUNT(*) FROM machines")
if err != nil {
panic(err)
}
resul.Next()
var resl string
err1 := resul.Scan(&resl)
if err1 != nil {
panic(err1)
}
rnum,errr := strconv.Atoi(resl)
if errr != nil {
panic(errr)
}
idstr := make([]string,rnum)
ids := make([]int,rnum)
row,err2 := sq.Query("SELECT id FROM machines")
if err2 != nil {
panic(err2)
}
var i int = 0
for row.Next() {
err := row.Scan(&idstr[i])
if err != nil {
if err == sql.ErrNoRows {
fmt.Println("Zero rows found")
} else {
panic(err)
}
}
ids[i],_=strconv.Atoi(idstr[i])
i++
}
return ids
}
func DbQuery(sq *sql.DB)([]Machine){
resul, err := sq.Query("SELECT COUNT(*) FROM machines")
if err != nil {
panic(err)
}
resul.Next()
var resl string
err1 := resul.Scan(&resl)
if err1 != nil {
panic(err1)
}
rnum,errr := strconv.Atoi(resl)
if errr != nil {
panic(errr)
}
machines := make([]Machine,rnum)
row,err2 := sq.Query("SELECT * FROM machines")
if err2 != nil {
panic(err2)
}
var i int = 0
for row.Next() {
err := row.Scan(&machines[i].Id, &machines[i].Nam, &machines[i].Cpu)
if err != nil {
if err == sql.ErrNoRows {
fmt.Println("Zero rows found")
} else {
panic(err)
}
}
drw,err1 := sq.Query("SELECT memory FROM disks WHERE cid=$1 ",machines[i].Id)
if err1 != nil {
panic(err1)
}
for drw.Next() {
var mem string
var intmem int
err3 := drw.Scan(&mem)
if err3 != nil {panic(err3)}
intmem,_ = strconv.Atoi(mem)
machines[i].Mem += intmem
}
i++
}
return machines
}
func DbInsert(sq *sql.DB,mem int, cid int){
_, err := sq.Exec("INSERT INTO disks(memory,cid) VALUES ($1,$2)", mem, cid)
if err != nil {
panic(err)
}
fmt.Println("Succesfull")
} |
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
type FlagData struct {
Username string
Flag string
Readonly bool
}
var globalDB *sql.DB
const sqliteTest = "/tmp/flagsrv.db3"
const mysqlEnv = "MYSQL_DB"
type LoginResult int
const (
LoginFailed LoginResult = iota
LoginSuccess
LoginNeedsMFA
)
func getDB() (*sql.DB, error) {
if globalDB != nil {
return globalDB, nil
}
if _, err := os.Stat(sqliteTest); err == nil {
db, err := sql.Open("sqlite3", sqliteTest)
if err != nil {
return nil, err
}
globalDB = db
} else {
db, err := sql.Open("mysql", os.Getenv(mysqlEnv))
if err != nil {
return nil, err
}
globalDB = db
}
if err := globalDB.Ping(); err != nil {
return nil, err
}
return globalDB, nil
}
func mustGetDB() *sql.DB {
db, err := getDB()
if err != nil {
log.Fatalf("Error connecting to database: %s", err)
}
return db
}
func verifyUsernamePassword(username, password string) LoginResult {
db := mustGetDB()
qry := `SELECT username,twofactor FROM users WHERE username = ? AND password = ?;`
if rows, err := db.Query(qry, username, password); err != nil {
log.Printf("Error verifying username/password: %s", err)
return LoginFailed
} else {
defer rows.Close()
if !rows.Next() {
return LoginFailed
}
var ret_username string
var twofactor int
if err := rows.Scan(&ret_username, &twofactor); err != nil {
log.Printf("Error scanning username/password: %s", err)
return LoginFailed
}
if ret_username != username {
log.Printf("Username mismatch!? %s vs %s", username, ret_username)
return LoginFailed
}
if twofactor > 0 {
return LoginNeedsMFA
}
return LoginSuccess
}
}
func getFlagDataForUser(username string) *FlagData {
db := mustGetDB()
qry := `SELECT flag, readonly FROM users WHERE username = ?;`
if rows, err := db.Query(qry, username); err != nil {
log.Printf("Error querying for flag: %s", err)
return nil
} else {
defer rows.Close()
if !rows.Next() {
return nil
}
var flag sql.NullString
var readonly sql.NullInt64
if err := rows.Scan(&flag, &readonly); err != nil {
log.Printf("Error scanning flag/readonly: %s", err)
return nil
}
fd := &FlagData{
Flag: flag.String,
Username: username,
}
if readonly.Valid && readonly.Int64 == 1 {
fd.Readonly = true
}
return fd
}
}
func (fd *FlagData) Save() error {
db := mustGetDB()
if fd.Readonly {
return fmt.Errorf("Attempt to save readonly flagdata!")
}
qry := `UPDATE users SET flag=? WHERE username=?;`
if _, err := db.Exec(qry, fd.Flag, fd.Username); err != nil {
log.Printf("Error updating flag: %s", err)
return err
}
return nil
}
func dbRegister(username, password string) error {
db := mustGetDB()
qry := `INSERT INTO users(username, password, twofactor) VALUES(?, ?, 0);`
if _, err := db.Exec(qry, username, password); err != nil {
log.Printf("Error registering new user: %s", err)
// TODO: return a more friendly error
return err
}
return nil
}
func dbEnroll2FA(username string) error {
db := mustGetDB()
qry := `UPDATE users SET twofactor=1 WHERE username=?;`
if _, err := db.Exec(qry, username); err != nil {
log.Printf("Error enable 2FA: %s", err)
return err
}
return nil
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package k8s
import (
"context"
"encoding/json"
"time"
"github.com/pkg/errors"
monitoringV1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
mmv1alpha1 "github.com/mattermost/mattermost-operator/apis/mattermost/v1alpha1"
apixv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apixv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
func (kc *KubeClient) createOrUpdateCustomResourceDefinitionBetaV1(crd *apixv1beta1.CustomResourceDefinition) (metav1.Object, error) {
ctx := context.TODO()
oldCRD, err := kc.ApixClientset.ApiextensionsV1beta1().CustomResourceDefinitions().Get(ctx, crd.GetName(), metav1.GetOptions{})
if err != nil && !k8sErrors.IsNotFound(err) {
return nil, err
}
if err != nil && k8sErrors.IsNotFound(err) {
return kc.ApixClientset.ApiextensionsV1beta1().CustomResourceDefinitions().Create(ctx, crd, metav1.CreateOptions{})
}
crd.ResourceVersion = oldCRD.ResourceVersion
return kc.ApixClientset.ApiextensionsV1beta1().CustomResourceDefinitions().Update(ctx, crd, metav1.UpdateOptions{})
}
func (kc *KubeClient) createOrUpdateCustomResourceDefinitionV1(crd *apixv1.CustomResourceDefinition) (metav1.Object, error) {
ctx := context.TODO()
oldCRD, err := kc.ApixClientset.ApiextensionsV1().CustomResourceDefinitions().Get(ctx, crd.GetName(), metav1.GetOptions{})
if err != nil && !k8sErrors.IsNotFound(err) {
return nil, err
}
if err != nil && k8sErrors.IsNotFound(err) {
return kc.ApixClientset.ApiextensionsV1().CustomResourceDefinitions().Create(ctx, crd, metav1.CreateOptions{})
}
crd.ResourceVersion = oldCRD.ResourceVersion
return kc.ApixClientset.ApiextensionsV1().CustomResourceDefinitions().Update(ctx, crd, metav1.UpdateOptions{})
}
func (kc *KubeClient) createOrUpdateClusterInstallation(namespace string, ci *mmv1alpha1.ClusterInstallation) (metav1.Object, error) {
ctx := context.TODO()
_, err := kc.MattermostClientsetV1Alpha.MattermostV1alpha1().ClusterInstallations(namespace).Get(ctx, ci.GetName(), metav1.GetOptions{})
if err != nil && !k8sErrors.IsNotFound(err) {
return nil, err
}
if err != nil && k8sErrors.IsNotFound(err) {
return kc.MattermostClientsetV1Alpha.MattermostV1alpha1().ClusterInstallations(namespace).Create(ctx, ci, metav1.CreateOptions{})
}
return kc.MattermostClientsetV1Alpha.MattermostV1alpha1().ClusterInstallations(namespace).Update(ctx, ci, metav1.UpdateOptions{})
}
func (kc *KubeClient) createOrUpdatePodMonitor(namespace string, pm *monitoringV1.PodMonitor) (metav1.Object, error) {
wait := 60
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(wait)*time.Second)
defer cancel()
_, err := kc.MonitoringClientsetV1.MonitoringV1().PodMonitors(namespace).Get(ctx, pm.GetName(), metav1.GetOptions{})
if err != nil && !k8sErrors.IsNotFound(err) {
return nil, err
}
if err != nil && k8sErrors.IsNotFound(err) {
return kc.MonitoringClientsetV1.MonitoringV1().PodMonitors(namespace).Create(ctx, pm, metav1.CreateOptions{})
}
patch, err := json.Marshal(pm)
if err != nil {
return nil, errors.Wrap(err, "could not marshal new Pod Monitor")
}
return kc.MonitoringClientsetV1.MonitoringV1().PodMonitors(namespace).Patch(ctx, pm.GetName(), types.MergePatchType, patch, metav1.PatchOptions{})
}
|
package web
import (
"text/template"
)
type Document struct {
Close bool //关闭文档
GenerateHtml bool //生成Html
Static string
Theme string
Attr map[string]string
Css map[string]string
Js map[string]string
Img map[string]string
CssPath string //当前view对应的css目录
JsPath string //当前view对应的Js目录
ImgPath string //当前view对应的Img目录
GlobalCssFile string
GlobalJsFile string
GlobalIndexCssFile string
GlobalIndexJsFile string
IndexCssFile string
IndexJsFile string
Hide bool //是否渲染模板
Func template.FuncMap
Title string
Body interface{}
}
|
package main
type ListNode struct {
Val int
Next *ListNode
}
///////////////////// 使用转换成切片的方式 ///////////////////////////////
func isPalindrome(head *ListNode) bool {
vallist := []int{}
for head != nil {
//把链表转换成切片
vallist = append(vallist, head.Val)
head = head.Next
}
n := len(vallist)
//使用双指针法判断是否为回文
for i, v := range vallist[:n/2] {
if v != vallist[n-1-i] {
return false
}
}
return true
}
///////////////////// 使用快慢指针 /////////////////////////////////////
func isPalindrome2(head *ListNode) bool {
if head == nil || head.Next == nil {
return true
}
fast, slow := head, head
var prev *ListNode = nil
for fast != nil && fast.Next != nil {
prev = slow
slow = slow.Next
fast = fast.Next.Next
}
//把slow慢指针断开
prev.Next = nil
// 翻转
var head2 *ListNode = nil
for slow != nil {
tmp := slow.Next
slow.Next = head2
head2 = slow
slow = tmp
}
// 对比
for head != nil && head2 != nil {
if head.Val != head2.Val {
return false
}
head = head.Next
head2 = head2.Next
}
return true
}
|
package control
import (
"fmt"
_ "github.com/et-zone/embi/dao"
"github.com/et-zone/embi/model"
"github.com/gin-gonic/gin"
)
func TPost(c *gin.Context) {
t := &model.ETarget{}
err := c.Bind(t)
if err != nil {
fmt.Println(err.Error())
c.JSON(200, gin.H{
"message": "ok",
})
return
}
// err = dao.InsertEtarget(t)
// if err != nil {
// fmt.Println(err.Error())
// }
c.JSON(200, gin.H{
"message": "ok",
})
return
}
func TGet(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
}
|
package requests
import (
"encoding/json"
"fmt"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
)
// SelectMasteryPath Select a mastery path when module item includes several possible paths.
// Requires Mastery Paths feature to be enabled. Returns a compound document
// with the assignments included in the given path and any module items
// related to those assignments
// https://canvas.instructure.com/doc/api/modules.html
//
// Path Parameters:
// # Path.CourseID (Required) ID
// # Path.ModuleID (Required) ID
// # Path.ID (Required) ID
//
// Form Parameters:
// # Form.AssignmentSetID (Optional) Assignment set chosen, as specified in the mastery_paths portion of the
// context module item response
// # Form.StudentID (Optional) Which student the selection applies to. If not specified, current user is
// implied.
//
type SelectMasteryPath struct {
Path struct {
CourseID string `json:"course_id" url:"course_id,omitempty"` // (Required)
ModuleID string `json:"module_id" url:"module_id,omitempty"` // (Required)
ID string `json:"id" url:"id,omitempty"` // (Required)
} `json:"path"`
Form struct {
AssignmentSetID string `json:"assignment_set_id" url:"assignment_set_id,omitempty"` // (Optional)
StudentID string `json:"student_id" url:"student_id,omitempty"` // (Optional)
} `json:"form"`
}
func (t *SelectMasteryPath) GetMethod() string {
return "POST"
}
func (t *SelectMasteryPath) GetURLPath() string {
path := "courses/{course_id}/modules/{module_id}/items/{id}/select_mastery_path"
path = strings.ReplaceAll(path, "{course_id}", fmt.Sprintf("%v", t.Path.CourseID))
path = strings.ReplaceAll(path, "{module_id}", fmt.Sprintf("%v", t.Path.ModuleID))
path = strings.ReplaceAll(path, "{id}", fmt.Sprintf("%v", t.Path.ID))
return path
}
func (t *SelectMasteryPath) GetQuery() (string, error) {
return "", nil
}
func (t *SelectMasteryPath) GetBody() (url.Values, error) {
return query.Values(t.Form)
}
func (t *SelectMasteryPath) GetJSON() ([]byte, error) {
j, err := json.Marshal(t.Form)
if err != nil {
return nil, nil
}
return j, nil
}
func (t *SelectMasteryPath) HasErrors() error {
errs := []string{}
if t.Path.CourseID == "" {
errs = append(errs, "'Path.CourseID' is required")
}
if t.Path.ModuleID == "" {
errs = append(errs, "'Path.ModuleID' is required")
}
if t.Path.ID == "" {
errs = append(errs, "'Path.ID' is required")
}
if len(errs) > 0 {
return fmt.Errorf(strings.Join(errs, ", "))
}
return nil
}
func (t *SelectMasteryPath) Do(c *canvasapi.Canvas) error {
_, err := c.SendRequest(t)
if err != nil {
return err
}
return nil
}
|
package main
import (
"github.com/sadasant/scripts/go/euler/euler"
"sort"
"strings"
)
func solution(file string) (total int) {
lines := strings.Split(file, ",")
sort.Strings(lines)
lower_limit := 64
for k, v := range lines {
worth := 0
// euler.Printf("%v %v ", k, v)
for _, _v := range v {
i_v := int(_v)
if i_v > lower_limit {
// euler.Printf("%s=%v ", string(_v), i_v - lower_limit)
worth += i_v - lower_limit
}
}
total += (k+1) * worth
// euler.Printf("\n")
}
return
}
func main() {
euler.Init(22, "What is the total of all the name scores in the file?")
euler.PrintTime("For COLIN | Result: %v, Nanoseconds: %d\n", solution, "COLIN")
euler.PrintTime("For the file | Result: %v, Nanoseconds: %d\n", solution, euler.Download("https://projecteuler.net/project/names.txt"))
}
|
package main
import (
"net"
"net/http"
"strings"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func RemoteAddress(c echo.Context) string {
AddressAndPort := strings.Split(c.Request().RemoteAddr, ":")
Address := AddressAndPort[0]
return Address
}
func ShowIP(c echo.Context) error {
Address := RemoteAddress(c)
return c.String(http.StatusOK, Address)
}
func ReverseDNS(c echo.Context) error {
Address := RemoteAddress(c)
Hostnames, err := net.LookupAddr(Address)
if err != nil {
return c.String(http.StatusNotFound, "Unable perform reverse DNS search for address " + Address)
}
HostnameString := strings.Join(Hostnames, "\n")
return c.String(http.StatusOK, HostnameString)
}
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.GET("/rdns*", ReverseDNS)
e.GET("/*", ShowIP)
e.Logger.Fatal(e.Start(":8081"))
}
|
package models
import(
"errors"
"github.com/tawfeeq0/auth_server/security"
)
type SdbUser struct{
Name string `json:"Description"`
BadgeNo string `json:"Name"`
Categories []string `json:"CategoryNames"`
}
func (user SdbUser) SignToken() (string, error) {
if user.BadgeNo != "" && len(user.Categories) >0 {
return security.CreateToken(user.BadgeNo,user.Categories)
} else {
return "", errors.New("Either use dones't have access or doesn't have AOR assigned ")
}
} |
package main
import (
"os"
"strings"
"github.com/jinzhu/configor"
)
type Config struct {
Server struct {
Address string `toml:"address" required:"true"`
Username string `toml:"username" required:"true"`
Password string `toml:"password" required:"true"`
} `toml:"server"`
Session struct {
Path string `toml:"path"`
} `toml:"session"`
}
func NewConfig(path string) (*Config, error) {
config := &Config{}
err := configor.Load(config, path)
if err != nil {
return nil, err
}
if strings.HasPrefix(config.Session.Path, "~/") {
config.Session.Path = os.Getenv("HOME") + "/" +
strings.TrimPrefix(config.Session.Path, "~/")
}
return config, nil
}
|
package main
import (
"fmt"
"time"
"cards"
"engine"
"engine/graphics"
)
func main() {
graphics := graphics.InitCanvasGraphics()
fmt.Println("Loading image...")
image := graphics.LoadImage("cards.png")
go (func() {
for !image.Loaded() {
time.Sleep(50)
}
fmt.Println("Images loaded.")
draw(graphics, image)
})()
select {}
}
func draw(graphics graphics.GraphicsContext, image graphics.Image) {
graphics.FillRect(engine.Rectangle{X: 0, Y: 0, Width: 1024, Height: 768}, engine.Color{R: 0, G: 0, B: 0, A: 255})
graphics.FillRect(engine.Rectangle{X: 10, Y: 10, Width: 100, Height: 100}, engine.Color{R: 255, G: 0, B: 0, A: 255})
graphics.FillRect(engine.Rectangle{X: 110, Y: 110, Width: 100, Height: 100}, engine.Color{R: 0, G: 0, B: 255, A: 255})
rect := cards.CardImageRectangles[cards.Card{Suit: cards.Hearts, Value: cards.Three}]
graphics.DrawSprite(image, engine.Rectangle(rect), engine.Rectangle{X: 0, Y: 0, Width: rect.Width, Height: rect.Height})
}
|
package gotun2socks
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/elazarl/goproxy"
"github.com/inconshreveable/go-vhost"
)
//import _ "net/http/pprof"
var (
proxy *goproxy.ProxyHttpServer
server *http.Server
)
func initGoProxy() {
//fd, _ := os.Create("err.txt")
//redirectStderr(fd)
proxy = goproxy.NewProxyHttpServer()
proxy.Verbose = false
proxy.NonproxyHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Host == "" {
fmt.Fprintln(w, "Cannot handle requests without Host header, e.g., HTTP 1.0")
return
}
req.URL.Scheme = "http"
req.URL.Host = req.Host
proxy.ServeHTTP(w, req)
})
//proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm)
}
func dialRemote(req *http.Request) net.Conn {
port := ""
if !strings.Contains(req.Host, ":") {
if req.URL.Scheme == "https" {
port = ":443"
} else {
port = ":80"
}
}
if req.URL.Scheme == "https" {
conf := tls.Config{
//InsecureSkipVerify: true,
}
remote, err := tls.Dial("tcp", req.Host+port, &conf)
if err != nil {
log.Printf("Websocket error connect %s", err)
return nil
}
return remote
} else {
remote, err := net.Dial("tcp", req.Host+port)
if err != nil {
log.Printf("Websocket error connect %s", err)
return nil
}
return remote
}
}
func startHttpsServer() {
// listen to the TLS ClientHello but make it a CONNECT request instead
ln, err := net.Listen("tcp", ":23501")
if err != nil {
log.Fatalf("Error listening for https connections - %v", err)
}
for {
c, err := ln.Accept()
if err != nil {
log.Printf("Error accepting new connection - %v", err)
continue
}
go func(c net.Conn) {
tlsConn, err := vhost.TLS(c)
if err != nil {
log.Printf("Error accepting new connection - %v", err)
}
if tlsConn.Host() == "" {
log.Printf("Cannot support non-SNI enabled clients")
return
}
connectReq := &http.Request{
Method: "CONNECT",
URL: &url.URL{
Opaque: tlsConn.Host(),
Host: net.JoinHostPort(tlsConn.Host(), "443"),
},
Host: tlsConn.Host(),
Header: make(http.Header),
RemoteAddr: c.RemoteAddr().String(),
}
resp := dumbResponseWriter{tlsConn}
proxy.ServeHTTP(resp, connectReq)
}(c)
}
}
type dumbResponseWriter struct {
net.Conn
}
func (dumb dumbResponseWriter) Header() http.Header {
panic("Header() should not be called on this ResponseWriter")
}
func (dumb dumbResponseWriter) Write(buf []byte) (int, error) {
if bytes.Equal(buf, []byte("HTTP/1.0 200 OK\r\n\r\n")) {
return len(buf), nil // throw away the HTTP OK response from the faux CONNECT request
}
return dumb.Conn.Write(buf)
}
func (dumb dumbResponseWriter) WriteHeader(code int) {
panic("WriteHeader() should not be called on this ResponseWriter")
}
func (dumb dumbResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return dumb, bufio.NewReadWriter(bufio.NewReader(dumb), bufio.NewWriter(dumb)), nil
}
func startHttpServer() *http.Server {
srv := &http.Server{Addr: fmt.Sprintf(":%d", 23500)}
srv.Handler = proxy
// go func() {
// http.ListenAndServe(":6060", nil)
// }()
go func() {
if err := srv.ListenAndServe(); err != nil {
// cannot panic, because this probably is an intentional close
log.Printf("Httpserver: ListenAndServe() error: %s", err)
server = nil
}
}()
// returning reference so caller can call Shutdown()
return srv
}
func startGoProxyServer(certPath, certKeyPath string) {
initGoProxy()
LoadAndSetCa(certPath, certKeyPath)
if proxy == nil {
return
}
server = startHttpServer()
go startHttpsServer()
proxy.OnRequest().DoFunc(
func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
category, matchType := adblockMatcher.TestUrlBlocked(r.URL.String(), r.Host, r.Referer())
if category != nil && matchType == Included {
return r, goproxy.NewResponse(r,
goproxy.ContentTypeHtml, http.StatusForbidden,
adblockMatcher.GetBlockPage(r.URL.String(), *category, "Blocked by server policy"))
}
return r, nil
})
proxy.OnResponse().DoFunc(
func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if resp == nil {
return resp
}
if resp.StatusCode > 400 { //ignore errors
return resp
}
if !adblockMatcher.TestContentTypeIsFiltrable(resp.Header.Get("Content-Type")) {
return resp
}
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
bytesData := buf.Bytes()
//since we'd read all body - we need to recreate reader for client here
resp.Body.Close()
resp.Body = ioutil.NopCloser(bytes.NewBuffer(bytesData))
if !adblockMatcher.IsContentSmallEnoughToFilter(int64(len(bytesData))) {
return resp
}
category := adblockMatcher.TestContainsForbiddenPhrases(bytesData)
if category != nil {
message := adblockMatcher.GetBlockPage(resp.Request.URL.String(), *category, "Trigger text found")
return goproxy.NewResponse(resp.Request, goproxy.ContentTypeHtml, http.StatusForbidden, message)
}
return resp
})
if proxy.Verbose {
log.Printf("Server started")
}
}
func stopGoProxyServer() {
if server != nil {
context, _ := context.WithTimeout(context.Background(), 1*time.Second)
server.Shutdown(context)
server = nil
}
}
|
package main
import (
"net/http"
"fmt"
"github.com/jfyne/live"
)
var cookieStore = live.NewCookieStore("lamevaaplicacio", []byte("elmeusecret"))
func main(){
logoutHandler := NewLogoutHandler()
loginHandler := NewLoginHandler()
infoHandler := miInformacion()
http.Handle("/info", infoHandler)
http.Handle("/logout", logoutHandler)
http.Handle("/login", loginHandler)
http.Handle("/live.js", live.Javascript{})
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println(err)
}
}
|
package backend
import (
"errors"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/zlangbert/hrp/config"
"mime/multipart"
)
// A Backend is a generic interface for chart storage
type Backend interface {
Initialize() error
GetIndex() ([]byte, error)
GetChart(string) ([]byte, error)
PutChart(filename string, file multipart.File) error
Reindex() error
}
// NewBackend is a factory that returns a new Backend based on the config
func NewBackend(cfg *config.AppConfig, init bool) (Backend, error) {
var backend Backend
switch cfg.BackendName {
case "s3":
b, err := newS3(cfg)
if err != nil {
return nil, err
}
backend = b
default:
return nil, fmt.Errorf(fmt.Sprintf("unrecognized storage backend: %s", cfg.BackendName))
}
// initialize
if init {
err := backend.Initialize()
if err != nil {
log.Error(err.Error())
return nil, errors.New("failed to initialize backend")
}
}
return backend, nil
}
|
// 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 agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !linux
// +build !linux
// Package rand implements a cryptographically secure pseudorandom number
// generator.
package rand
import "crypto/rand"
// Reader is the default reader.
var Reader = rand.Reader
// Read implements io.Reader.Read.
func Read(b []byte) (int, error) {
return rand.Read(b)
}
|
package iface
type IMsgHanler interface {
AddRouter(uint32,IRouter)
DoMsgRouter(IRequest)
}
|
// Copyright 2020 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, Version 2.0, included in the file
// licenses/APL.txt.
// This test compares a dump generated from PostgreSQL with the pg_catalog
// and compares it with the current pg_catalog at cockroach db skipping
// all the known diffs:
//
// cd pkg/sql
// go test -run TestPGCatalog
//
// If you want to re-create the known (expected) diffs with the current differences
// add -rewrite-diffs flag when running this test:
//
// cd pkg/sql
// go test -run TestPGCatalog -rewrite-diffs
//
// To create the postgres dump file see pkg/cmd/generate-pg-catalog/main.go:
//
// cd pkg/cmd/generate-pg-catalog/
// go run main.go > ../../sql/testdata/pg_catalog_tables.json.
package sql
import (
"bufio"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strings"
"testing"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors/oserror"
"github.com/lib/pq/oid"
)
// Test data files.
const (
catalogDump = "%s_tables.json" // PostgreSQL pg_catalog schema
expectedDiffs = "%s_test_expected_diffs.json" // Contains expected difference between postgres and cockroach
testdata = "testdata" // testdata directory
catalogPkg = "catalog"
catconstantsPkg = "catconstants"
constantsGo = "constants.go"
vtablePkg = "vtable"
pgCatalogGo = "pg_catalog.go"
)
// When running test with -rewrite-diffs test will pass and re-create pg_catalog_test-diffs.json
var (
rewriteFlag = flag.Bool("rewrite-diffs", false, "This will re-create the expected diffs file")
catalogName = flag.String("catalog", "pg_catalog", "Catalog or namespace, default: pg_catalog")
)
// strings used on constants creations and text manipulation.
const (
pgCatalogPrefix = "PgCatalog"
pgCatalogIDConstant = "PgCatalogID"
tableIDSuffix = "TableID"
tableDefsDeclaration = `tableDefs: map[descpb.ID]virtualSchemaDef{`
tableDefsTerminal = `},`
undefinedTablesDeclaration = `undefinedTables: buildStringSet(`
undefinedTablesTerminal = `),`
virtualTablePosition = `// typOid is the only OID generation approach that does not use oidHasher, because`
virtualTableTemplate = `var %s = virtualSchemaTable{
comment: "%s was created for compatibility and is currently unimplemented",
schema: vtable.%s,
populate: func(ctx context.Context, p *planner, _ catalog.DatabaseDescriptor, addRow func(...tree.Datum) error) error {
return nil
},
unimplemented: true,
}
`
)
var addMissingTables = flag.Bool(
"add-missing-tables",
false,
"add-missing-tables will complete pg_catalog tables in the go code",
)
var (
tableFinderRE = regexp.MustCompile(`(?i)CREATE TABLE pg_catalog\.([^\s]+)\s`)
)
var none = struct{}{}
// summary will keep accountability for any unexpected difference and report it in the log.
type summary struct {
missingTables int
missingColumns int
mismatchDatatypesOid int
}
// report will log the amount of diffs for missing table and columns and data type mismatches.
func (sum *summary) report(t *testing.T) {
if sum.missingTables != 0 {
errorf(t, "Missing %d tables", sum.missingTables)
}
if sum.missingColumns != 0 {
errorf(t, "Missing %d columns", sum.missingColumns)
}
if sum.mismatchDatatypesOid != 0 {
errorf(t, "Column datatype mismatches: %d", sum.mismatchDatatypesOid)
}
}
// loadTestData retrieves the pg_catalog from the dumpfile generated from Postgres
func loadTestData(t testing.TB) PGMetadataTables {
var pgCatalogFile PGMetadataFile
testdataFile := filepath.Join(testdata, fmt.Sprintf(catalogDump, *catalogName))
f, err := os.Open(testdataFile)
if err != nil {
t.Fatal(err)
}
defer f.Close()
bytes, err := ioutil.ReadAll(f)
if err != nil {
t.Fatal(err)
}
if err = json.Unmarshal(bytes, &pgCatalogFile); err != nil {
t.Fatal(err)
}
return pgCatalogFile.PGMetadata
}
// loadCockroachPgCatalog retrieves pg_catalog schema from cockroach db
func loadCockroachPgCatalog(t testing.TB) PGMetadataTables {
crdbTables := make(PGMetadataTables)
ctx := context.Background()
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop(ctx)
sqlRunner := sqlutils.MakeSQLRunner(db)
rows := sqlRunner.Query(t, GetPGMetadataSQL, *catalogName)
defer rows.Close()
for rows.Next() {
var tableName, columnName, dataType string
var dataTypeOid uint32
if err := rows.Scan(&tableName, &columnName, &dataType, &dataTypeOid); err != nil {
t.Fatal(err)
}
crdbTables.AddColumnMetadata(tableName, columnName, dataType, dataTypeOid)
}
return crdbTables
}
// loadExpectedDiffs get all differences that will be skipped by the this test
func loadExpectedDiffs(t *testing.T) (diffs PGMetadataTables) {
diffs = PGMetadataTables{}
if *rewriteFlag {
// For rewrite we want this to be empty and get populated.
return
}
diffFile := filepath.Join(testdata, fmt.Sprintf(expectedDiffs, *catalogName))
if _, err := os.Stat(diffFile); err != nil {
if oserror.IsNotExist(err) {
// File does not exists it means diffs are not expected.
return
}
t.Fatal(err)
}
f, err := os.Open(diffFile)
if err != nil {
t.Fatal(err)
}
defer dClose(f)
bytes, err := ioutil.ReadAll(f)
if err != nil {
t.Fatal(err)
}
if err = json.Unmarshal(bytes, &diffs); err != nil {
t.Fatal(err)
}
return
}
// errorf wraps *testing.T Errorf to report fails only when the test doesn't run in rewrite mode.
func errorf(t *testing.T, format string, args ...interface{}) {
if !*rewriteFlag {
t.Errorf(format, args...)
}
}
func rewriteDiffs(t *testing.T, diffs PGMetadataTables, diffsFile string) {
if !*rewriteFlag {
return
}
if err := diffs.rewriteDiffs(diffsFile); err != nil {
t.Fatal(err)
}
}
// fixConstants updates catconstants that are needed for pgCatalog.
func fixConstants(t *testing.T, notImplemented PGMetadataTables) {
constantsFileName := filepath.Join(".", catalogPkg, catconstantsPkg, constantsGo)
// pgConstants will contains all the pgCatalog tableID constant adding the new tables and preventing duplicates
pgConstants := getPgCatalogConstants(t, constantsFileName, notImplemented)
sort.Strings(pgConstants)
// Rewrite will place all the pgConstants in alphabetical order after PgCatalogID
rewriteFile(constantsFileName, func(input *os.File, output outputFile) {
reader := bufio.NewScanner(input)
for reader.Scan() {
text := reader.Text()
trimText := strings.TrimSpace(text)
// Skips PgCatalog constants (except PgCatalogID) as these will be written from pgConstants slice
if strings.HasPrefix(trimText, pgCatalogPrefix) && trimText != pgCatalogIDConstant {
continue
}
output.appendString(text)
output.appendString("\n")
if trimText == pgCatalogIDConstant {
for _, pgConstant := range pgConstants {
output.appendString("\t")
output.appendString(pgConstant)
output.appendString("\n")
}
}
}
})
}
// fixVtable adds missing table's create table constants.
func fixVtable(t *testing.T, notImplemented PGMetadataTables) {
fileName := filepath.Join(vtablePkg, pgCatalogGo)
// rewriteFile first will check existing create table constants to avoid duplicates.
rewriteFile(fileName, func(input *os.File, output outputFile) {
existingTables := make(map[string]struct{})
reader := bufio.NewScanner(input)
for reader.Scan() {
text := reader.Text()
output.appendString(text)
output.appendString("\n")
createTable := tableFinderRE.FindStringSubmatch(text)
if createTable != nil {
tableName := createTable[1]
existingTables[tableName] = none
}
}
for tableName, columns := range notImplemented {
if _, ok := existingTables[tableName]; ok {
// Table already implemented.
continue
}
createTable, err := createTableConstant(tableName, columns)
if err != nil {
// We can not implement this table as this uses types not implemented.
t.Log(err)
continue
}
output.appendString(createTable)
}
})
}
// fixPgCatalogGo will update pgCatalog.undefinedTables, pgCatalog.tableDefs and
// will add needed virtualSchemas.
func fixPgCatalogGo(t *testing.T, notImplemented PGMetadataTables) {
undefinedTablesText, err := getUndefinedTablesText(notImplemented, pgCatalog)
if err != nil {
t.Fatal(err)
}
tableDefinitionText := getTableDefinitionsText(pgCatalogGo, notImplemented)
rewriteFile(pgCatalogGo, func(input *os.File, output outputFile) {
reader := bufio.NewScanner(input)
for reader.Scan() {
text := reader.Text()
trimText := strings.TrimSpace(text)
if trimText == virtualTablePosition {
//VirtualSchemas doesn't have a particular place to start we just print it before virtualTablePosition
output.appendString(printVirtualSchemas(notImplemented))
}
output.appendString(text)
output.appendString("\n")
switch trimText {
case tableDefsDeclaration:
printBeforeTerminalString(reader, output, tableDefsTerminal, tableDefinitionText)
case undefinedTablesDeclaration:
printBeforeTerminalString(reader, output, undefinedTablesTerminal, undefinedTablesText)
}
}
})
}
// printBeforeTerminalString will skip all the lines and print `s` text when finds the terminal string.
func printBeforeTerminalString(
reader *bufio.Scanner, output outputFile, terminalString string, s string,
) {
for reader.Scan() {
text := reader.Text()
trimText := strings.TrimSpace(text)
if strings.HasPrefix(trimText, "//") {
// As example, see pg_catalog.go where pg_catalog.allTablesNames are
// defined, after "buildStringSet(" there are comments that will not
// be replaced with `s` text.
output.appendString(text)
output.appendString("\n")
continue
}
if trimText != terminalString {
continue
}
output.appendString(s)
output.appendString(text)
output.appendString("\n")
break
}
}
// getPgCatalogConstants reads catconstant and retrieves all the constant with `PgCatalog` prefix.
func getPgCatalogConstants(
t *testing.T, inputFileName string, notImplemented PGMetadataTables,
) []string {
pgConstantSet := make(map[string]struct{})
f, err := os.Open(inputFileName)
if err != nil {
t.Logf("Problem getting pgCatalogConstants: %v", err)
t.Fatal(err)
}
defer dClose(f)
reader := bufio.NewScanner(f)
for reader.Scan() {
text := strings.TrimSpace(reader.Text())
if strings.HasPrefix(text, pgCatalogPrefix) {
if text == pgCatalogIDConstant {
continue
}
pgConstantSet[text] = none
}
}
for tableName := range notImplemented {
pgConstantSet[constantName(tableName, tableIDSuffix)] = none
}
pgConstants := make([]string, 0, len(pgConstantSet))
for pgConstantName := range pgConstantSet {
pgConstants = append(pgConstants, pgConstantName)
}
return pgConstants
}
// outputFile wraps an *os.file to avoid explicit error checks on every WriteString.
type outputFile struct {
f *os.File
}
// appendString calls WriteString and panics on error
func (o outputFile) appendString(s string) {
if _, err := o.f.WriteString(s); err != nil {
panic(fmt.Errorf("error while writing string: %s: %v", s, err))
}
}
// rewriteFile recreate a file by using the f func, this creates a temporary
// file to place all the output first then it replaces the original file.
func rewriteFile(fileName string, f func(*os.File, outputFile)) {
tmpName := fileName + ".tmp"
updateFile(fileName, tmpName, f)
defer func() {
if err := os.Remove(tmpName); err != nil {
panic(fmt.Errorf("problem removing temp file %s: %e", tmpName, err))
}
}()
updateFile(tmpName, fileName, func(input *os.File, output outputFile) {
if _, err := io.Copy(output.f, input); err != nil {
panic(fmt.Errorf("problem at rewriting file %s into %s: %v", tmpName, fileName, err))
}
})
}
func updateFile(inputFileName, outputFileName string, f func(input *os.File, output outputFile)) {
input, err := os.Open(inputFileName)
if err != nil {
panic(fmt.Errorf("error opening file %s: %v", inputFileName, err))
}
defer dClose(input)
output, err := os.OpenFile(outputFileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
panic(fmt.Errorf("error opening file %s: %v", outputFileName, err))
}
defer dClose(output)
f(input, outputFile{output})
}
// dClose is a helper that eliminates the need of error checking and defer the
// io.Closer Close() and pass lint checks.
func dClose(f io.Closer) {
err := f.Close()
if err != nil {
panic(err)
}
}
var acronyms = map[string]struct{}{
"acl": none,
"id": none,
}
// constantName create constant names for pg_catalog fixableTables following
// constant names standards.
func constantName(tableName string, suffix string) string {
var sb strings.Builder
snakeWords := strings.Split(tableName, "_")[1:]
sb.WriteString("PgCatalog")
for _, word := range snakeWords {
if _, ok := acronyms[word]; ok {
sb.WriteString(strings.ToUpper(word))
} else {
sb.WriteString(strings.ToUpper(word[:1]))
sb.WriteString(word[1:])
}
}
sb.WriteString(suffix)
return sb.String()
}
// createTableConstant formats the text for vtable constants.
func createTableConstant(tableName string, columns PGMetadataColumns) (string, error) {
var sb strings.Builder
constName := constantName(tableName, "")
if notImplementedTypes := columns.getUnimplementedTypes(); len(notImplementedTypes) > 0 {
return "", fmt.Errorf("not all types are implemented %s: %v", tableName, notImplementedTypes)
}
sb.WriteString("\n//")
sb.WriteString(constName)
sb.WriteString(" is an empty table in the pg_catalog that is not implemented yet\n")
sb.WriteString("const ")
sb.WriteString(constName)
sb.WriteString(" = `\n")
sb.WriteString("CREATE TABLE pg_catalog.")
sb.WriteString(tableName)
sb.WriteString(" (\n")
prefix := ""
for columnName, columnType := range columns {
formatColumn(&sb, prefix, columnName, columnType)
prefix = ",\n"
}
sb.WriteString("\n)`\n")
return sb.String(), nil
}
func formatColumn(
sb *strings.Builder, prefix, columnName string, columnType *PGMetadataColumnType,
) {
typeOid := oid.Oid(columnType.Oid)
typeName := types.OidToType[typeOid].Name()
if !strings.HasPrefix(typeName, `"char"`) {
typeName = strings.ToUpper(typeName)
}
sb.WriteString(prefix)
sb.WriteString("\t")
sb.WriteString(columnName)
sb.WriteString(" ")
sb.WriteString(typeName)
}
// printVirtualSchemas formats the golang code to create the virtualSchema
// structure.
func printVirtualSchemas(newTableNameList PGMetadataTables) string {
var sb strings.Builder
for tableName := range newTableNameList {
variableName := "p" + constantName(tableName, "Table")[1:]
vTableName := constantName(tableName, "")
sb.WriteString(fmt.Sprintf(virtualTableTemplate, variableName, tableName, vTableName))
}
return sb.String()
}
// getTableNameFromCreateTable uses pkg/sql/parser to analyze CREATE TABLE
// statement to retrieve table name.
func getTableNameFromCreateTable(createTableText string) (string, error) {
stmt, err := parser.ParseOne(createTableText)
if err != nil {
return "", err
}
create := stmt.AST.(*tree.CreateTable)
return create.Table.Table(), nil
}
// getUndefinedTablesText retrieves pgCatalog.undefinedTables, then it merges the
// new table names and formats the replacement text.
func getUndefinedTablesText(newTables PGMetadataTables, vs virtualSchema) (string, error) {
newTableList, err := getUndefinedTablesList(newTables, vs)
if err != nil {
return "", err
}
return formatUndefinedTablesText(newTableList), nil
}
// getUndefinedTablesList checks undefinedTables in the virtualSchema and makes
// sure they are not defined in tableDefs or are newTables to implement.
func getUndefinedTablesList(newTables PGMetadataTables, vs virtualSchema) ([]string, error) {
var undefinedTablesList []string
removeTables := make(map[string]struct{})
for _, table := range vs.tableDefs {
tableName, err := getTableNameFromCreateTable(table.getSchema())
if err != nil {
return nil, err
}
removeTables[tableName] = struct{}{}
}
for tableName := range newTables {
removeTables[tableName] = struct{}{}
}
for tableName := range vs.undefinedTables {
if _, ok := removeTables[tableName]; !ok {
undefinedTablesList = append(undefinedTablesList, tableName)
}
}
sort.Strings(undefinedTablesList)
return undefinedTablesList, nil
}
func formatUndefinedTablesText(newTableNameList []string) string {
var sb strings.Builder
for _, tableName := range newTableNameList {
sb.WriteString("\t\t\"")
sb.WriteString(tableName)
sb.WriteString("\",\n")
}
return sb.String()
}
// getTableDefinitionsText creates the text that will replace current
// definition of pgCatalog.tableDefs (at pg_catalog.go), by adding the new
// table definitions.
func getTableDefinitionsText(fileName string, notImplemented PGMetadataTables) string {
tableDefs := make(map[string]string)
maxLength := 0
f, err := os.Open(fileName)
if err != nil {
panic(fmt.Errorf("could not open file %s: %v", fileName, err))
}
defer dClose(f)
reader := bufio.NewScanner(f)
for reader.Scan() {
text := strings.TrimSpace(reader.Text())
if text == tableDefsDeclaration {
break
}
}
for reader.Scan() {
text := strings.TrimSpace(reader.Text())
if text == tableDefsTerminal {
break
}
def := strings.Split(text, ":")
defName := strings.TrimSpace(def[0])
defValue := strings.TrimRight(strings.TrimSpace(def[1]), ",")
tableDefs[defName] = defValue
length := len(defName)
if length > maxLength {
maxLength = length
}
}
for tableName := range notImplemented {
defName := "catconstants." + constantName(tableName, tableIDSuffix)
if _, ok := tableDefs[defName]; ok {
// Not overriding existing tableDefinitions
delete(notImplemented, tableName)
continue
}
defValue := "p" + constantName(tableName, "Table")[1:]
tableDefs[defName] = defValue
length := len(defName)
if length > maxLength {
maxLength = length
}
}
return formatTableDefinitionText(tableDefs, maxLength)
}
func formatTableDefinitionText(tableDefs map[string]string, maxLength int) string {
var sbAll strings.Builder
sortedDefKeys := getSortedDefKeys(tableDefs)
for _, defKey := range sortedDefKeys {
var sb strings.Builder
sb.WriteString("\t\t")
sb.WriteString(defKey)
sb.WriteString(":")
for sb.Len() < maxLength+4 {
sb.WriteString(" ")
}
sb.WriteString(tableDefs[defKey])
sb.WriteString(",\n")
sbAll.WriteString(sb.String())
}
return sbAll.String()
}
func getSortedDefKeys(tableDefs map[string]string) []string {
keys := make([]string, 0, len(tableDefs))
for constName := range tableDefs {
keys = append(keys, constName)
}
sort.Strings(keys)
return keys
}
// TestPGCatalog is the pg_catalog diff tool test which compares pg_catalog
// with postgres and cockroach.
func TestPGCatalog(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
defer func() {
r := recover()
if err, ok := r.(error); ok {
t.Fatal(err)
}
}()
if *addMissingTables && *catalogName != "pg_catalog" {
t.Fatal("--add-missing-tables only work for pg_catalog")
}
pgTables := loadTestData(t)
crdbTables := loadCockroachPgCatalog(t)
diffs := loadExpectedDiffs(t)
sum := &summary{}
for pgTable, pgColumns := range pgTables {
t.Run(fmt.Sprintf("Table=%s", pgTable), func(t *testing.T) {
crdbColumns, ok := crdbTables[pgTable]
if !ok {
if !diffs.isExpectedMissingTable(pgTable) {
errorf(t, "Missing table `%s`", pgTable)
diffs.addMissingTable(pgTable)
sum.missingTables++
}
return
}
for expColumnName, expColumn := range pgColumns {
gotColumn, ok := crdbColumns[expColumnName]
if !ok {
if !diffs.isExpectedMissingColumn(pgTable, expColumnName) {
errorf(t, "Missing column `%s`", expColumnName)
diffs.addMissingColumn(pgTable, expColumnName)
sum.missingColumns++
}
continue
}
if diffs.isDiffOid(pgTable, expColumnName, expColumn, gotColumn) {
sum.mismatchDatatypesOid++
errorf(t, "Column `%s` expected data type oid `%d` (%s) but found `%d` (%s)",
expColumnName,
expColumn.Oid,
expColumn.DataType,
gotColumn.Oid,
gotColumn.DataType,
)
diffs.addDiff(pgTable, expColumnName, expColumn, gotColumn)
}
}
})
}
sum.report(t)
rewriteDiffs(t, diffs, filepath.Join(testdata, fmt.Sprintf(expectedDiffs, *catalogName)))
if *addMissingTables {
validateUndefinedTablesField(t)
unimplemented := diffs.getUnimplementedTables(pgTables)
fixConstants(t, unimplemented)
fixVtable(t, unimplemented)
fixPgCatalogGo(t, unimplemented)
}
}
// TestPGMetadataCanFixCode checks for parts of the code this file is checking with
// add-missing-tables flag to verify that a potential refactoring does not
// break the code.
func TestPGMetadataCanFixCode(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// TODO: Add more checks, for now adding the test that is relevant for
// rewrite undefinedTables.
validateUndefinedTablesField(t)
}
// validateUndefinedTablesField checks the definition of virtualSchema objects
// (pg_catalog and information_schema) have a undefinedTables field which can
// be rewritten by this code.
func validateUndefinedTablesField(t *testing.T) {
propertyIndex := strings.IndexRune(undefinedTablesDeclaration, ':')
property := undefinedTablesDeclaration[:propertyIndex]
// Using pgCatalog but information_schema is a virtualSchema as well
assertProperty(t, property, pgCatalog)
}
// assertProperty checks the property (or field) exists in the given interface.
func assertProperty(t *testing.T, property string, i interface{}) {
t.Run(fmt.Sprintf("assertProperty/%s", property), func(t *testing.T) {
value := reflect.ValueOf(i)
if value.Type().Kind() != reflect.Ptr {
value = reflect.New(reflect.TypeOf(i))
}
field := value.Elem().FieldByName(property)
if !field.IsValid() {
t.Fatalf("field %s is not a field of type %T", property, i)
}
})
}
|
package dynamiclistener
func OnlyAllow(str string) func(...string) []string {
return func(s2 ...string) []string {
for _, s := range s2 {
if s == str {
return []string{s}
}
}
return nil
}
}
|
package main
import(
"math/rand"
//"time"
"fmt"
"./gamelogic"
"bufio"
"os"
"log"
)
func main(){
gamelogic.Rand_init()
//reader := bufio.NewReader(os.Stdin)
fmt.Printf("Welcome to Five Card Draw! (press 'enter' between messages to continue)")
bufio.NewReader(os.Stdin).ReadBytes('\n')
ante := 1
min_bet := 0
max_bet := 20
game, gerr := gamelogic.GameInit(ante, min_bet, max_bet)
if gerr != nil{
fmt.Printf("Game object did not initialize! \n")
}
p1err := game.Join("Ashton", 100, 0)
if p1err != nil{
fmt.Printf("Player 1 was not added to the game! \n")
}
p2err := game.Join("Adam", 100, 1)
if p2err != nil {
fmt.Printf("Player 2 was not added to the game! \n")
log.Fatal(p2err)
}
p3err := game.Join("Matthew", 100, 2)
if p3err != nil {
fmt.Printf("Player 3 was not added to the game! \n")
log.Fatal(p3err)
}
dealterToken := 0
fmt.Printf("1 \n")
newErr := game.NewRound(dealterToken)
if newErr != nil{
log.Fatal(newErr)
}
fmt.Printf("2 \n")
fmt.Printf("Dealer token: %d \n", game.Dealer_Token)
fmt.Printf("Current Player is %s \n", game.Get_current_player_name())
for{
err, winner := game.Winner_check()
if err != nil{
log.Fatal(err)
}
if winner != nil{
fmt.Printf("A winner is %s \n", winner.Name)
break
}
if (game.Phase == 0 || game.Phase == 2 || game.Phase == 4){
player := game.Get_current_player_name()
decision := rand.Float32()
if decision < 0.25{
fmt.Printf("Bet \n")
raise := rand.Intn(5)
err := game.Bet(player, raise)
if err != nil{
log.Fatal(err)
}
}else if decision < 0.88{
pindex, err := game.GetPlayerIndex(player)
if err != nil{
log.Fatal(err)
}
if game.Players[pindex].Bet == game.Current_Bet{
fmt.Printf("Check \n")
err = game.Check(player)
if err != nil{
log.Fatal(err)
}
}else{
fmt.Printf("Call \n")
err := game.Call(player)
if err != nil{
log.Fatal(err)
}
}
}else{
fmt.Printf("Fold \n")
err := game.Fold(player)
if err != nil{
log.Fatal(err)
}
}
}else if (game.Phase == 1 || game.Phase == 3){
player := game.Get_current_player_name()
num_discard := rand.Intn(4)
fmt.Printf("%s will discard %d cards \n", player, num_discard)
var discard []int
for i := 0; i <= num_discard; i++{
discard = append(discard, i)
}
err := game.Discard(player, discard)
if err != nil{
log.Fatal(err)
}
}else{
//game.Phase == 5
winner := game.Showdown()
fmt.Printf("A winner is %s", winner.Name)
break
}
}
}
/*player := game.Get_current_player_name()
err := game.Bet(player, 7)
fmt.Printf("%s bets %d \n", player, 7)
if err != nil{
log.Fatal(err)
}
fmt.Printf("3 \n")
player = game.Get_current_player_name()
err = game.Call(player)
fmt.Printf("%s calls \n", player)
if err != nil{
log.Fatal(err)
}
fmt.Printf("4 \n")
player = game.Get_current_player_name()
err = game.Bet(player, 4)
fmt.Printf("%s bets 4 \n", player)
if err != nil{
log.Fatal(err)
}
fmt.Printf("5 \n")
player = game.Get_current_player_name()
err = game.Call(player)
fmt.Printf("%s calls \n", player)
if err != nil{
log.Fatal(err)
}
fmt.Printf("6 \n")
player = game.Get_current_player_name()
err = game.Call(player)
fmt.Printf("%s calls \n", player)
if err != nil{
log.Fatal(err)
}
fmt.Printf("7 \n")
player = game.Get_current_player_name()
err = game.Call(player)
fmt.Printf("%s calls \n", player)
if err != nil{
log.Fatal(err)
}
fmt.Printf("8 \n")
player = game.Get_current_player_name()
err = game.Bet(player, 4)
fmt.Printf("%s bests 4", player)
if err != nil{
log.Fatal(err)
}
}
*/ |
// 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 kernel
import (
"context"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"chromiumos/tast/common/testexec"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: PerfCallgraph,
Desc: "Checks that callchains can be profiled using perf",
Contacts: []string{"chromeos-kernel-test@google.com"},
// Call stacks can't currently be unwound on ARM due to the
// Thumb and ARM ISAs using different registers for the frame pointer.
SoftwareDeps: []string{"amd64"},
Attr: []string{"group:mainline"},
})
}
func PerfCallgraph(ctx context.Context, s *testing.State) {
const exe = "/usr/local/libexec/tast/helpers/local/cros/kernel.PerfCallgraph.graph"
td, err := ioutil.TempDir("", "tast.kernel.PerfCallgraph")
if err != nil {
s.Fatal("Failed to create temp dir: ", err)
}
defer os.RemoveAll(td)
trace := filepath.Join(td, "trace")
if err := testexec.CommandContext(ctx, "perf", "record", "-N", "-e", "cycles", "-g",
"-o", trace, "--", exe).Run(testexec.DumpLogOnError); err != nil {
s.Fatal("Failed to record trace: ", err)
}
out, err := testexec.CommandContext(ctx, "perf", "report", "-D",
"-i", trace).Output(testexec.DumpLogOnError)
if err != nil {
s.Fatal("Failed to generate report: ", err)
}
const outFile = "report.txt"
if err := ioutil.WriteFile(filepath.Join(s.OutDir(), outFile), out, 0644); err != nil {
s.Error("Failed to write report: ", err)
}
// Try to find a sample with a callchain of the expected length.
// Samples are formatted as follows and separated by blank lines:
//
// 41522248799882 0x7e60 [0x70]: PERF_RECORD_SAMPLE(IP, 0x2): 12923/12923: 0x5a385056d84f period: 492431 addr: 0
// ... FP chain: nr:8
// ..... 0: fffffffffffffe00
// ..... 1: 00005a385056d84f
// ..... 2: 00005a385056d892
// ..... 3: 00005a385056d8e5
// ..... 4: 00005a385056d912
// ..... 5: 00005a385056d991
// ..... 6: 00007a3ddb542ad4
// ..... 7: 00005a385056d6ea
// ... thread: kernel.PerfCall:12923
// ...... dso: /usr/local/libexec/tast/helpers/local/cros/kernel.PerfCallgraph.graph
chainRegexp := regexp.MustCompile(`\bFP chain: nr:(\d+)\b`)
const wantedChainLength = 3
for _, sample := range strings.Split(string(out), "\n\n") {
// Skip non-samples and samples for other DSOs.
if !strings.Contains(sample, "PERF_RECORD_SAMPLE") ||
!strings.Contains(sample, "dso: "+exe) {
continue
}
// Extract the chain length.
ms := chainRegexp.FindStringSubmatch(sample)
if ms == nil {
continue
}
if chainLength, err := strconv.Atoi(ms[1]); err != nil {
s.Fatalf("Failed to parse callchain length %q: %v", ms[1], err)
} else if chainLength >= wantedChainLength {
s.Log("Found callchain of length ", chainLength)
return
}
}
s.Errorf("Failed to find callchain of length %d or greater; see %v", wantedChainLength, outFile)
}
|
package main
import (
"flag"
"math/rand"
"github.com/lovung/sortBigFile/lib/golib"
)
func main() {
fo := flag.String("o", "resources/list.txt", "file path to write to")
num := flag.Int("n", 1000000, "number of items")
flag.Parse()
slice := rand.Perm(*num)
golib.WriteFile(*fo, slice, len(slice))
}
|
package tempconv
import (
"math"
"testing"
)
// TestKToC tests KToC
func TestKToC(t *testing.T) {
// Test the conversion from Kelvin to Celsius
k := Kelvin(0)
c := KToC(k)
if c != -273.15 {
t.Errorf("KToC(273.15) failed: %v\n", c)
}
}
// TestKToF tests KToF
func TestKToF(t *testing.T) {
// Test the conversion from Kelvin to Celsius
k := Kelvin(0)
f := KToF(k)
if math.Round(float64(f)*100)/100 != -459.67 {
t.Errorf("KToF(523.67) failed: %v\n", f)
}
}
|
package hangouts
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/seibert-media/golibs/log"
"go.uber.org/zap"
googleAuth "golang.org/x/oauth2/google"
)
// Hangouts handler
type Hangouts struct {
*http.Client
URL string
}
// New Hangouts client
func New(ctx context.Context, serviceAccount string) (*Hangouts, error) {
ctx = log.WithFields(ctx, zap.String("component", "hangouts"))
httpClient, err := googleAuth.DefaultClient(ctx, "https://www.googleapis.com/auth/chat.bot")
if err != nil {
return nil, err
}
return &Hangouts{
Client: httpClient,
}, nil
}
// NewWebhookClient for Hangouts
func NewWebhookClient(url string) (*Hangouts, error) {
return &Hangouts{
Client: &http.Client{},
URL: url,
}, nil
}
// Send Message to Hangouts
// space can be left empty if using webhooks as it is used to identify the channel messages are being sent to
func (h *Hangouts) Send(ctx context.Context, space string, msg *Message) error {
url := h.URL
if url == "" {
url = fmt.Sprintf("https://chat.googleapis.com/v1/%s/messages", space)
}
ctx = log.WithFields(ctx, zap.String("url", url))
data, err := json.Marshal(msg)
if err != nil {
return err
}
resp, err := h.Client.Post(url, "application/json", bytes.NewBuffer(data))
if err != nil {
return err
}
if resp.StatusCode/100 != 2 {
body, _ := ioutil.ReadAll(resp.Body)
log.From(ctx).Error("post message error", zap.String("status", resp.Status), zap.ByteString("body", body))
return fmt.Errorf("post message error: %s", body)
}
return nil
}
|
package main
type foo struct {
bar int
}
func main() {
var f foo
// := 操作符不能用于结构体字段赋值。
f.bar, tmp := 1, 2
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"github.com/syucream/numeronymize/src/numeronymize"
)
func main() {
in, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
numeronymized := numeronymize.Numeronymize(string(in))
fmt.Println(numeronymized)
}
|
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package sdk_test
import (
"fmt"
"net/http"
"github.com/mainflux/mainflux/pkg/errors"
)
func createError(e error, statusCode int) error {
httpStatus := fmt.Sprintf("%d %s", statusCode, http.StatusText(statusCode))
return errors.Wrap(e, errors.New(httpStatus))
}
|
package backend
import (
"net/http"
"github.com/goadesign/goa"
"github.com/goadesign/goa/middleware"
"github.com/MiCHiLU/goapp-scaffold/app"
)
func init() {
service := goa.New("appengine")
service.Use(middleware.RequestID())
service.Use(middleware.LogRequest(true))
service.Use(middleware.ErrorHandler(service, true))
service.Use(middleware.Recover())
app.MountItemsController(service, newItemsController(service))
http.HandleFunc("/", service.Mux.ServeHTTP)
//http.HandleFunc("/", handleFunc)
}
|
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
strfmt "github.com/go-openapi/strfmt"
)
// NewGetAttributesOfUserParams creates a new GetAttributesOfUserParams object
// with the default values initialized.
func NewGetAttributesOfUserParams() *GetAttributesOfUserParams {
var ()
return &GetAttributesOfUserParams{
timeout: cr.DefaultTimeout,
}
}
// NewGetAttributesOfUserParamsWithTimeout creates a new GetAttributesOfUserParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewGetAttributesOfUserParamsWithTimeout(timeout time.Duration) *GetAttributesOfUserParams {
var ()
return &GetAttributesOfUserParams{
timeout: timeout,
}
}
/*GetAttributesOfUserParams contains all the parameters to send to the API endpoint
for the get attributes of user operation typically these are written to a http.Request
*/
type GetAttributesOfUserParams struct {
/*Accept*/
Accept *string
/*Embedded*/
Embedded *string
/*Name*/
Name *string
timeout time.Duration
}
// WithAccept adds the accept to the get attributes of user params
func (o *GetAttributesOfUserParams) WithAccept(Accept *string) *GetAttributesOfUserParams {
o.Accept = Accept
return o
}
// WithEmbedded adds the embedded to the get attributes of user params
func (o *GetAttributesOfUserParams) WithEmbedded(Embedded *string) *GetAttributesOfUserParams {
o.Embedded = Embedded
return o
}
// WithName adds the name to the get attributes of user params
func (o *GetAttributesOfUserParams) WithName(Name *string) *GetAttributesOfUserParams {
o.Name = Name
return o
}
// WriteToRequest writes these params to a swagger request
func (o *GetAttributesOfUserParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
r.SetTimeout(o.timeout)
var res []error
if o.Accept != nil {
// query param Accept
var qrAccept string
if o.Accept != nil {
qrAccept = *o.Accept
}
qAccept := qrAccept
if qAccept != "" {
if err := r.SetQueryParam("Accept", qAccept); err != nil {
return err
}
}
}
if o.Embedded != nil {
// query param _embedded
var qrEmbedded string
if o.Embedded != nil {
qrEmbedded = *o.Embedded
}
qEmbedded := qrEmbedded
if qEmbedded != "" {
if err := r.SetQueryParam("_embedded", qEmbedded); err != nil {
return err
}
}
}
if o.Name != nil {
// path param name
if err := r.SetPathParam("name", *o.Name); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
|
package leetcode
func minArray(numbers []int) int {
if len(numbers) == 0 {
return 0
}
begin := 0
end := len(numbers) - 1
mid := 0
for begin < end {
mid = (begin + end) / 2
if numbers[mid] < numbers[end] {
end = mid
} else if numbers[mid] > numbers[end] {
begin = mid + 1
} else {
end--
}
}
return numbers[begin]
}
|
package cmd
import (
"fmt"
"os"
"path/filepath"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
)
var confirm bool
// nukeCmd represents the nuke command
var nukeCmd = &cobra.Command{
Use: "nuke",
Short: "Nuke the database",
Long: `Deletes the database directory.`,
Run: func(cmd *cobra.Command, args []string) {
if confirm {
//Disconnect the database
err := db.Close()
if err != nil {
panic(err)
}
//Get home directory
home, err := homedir.Dir()
if err != nil {
panic(err)
}
//Generate database path
dbPath := filepath.Join(home, "aluminum")
//Delete the database directory
err = os.RemoveAll(dbPath)
if err != nil {
panic(err)
}
fmt.Println("Database nuked!")
} else {
fmt.Print(`You're attempting to nuke the database!
Nuking the database is irreversible! Aluminum will loose track of
what games you have installed and will be unable to remove game
integrations automatically (You'll have to do this manually!). If
you're absolutely sure you want to do this, please re-run this
command with the "--confirm" flag. You've been warned!
`)
}
},
}
func init() {
rootCmd.AddCommand(nukeCmd)
nukeCmd.Flags().BoolVar(&confirm, "confirm", false, "Confirm nuking the database")
}
|
package web
import (
"encoding/json"
"github.com/RemmargorP/memjudge/api"
"net/http"
)
func (wi *WebInstance) APISignUpHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
decoder := json.NewDecoder(r.Body)
var signupdata struct {
Login string
Email string
Password string
}
var response struct {
Status string `json:"status"`
Reason string `json:"reason"`
Redir string `json:"redirect"`
}
var serialized []byte
if err := decoder.Decode(&signupdata); err != nil {
response.Reason = err.Error()
response.Status = "FAIL"
} else {
u, err := api.SignUp(wi.DB, signupdata.Login, signupdata.Email, signupdata.Password)
if u != nil {
response.Reason = "Success"
response.Redir = "/"
response.Status = "OK"
} else {
response.Reason = err.Error()
response.Status = "FAIL"
}
}
serialized, _ = json.Marshal(response)
w.Write(serialized)
}
|
package prometheus
import (
"context"
"encoding/json"
"fmt"
"strings"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// returns the prometheus service name
func GetPrometheusService(clientset kubernetes.Interface) (*v1.Service, bool, error) {
services, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{
LabelSelector: "app=prometheus,component=server,heritage=Helm",
})
if err != nil {
return nil, false, err
}
if len(services.Items) == 0 {
return nil, false, nil
}
return &services.Items[0], true, nil
}
// returns the prometheus service name
func getKubeStateMetricsService(clientset kubernetes.Interface) (*v1.Service, bool, error) {
services, err := clientset.CoreV1().Services("").List(context.TODO(), metav1.ListOptions{
LabelSelector: "app.kubernetes.io/name=kube-state-metrics",
})
if err != nil {
return nil, false, err
}
if len(services.Items) == 0 {
return nil, false, nil
}
return &services.Items[0], true, nil
}
type SimpleIngress struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
}
// GetIngressesWithNGINXAnnotation gets an array of names for all ingresses controlled by
// NGINX
func GetIngressesWithNGINXAnnotation(clientset kubernetes.Interface) ([]SimpleIngress, error) {
ingressList, err := clientset.NetworkingV1beta1().Ingresses("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
return nil, err
}
res := make([]SimpleIngress, 0)
for _, ingress := range ingressList.Items {
if ingressAnn, found := ingress.ObjectMeta.Annotations["kubernetes.io/ingress.class"]; found {
if ingressAnn == "nginx" {
res = append(res, SimpleIngress{
Name: ingress.ObjectMeta.Name,
Namespace: ingress.ObjectMeta.Namespace,
})
}
}
}
return res, nil
}
type QueryOpts struct {
Metric string `schema:"metric"`
ShouldSum bool `schema:"shouldsum"`
Kind string `schema:"kind"`
PodList []string `schema:"pods"`
Name string `schema:"name"`
Namespace string `schema:"namespace"`
StartRange uint `schema:"startrange"`
EndRange uint `schema:"endrange"`
Resolution string `schema:"resolution"`
Percentile float64 `schema:"percentile"`
}
func QueryPrometheus(
clientset kubernetes.Interface,
service *v1.Service,
opts *QueryOpts,
) ([]byte, error) {
if len(service.Spec.Ports) == 0 {
return nil, fmt.Errorf("prometheus service has no exposed ports to query")
}
selectionRegex, err := getSelectionRegex(opts.Kind, opts.Name)
if err != nil {
return nil, err
}
var podSelector string
if len(opts.PodList) > 0 {
podSelector = fmt.Sprintf(`namespace="%s",pod=~"%s",container!="POD",container!=""`, opts.Namespace, strings.Join(opts.PodList, "|"))
} else {
podSelector = fmt.Sprintf(`namespace="%s",pod=~"%s",container!="POD",container!=""`, opts.Namespace, selectionRegex)
}
query := ""
if opts.Metric == "cpu" {
query = fmt.Sprintf("rate(container_cpu_usage_seconds_total{%s}[5m])", podSelector)
} else if opts.Metric == "memory" {
query = fmt.Sprintf("container_memory_usage_bytes{%s}", podSelector)
} else if opts.Metric == "network" {
netPodSelector := fmt.Sprintf(`namespace="%s",pod=~"%s",container="POD"`, opts.Namespace, selectionRegex)
query = fmt.Sprintf("rate(container_network_receive_bytes_total{%s}[5m])", netPodSelector)
} else if opts.Metric == "nginx:errors" {
num := fmt.Sprintf(`sum(rate(nginx_ingress_controller_requests{status=~"5.*",namespace="%s",ingress=~"%s"}[5m]) OR on() vector(0))`, opts.Namespace, selectionRegex)
denom := fmt.Sprintf(`sum(rate(nginx_ingress_controller_requests{namespace="%s",ingress=~"%s"}[5m]) > 0)`, opts.Namespace, selectionRegex)
query = fmt.Sprintf(`%s / %s * 100 OR on() vector(0)`, num, denom)
} else if opts.Metric == "nginx:latency" {
num := fmt.Sprintf(`sum(rate(nginx_ingress_controller_request_duration_seconds_sum{namespace=~"%s",ingress=~"%s"}[5m]) OR on() vector(0))`, opts.Namespace, selectionRegex)
denom := fmt.Sprintf(`sum(rate(nginx_ingress_controller_request_duration_seconds_count{namespace=~"%s",ingress=~"%s"}[5m]))`, opts.Namespace, selectionRegex)
query = fmt.Sprintf(`%s / %s OR on() vector(0)`, num, denom)
} else if opts.Metric == "nginx:latency-histogram" {
query = fmt.Sprintf(`histogram_quantile(%f, sum(rate(nginx_ingress_controller_request_duration_seconds_bucket{status!="404",status!="500",namespace=~"%s",ingress=~"%s"}[5m])) by (le, ingress))`, opts.Percentile, opts.Namespace, selectionRegex)
} else if opts.Metric == "cpu_hpa_threshold" {
// get the name of the kube hpa metric
metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "spec_target_metric")
cpuMetricName := getKubeCPUMetricName(clientset, service, opts)
ksmSvc, found, _ := getKubeStateMetricsService(clientset)
appLabel := ""
if found {
appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
}
query = createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, selectionRegex, opts.Name, opts.Namespace, appLabel, hpaMetricName)
} else if opts.Metric == "memory_hpa_threshold" {
metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "spec_target_metric")
memMetricName := getKubeMemoryMetricName(clientset, service, opts)
ksmSvc, found, _ := getKubeStateMetricsService(clientset)
appLabel := ""
if found {
appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
}
query = createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, selectionRegex, opts.Name, opts.Namespace, appLabel, hpaMetricName)
} else if opts.Metric == "hpa_replicas" {
metricName, hpaMetricName := getKubeHPAMetricName(clientset, service, opts, "status_current_replicas")
ksmSvc, found, _ := getKubeStateMetricsService(clientset)
appLabel := ""
if found {
appLabel = ksmSvc.ObjectMeta.Labels["app.kubernetes.io/instance"]
}
query = createHPACurrentReplicasQuery(metricName, opts.Name, opts.Namespace, appLabel, hpaMetricName)
}
if opts.ShouldSum {
query = fmt.Sprintf("sum(%s)", query)
}
fmt.Println("QUERY IS", query)
queryParams := map[string]string{
"query": query,
"start": fmt.Sprintf("%d", opts.StartRange),
"end": fmt.Sprintf("%d", opts.EndRange),
"step": opts.Resolution,
}
resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
"http",
service.Name,
fmt.Sprintf("%d", service.Spec.Ports[0].Port),
"/api/v1/query_range",
queryParams,
)
rawQuery, err := resp.DoRaw(context.TODO())
if err != nil {
return nil, err
}
return parseQuery(rawQuery, opts.Metric)
}
type promRawQuery struct {
Data struct {
Result []struct {
Metric struct {
Pod string `json:"pod,omitempty"`
} `json:"metric,omitempty"`
Values [][]interface{} `json:"values"`
} `json:"result"`
} `json:"data"`
}
type promParsedSingletonQueryResult struct {
Date interface{} `json:"date,omitempty"`
CPU interface{} `json:"cpu,omitempty"`
Replicas interface{} `json:"replicas,omitempty"`
Memory interface{} `json:"memory,omitempty"`
Bytes interface{} `json:"bytes,omitempty"`
ErrorPct interface{} `json:"error_pct,omitempty"`
Latency interface{} `json:"latency,omitempty"`
}
type promParsedSingletonQuery struct {
Pod string `json:"pod,omitempty"`
Results []promParsedSingletonQueryResult `json:"results"`
}
func parseQuery(rawQuery []byte, metric string) ([]byte, error) {
rawQueryObj := &promRawQuery{}
json.Unmarshal(rawQuery, rawQueryObj)
res := make([]*promParsedSingletonQuery, 0)
for _, result := range rawQueryObj.Data.Result {
singleton := &promParsedSingletonQuery{
Pod: result.Metric.Pod,
}
singletonResults := make([]promParsedSingletonQueryResult, 0)
for _, values := range result.Values {
singletonResult := &promParsedSingletonQueryResult{
Date: values[0],
}
if metric == "cpu" {
singletonResult.CPU = values[1]
} else if metric == "memory" {
singletonResult.Memory = values[1]
} else if metric == "network" {
singletonResult.Bytes = values[1]
} else if metric == "nginx:errors" {
singletonResult.ErrorPct = values[1]
} else if metric == "cpu_hpa_threshold" {
singletonResult.CPU = values[1]
} else if metric == "memory_hpa_threshold" {
singletonResult.Memory = values[1]
} else if metric == "hpa_replicas" {
singletonResult.Replicas = values[1]
} else if metric == "nginx:latency" || metric == "nginx:latency-histogram" {
singletonResult.Latency = values[1]
}
singletonResults = append(singletonResults, *singletonResult)
}
singleton.Results = singletonResults
res = append(res, singleton)
}
return json.Marshal(res)
}
func getSelectionRegex(kind, name string) (string, error) {
var suffix string
switch strings.ToLower(kind) {
case "deployment":
suffix = "[a-z0-9]+-[a-z0-9]+"
case "statefulset":
suffix = "[0-9]+"
case "job":
suffix = "[a-z0-9]+"
case "cronjob":
suffix = "[a-z0-9]+-[a-z0-9]+"
case "ingress":
return name, nil
default:
return "", fmt.Errorf("not a supported controller to query for metrics")
}
return fmt.Sprintf("%s-%s", name, suffix), nil
}
func createHPAAbsoluteCPUThresholdQuery(cpuMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
kubeMetricsPodSelector := getKubeMetricsPodSelector(podSelectionRegex, namespace)
kubeMetricsHPASelector := fmt.Sprintf(
`%s="%s",namespace="%s",metric_name="cpu",metric_target_type="utilization"`,
hpaMetricName,
hpaName,
namespace,
)
if cpuMetricName == "kube_pod_container_resource_requests" {
kubeMetricsPodSelector += `,resource="cpu",unit="core"`
}
// the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
// as well
if appLabel != "" {
kubeMetricsPodSelector += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
kubeMetricsHPASelector += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
}
requestCPU := fmt.Sprintf(
`sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
hpaMetricName,
cpuMetricName,
kubeMetricsPodSelector,
hpaMetricName,
hpaName,
)
targetCPUUtilThreshold := fmt.Sprintf(
`%s{%s} / 100`,
metricName,
kubeMetricsHPASelector,
)
return fmt.Sprintf(`%s * on(%s) %s`, requestCPU, hpaMetricName, targetCPUUtilThreshold)
}
func createHPAAbsoluteMemoryThresholdQuery(memMetricName, metricName, podSelectionRegex, hpaName, namespace, appLabel, hpaMetricName string) string {
kubeMetricsPodSelector := getKubeMetricsPodSelector(podSelectionRegex, namespace)
kubeMetricsHPASelector := fmt.Sprintf(
`%s="%s",namespace="%s",metric_name="memory",metric_target_type="utilization"`,
hpaMetricName,
hpaName,
namespace,
)
if memMetricName == "kube_pod_container_resource_requests" {
kubeMetricsPodSelector += `,resource="memory",unit="byte"`
}
// the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
// as well
if appLabel != "" {
kubeMetricsPodSelector += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
kubeMetricsHPASelector += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
}
requestMem := fmt.Sprintf(
`sum by (%s) (label_replace(%s{%s},"%s", "%s", "", ""))`,
hpaMetricName,
memMetricName,
kubeMetricsPodSelector,
hpaMetricName,
hpaName,
)
targetMemUtilThreshold := fmt.Sprintf(
`%s{%s} / 100`,
metricName,
kubeMetricsHPASelector,
)
return fmt.Sprintf(`%s * on(%s) %s`, requestMem, hpaMetricName, targetMemUtilThreshold)
}
func getKubeMetricsPodSelector(podSelectionRegex, namespace string) string {
return fmt.Sprintf(
`pod=~"%s",namespace="%s",container!="POD",container!=""`,
podSelectionRegex,
namespace,
)
}
func createHPACurrentReplicasQuery(metricName, hpaName, namespace, appLabel, hpaMetricName string) string {
kubeMetricsHPASelector := fmt.Sprintf(
`%s="%s",namespace="%s"`,
hpaMetricName,
hpaName,
namespace,
)
// the kube-state-metrics queries are less prone to error if the field app_kubernetes_io_instance is matched
// as well
if appLabel != "" {
kubeMetricsHPASelector += fmt.Sprintf(`,app_kubernetes_io_instance="%s"`, appLabel)
}
return fmt.Sprintf(
`%s{%s}`,
metricName,
kubeMetricsHPASelector,
)
}
type promRawValuesQuery struct {
Status string `json:"status"`
Data []string `json:"data"`
}
// getKubeHPAMetricName performs a "best guess" for the name of the kube HPA metric,
// which was renamed to kube_horizontalpodautoscaler... in later versions of kube-state-metrics.
// we query Prometheus for a list of metric names to see if any match the new query
// value, otherwise we return the deprecated name.
func getKubeHPAMetricName(
clientset kubernetes.Interface,
service *v1.Service,
opts *QueryOpts,
suffix string,
) (string, string) {
queryParams := map[string]string{
"match[]": fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix),
"start": fmt.Sprintf("%d", opts.StartRange),
"end": fmt.Sprintf("%d", opts.EndRange),
}
resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
"http",
service.Name,
fmt.Sprintf("%d", service.Spec.Ports[0].Port),
"/api/v1/label/__name__/values",
queryParams,
)
rawQuery, err := resp.DoRaw(context.TODO())
if err != nil {
return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
}
rawQueryObj := &promRawValuesQuery{}
json.Unmarshal(rawQuery, rawQueryObj)
if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
return fmt.Sprintf("kube_horizontalpodautoscaler_%s", suffix), "horizontalpodautoscaler"
}
return fmt.Sprintf("kube_hpa_%s", suffix), "hpa"
}
func getKubeCPUMetricName(
clientset kubernetes.Interface,
service *v1.Service,
opts *QueryOpts,
) string {
queryParams := map[string]string{
"match[]": "kube_pod_container_resource_requests",
"start": fmt.Sprintf("%d", opts.StartRange),
"end": fmt.Sprintf("%d", opts.EndRange),
}
resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
"http",
service.Name,
fmt.Sprintf("%d", service.Spec.Ports[0].Port),
"/api/v1/label/__name__/values",
queryParams,
)
rawQuery, err := resp.DoRaw(context.TODO())
if err != nil {
return "kube_pod_container_resource_requests_cpu_cores"
}
rawQueryObj := &promRawValuesQuery{}
json.Unmarshal(rawQuery, rawQueryObj)
if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
return "kube_pod_container_resource_requests"
}
return "kube_pod_container_resource_requests_cpu_cores"
}
func getKubeMemoryMetricName(
clientset kubernetes.Interface,
service *v1.Service,
opts *QueryOpts,
) string {
queryParams := map[string]string{
"match[]": "kube_pod_container_resource_requests",
"start": fmt.Sprintf("%d", opts.StartRange),
"end": fmt.Sprintf("%d", opts.EndRange),
}
resp := clientset.CoreV1().Services(service.Namespace).ProxyGet(
"http",
service.Name,
fmt.Sprintf("%d", service.Spec.Ports[0].Port),
"/api/v1/label/__name__/values",
queryParams,
)
rawQuery, err := resp.DoRaw(context.TODO())
if err != nil {
return "kube_pod_container_resource_requests_memory_bytes"
}
rawQueryObj := &promRawValuesQuery{}
json.Unmarshal(rawQuery, rawQueryObj)
if rawQueryObj.Status == "success" && len(rawQueryObj.Data) == 1 {
return "kube_pod_container_resource_requests"
}
return "kube_pod_container_resource_requests_memory_bytes"
}
|
package main
import (
"log"
"fmt"
"time"
"io/ioutil"
"net/http"
"strconv"
"encoding/json"
"github.com/gorilla/mux"
)
func checkTerminalVersion(version string) bool {
const LAST_CLIENT_VERSION = "2.3.1"
if version == LAST_CLIENT_VERSION {
return true
}
return false
}
func extractUint64(vars map[string]string, vname string) uint64 {
id, err := strconv.ParseUint(vars[vname], 10, 64)
if err != nil {
panic(fmt.Sprintf("Invalid %s format", vname))
}
return id
}
func TimeSyncHandler(w http.ResponseWriter, r *http.Request) {
receive_time := time.Now().UTC().UnixNano() / 1000000
log.Println("TIME", r.URL)
v := mux.Vars(r)
w.Write([]byte(fmt.Sprintf("%s:%d:%d",
v["begin_time"],
receive_time,
receive_time)))
}
func GetDataHandlerOld(w http.ResponseWriter, r *http.Request) {
ares := &DataResponse{ Error: &Error{ Text: "too old. Update your application" } }
json, _ := json.MarshalIndent(ares, "", " ")
w.Write(json)
}
func GetDataHandler(w http.ResponseWriter, r *http.Request) {
var ares DataResponse
var dreq DataRequest
defer func() {
if r := recover(); r != nil {
log.Println("!!!", "got error", r)
ares.Error = &Error{ Text: fmt.Sprintf("%s", r) }
}
json, _ := json.MarshalIndent(ares, "", " ")
w.Write(json)
}()
log.Println("DATA-REQ", r.URL)
v := mux.Vars(r)
id := extractUint64(v, "CompetitionId")
ts := extractUint64(v, "TimeStamp")
termString := v["TerminalString"]
UpdateTerminalActivity(termString)
term := GetTerminals(id, &termString, 0)
if len(term) != 1 {
panic("terminal not recognized")
}
err := json.NewDecoder(r.Body).Decode(&dreq)
if err != nil {
panic(err);
}
if( !checkTerminalVersion(dreq.Version) ) {
GetDataHandlerOld(w, r)
return
}
if term[0].Permissions.Read == true {
ares = GetCompetition(id, &termString, ts)
rstat := ares.RaceStatus
if ares.RaceStatus == nil {
rstat = GetRaceStatus(id);
}
if rstat.IsActive == nil || *rstat.IsActive == false {
panic("competition is closed")
}
} else {
panic("no read permissions")
}
}
func UpdateHandler(w http.ResponseWriter, r *http.Request) {
log.Println("DATA-NEW", r.URL)
var laps []Lap
var receive_time = uint64(time.Now().UTC().UnixNano() / 1000000)
defer func() {
if r := recover(); r != nil {
log.Println("!!!", "got error", r)
w.WriteHeader(http.StatusBadRequest)
} else {
w.Write([]byte("true"))
}
}()
v := mux.Vars(r)
CompetitionId := extractUint64(v, "CompetitionId")
termString := v["TerminalString"]
UpdateTerminalActivity(termString)
race := GetRaceStatus(CompetitionId)
if race == nil {
panic("Unknown Competition")
}
if race.IsActive == nil || *race.IsActive == false {
panic("competition is closed")
}
term := GetTerminals(CompetitionId, &termString, 0)
if len(term) != 1 {
panic("terminal not registered in competition")
}
if term[0].Permissions.Write == false {
panic("terminal have no write permissions")
}
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Println("!!!", "http body not readed", err)
panic("Invalid request")
}
err = json.Unmarshal(body, &laps)
if err != nil {
panic("Invalid json data")
}
UpdateLaps(CompetitionId, laps, uint64(receive_time))
// write log
data, _ := json.Marshal(laps)
SaveToJournal(CompetitionId,
receive_time,
v["TerminalString"],
fmt.Sprintf("%s", r.URL), data)
}
|
/*
* Copyright 2019, Offchain Labs, 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
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vm
import (
"github.com/offchainlabs/arb-util/machine"
"github.com/offchainlabs/arb-util/protocol"
"github.com/offchainlabs/arb-util/value"
)
type MachineAssertionContext struct {
machine *Machine
timeBounds protocol.TimeBounds
numSteps uint32
outMsgs []protocol.Message
logs []value.Value
}
func NewMachineAssertionContext(m *Machine, timeBounds protocol.TimeBounds) *MachineAssertionContext {
outMsgs := make([]protocol.Message, 0)
ret := &MachineAssertionContext{
m,
timeBounds,
0,
outMsgs,
make([]value.Value, 0),
}
ret.machine.SetContext(ret)
return ret
}
func (ac *MachineAssertionContext) LoggedValue(data value.Value) error {
ac.logs = append(ac.logs, data)
return nil
}
func (ac *MachineAssertionContext) Send(data value.Value, tokenType value.IntValue, currency value.IntValue, dest value.IntValue) error {
tokType := [21]byte{}
tokBytes := tokenType.ToBytes()
copy(tokType[:], tokBytes[:])
newMsg := protocol.NewMessage(data, tokType, currency.BigInt(), dest.ToBytes())
ac.outMsgs = append(ac.outMsgs, newMsg)
return nil
}
func (ac *MachineAssertionContext) OutMessageCount() int {
return len(ac.outMsgs)
}
func (ac *MachineAssertionContext) GetTimeBounds() value.Value {
return ac.timeBounds.AsValue()
}
func (ac *MachineAssertionContext) NotifyStep() {
ac.numSteps++
}
func (ac *MachineAssertionContext) Finalize(m *Machine) *protocol.Assertion {
ac.machine.SetContext(&machine.MachineNoContext{})
return protocol.NewAssertion(ac.machine.Hash(), ac.numSteps, ac.outMsgs, ac.logs)
}
func (ac *MachineAssertionContext) EndContext() {
ac.machine.SetContext(&machine.MachineNoContext{})
}
|
package conv
import (
"errors"
"image/jpeg"
"image/png"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
const (
contentTypeJPEG = "image/jpeg"
contentTypePNG = "image/png"
contentTypeOther = "application/octet-stream"
extensionJPEG = ".jpg"
extensionPNG = ".png"
)
// Indecates file destination to convert.
type fileDest struct {
from *os.File
to *os.File
}
// ConvertImages converts an image file with an extension to another specified by "extFrom" and "extTo" in "destDir" directory.
func ConvertImages(destDir, extFrom, extTo string) error {
if extFrom == extTo {
return errors.New("specified extensions must be distinct")
}
return filepath.Walk(destDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(path, extFrom) {
err = convert(path, extFrom, extTo)
}
return err
})
}
// Convert all the image files with a specified extension under target directory to another file with anotehr extension.
func convert(filepathFrom, extFrom, extTo string) error {
from, err := os.Open(filepathFrom)
if err != nil {
return err
}
defer from.Close()
filepathTo := strings.TrimSuffix(filepathFrom, extFrom) + extTo
to, err := os.Create(filepathTo)
if err != nil {
return err
}
defer to.Close()
switch {
case extFrom == extensionJPEG && extTo == extensionPNG:
err = jpegToPNG(fileDest{from, to})
case extFrom == extensionPNG && extTo == extensionJPEG:
err = pngToJPEG(fileDest{from, to})
default:
err = errors.New("unsupported extension combination to covert from: " + extFrom + " to: " + extTo)
}
if err != nil {
defer os.Remove(filepathTo)
}
return err
}
// Convert an image file from jpeg to png.
func jpegToPNG(dest fileDest) error {
if !isJPEG(dest.from) {
return errors.New("content type of the original file is not " + contentTypeJPEG)
}
jpegImg, err := jpeg.Decode(dest.from)
if err != nil {
return err
}
png.Encode(dest.to, jpegImg)
return nil
}
// Convert an image file from png to jpeg.
func pngToJPEG(dest fileDest) error {
if !isPNG(dest.from) {
return errors.New("content type of the original file is not " + contentTypePNG)
}
pngImg, err := png.Decode(dest.from)
if err != nil {
return err
}
return jpeg.Encode(dest.to, pngImg, nil)
}
// Determine if the content type of a given file is image/jpeg
func isJPEG(file *os.File) bool {
contentType, _ := getFileContentType(file)
return contentType == contentTypeJPEG
}
// Determine if the content type of a given file is image/png
func isPNG(file *os.File) bool {
contentType, _ := getFileContentType(file)
return contentType == contentTypePNG
}
// Detect content type from the first 512 bytes of a given file.
func getFileContentType(file *os.File) (string, error) {
// Using the first 512 bytes to detect the content type.
buffer := make([]byte, 512)
_, err := file.Read(buffer)
// Reset the file pointer
file.Seek(0, io.SeekStart)
if err != nil {
return "", err
}
return http.DetectContentType(buffer), nil
}
|
// Copyright 2021 - 2021 The goword Authors. All rights reserved. Use of
// this source code is governed by a MIT license that can be found in
// the LICENSE file.
//
// Package goword providing a set of functions that allow you to write to
// and read from DOCX files. Supports reading and writing
// wordprocessing documents generated by Microsoft Word™ 2007 and later.
// This library needs Go version 1.15 or later.
package elements
// HexColor is a union type
type HexColor struct {
HexColorAuto HexColorAuto
HexColorRGB *string
}
|
// Copyright (c) 2017 Kuguar <licenses@kuguar.io> Author: Adrian P.K. <apk@kuguar.io>
//
// MIT License
//
// 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,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package routers
import (
"github.com/adrianpk/fundacja/bootstrap"
"github.com/adrianpk/fundacja/api"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
)
// InitAPIAvatarRouter - Initialize API router for profile avatar.
func InitAPIAvatarRouter() *mux.Router {
// Paths
avatarPath := "/users/{user}/profile/avatar"
// Router
avatarRouter := apiV1Router.PathPrefix(avatarPath).Subrouter()
// Resource
avatarRouter.HandleFunc("", api.HandleAvatar)
// Middleware
apiV1Router.Handle(avatarPath, negroni.New(
negroni.HandlerFunc(bootstrap.Authorize),
negroni.Wrap(avatarRouter),
))
return avatarRouter
}
|
// https://www.hackerrank.com/challenges/30-recursion
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
func main() {
n := answer(os.Stdin)
fmt.Println(n)
}
func answer(input io.Reader) int {
in := bufio.NewReader(input)
line, err := in.ReadString('\n')
if err != nil {
if err != io.EOF {
return -1
}
}
n, err := strconv.Atoi(strings.TrimSpace(line))
if err != nil {
return -2
}
return factorial(n)
}
func factorial(n int) int {
if n > 1 {
return n * factorial(n-1)
}
return 1
}
|
package cpu
import (
"github.com/elastic/beats/metricbeat/mb"
"github.com/elastic/beats/libbeat/common"
)
func init() {
if err := mb.Registry.AddMetricSet("use", "cpu", New); err != nil {
panic(err)
}
}
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
return &CPUMetricSet{
BaseMetricSet: base,
},nil
}
type CPUMetricSet struct {
mb.BaseMetricSet
}
func (m *CPUMetricSet) Fetch() (event common.MapStr, err error) {
return common.MapStr{"hello": "world"},nil
} |
package main
import (
// "net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/YanshuoH/douban-reading-stat/db"
"github.com/YanshuoH/douban-reading-stat/controllers"
"github.com/YanshuoH/douban-reading-stat/middlewares"
)
const (
// Port at which the server starts listening
Port = "3000"
)
func init() {
db.Connect()
}
func main() {
// Configure Gin
router := gin.Default()
// Set html render options
router.LoadHTMLGlob("./templates/*")
router.RedirectTrailingSlash = true
router.RedirectFixedPath = true
// Middlewares
router.Use(middlewares.ConnectDb)
// Statics
router.Static("/public", "./public")
// Routing list
router.GET("/", controllers.Index)
router.GET("/user/:userId", controllers.StatPage)
router.GET("/api/user", controllers.SearchUser)
router.GET("/api/user/:userId", controllers.GetUser)
// Start listening
port := Port
if len(os.Getenv("PORT")) > 0 {
port = os.Getenv("PORT")
}
router.Run(":" + port)
}
|
// +build tools
package tools
// go install github.com/golangci/golangci-lint/cmd/golangci-lint github.com/MarioCarrion/nit/cmd/nit
import (
_ "github.com/MarioCarrion/nit/cmd/nit"
_ "github.com/golangci/golangci-lint/cmd/golangci-lint"
)
|
package Contains_Duplicate_II
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestOK(t *testing.T) {
ast := assert.New(t)
ast.Equal(containsNearbyDuplicate([]int{1, 2, 3, 4, 5, 1}, 3), false)
ast.Equal(containsNearbyDuplicate([]int{1, 2, 3, 1}, 3), true)
ast.Equal(containsNearbyDuplicate([]int{1, 0, 1, 1}, 1), true)
ast.Equal(containsNearbyDuplicate([]int{1, 2, 3, 1, 2, 3}, 2), false)
}
|
package entity
type ClientModifyRequestParam struct {
AccessToken string `json:"access_token"`
Tags []string `json:"tags"`
// TODO配列にする
ItemIDs string `json:"item_ids"`
}
type ModifyRequestParam struct {
ConsumerKey string `json:"consumer_key"`
AccessToken string `json:"access_token"`
Actions []*ModifyAction `json:"actions"`
}
type ModifyAction struct {
Action string `json:"action"`
ItemID string `json:"item_id"`
Tags []string `json:"tags"`
}
type ActionResult struct {
Status int `json:"status"`
}
|
package dbschedules
// Recoverable checks if a schedule is recoverable.
// The schedule should not contain any Abort actions.
func Recoverable(s Schedule) bool {
lastWrite := map[string]string{}
committed := map[string]bool{"": true}
deps := map[string]map[string]bool{}
for _, t := range s.Transactions() {
deps[t] = map[string]bool{}
}
for _, x := range s {
switch x.Type {
case Commit:
committed[x.Transaction] = true
for t := range deps[x.Transaction] {
if !committed[t] {
return false
}
}
case Read:
deps[x.Transaction][lastWrite[x.Object]] = true
case Write:
lastWrite[x.Object] = x.Transaction
}
}
return true
}
// ACA checks if a schedule avoids cascading aborts.
func ACA(s Schedule) bool {
return acaOrStrict(s, false)
}
// Strict checks if a schedule is strict.
func Strict(s Schedule) bool {
return acaOrStrict(s, true)
}
func acaOrStrict(s Schedule, strict bool) bool {
objectLocks := map[string]string{}
for _, x := range s {
switch x.Type {
case Write:
if strict {
if trans, ok := objectLocks[x.Object]; ok && trans != x.Transaction {
return false
}
}
objectLocks[x.Object] = x.Transaction
case Read:
if trans, ok := objectLocks[x.Object]; ok && trans != x.Transaction {
return false
}
case Commit, Abort:
freeObjs := map[string]bool{}
for obj, t := range objectLocks {
if t == x.Transaction {
freeObjs[obj] = true
}
}
for x := range freeObjs {
delete(objectLocks, x)
}
}
}
return true
}
|
package raws // import "github.com/BenLubar/dfide/raws"
import (
"reflect"
"strconv"
"strings"
"sync"
)
type stringOrIndex struct {
String string
Index int
}
func makeIndexString(s string) []stringOrIndex {
parts := strings.Split(s, ".")
converted := make([]stringOrIndex, len(parts))
for i, p := range parts {
if n, err := strconv.Atoi(p); err == nil {
converted[i].Index = n
} else {
converted[i].String = p
}
}
return converted
}
type structTag struct {
Name []stringOrIndex
Char bool
Union bool
}
var structTagElements = func() map[string]reflect.StructField {
m := make(map[string]reflect.StructField)
t := reflect.TypeOf(structTag{})
for i, n := 0, t.NumField(); i < n; i++ {
f := t.Field(i)
if f.Name == "Name" {
continue
}
m[strings.ToLower(f.Name)] = f
}
return m
}()
func parseStructTag(t reflect.StructTag) *structTag {
s, ok := t.Lookup("raws")
if !ok {
return nil
}
parts := strings.Split(s, ",")
if len(parts) == 0 || parts[0] == "" {
panic("raws: invalid struct tag")
}
st := &structTag{
Name: makeIndexString(parts[0]),
}
v := reflect.ValueOf(st).Elem()
for i := 1; i < len(parts); i++ {
f, ok := structTagElements[parts[i]]
if !ok {
panic("raws: invalid struct tag: no such flag: " + parts[i])
}
vf := v.FieldByIndex(f.Index)
if vf.Bool() {
panic("raws: invalid struct tag: duplicate flag: " + parts[i])
}
vf.SetBool(true)
}
if st.Union && (len(st.Name) != 1 || st.Name[0].String == "") {
panic("raws: invalid struct tag: union must have simple name")
}
return st
}
type typeDescription struct {
union bool
fields []reflect.StructField
tags []structTag
}
var typeDescriptions = make(map[reflect.Type]*typeDescription)
var typeDescriptionLock sync.Mutex
func getTypeDescription(t reflect.Type) *typeDescription {
typeDescriptionLock.Lock()
defer typeDescriptionLock.Unlock()
return getTypeDescriptionLocked(t)
}
func getTypeDescriptionLocked(t reflect.Type) *typeDescription {
if t.Kind() == reflect.Slice {
t = t.Elem()
}
if d, ok := typeDescriptions[t]; ok {
return d
}
d := &typeDescription{}
for i, n := 0, t.NumField(); i < n; i++ {
f := t.Field(i)
st := parseStructTag(f.Tag)
if st != nil {
if st.Char && f.Type.Kind() != reflect.Int32 &&
(f.Type.Kind() != reflect.Slice || f.Type.Elem().Kind() != reflect.Int32) {
panic("raws: invalid struct tag: char flag can only be used on rune or []rune")
}
if st.Union && f.Type.Kind() != reflect.Ptr {
panic("raws: invalid struct tag: union flag can only be used on pointer")
}
d.fields = append(d.fields, f)
d.tags = append(d.tags, *st)
}
}
if len(d.tags) == 0 {
typeDescriptions[t] = nil
return nil
}
if d.tags[0].Union {
for _, t := range d.tags {
if !t.Union {
panic("raws: if a struct is a union, all fields of the struct must be tagged")
}
}
d.union = true
}
typeDescriptions[t] = d
return d
}
|
package crawler
import (
"context"
"fmt"
log "git.ronaksoftware.com/blip/server/internal/logger"
"git.ronaksoftware.com/blip/server/internal/pools"
"git.ronaksoftware.com/blip/server/internal/tools"
"git.ronaksoftware.com/blip/server/pkg/config"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
"go.uber.org/zap"
"io/ioutil"
"net/http"
"net/url"
)
/*
Creation Time: 2019 - Nov - 10
Created by: (ehsan)
Maintainers:
1. Ehsan N. Moosa (E2)
Auditor: Ehsan N. Moosa (E2)
Copyright Ronak Software Group 2018
*/
// DropAll deletes all the crawlers from the database
func DropAll() error {
return crawlerCol.Drop(nil)
}
// Save insert the crawler 'c' into the database
func Save(crawlerX *Crawler) (primitive.ObjectID, error) {
if crawlerX.ID == primitive.NilObjectID {
crawlerX.ID = primitive.NewObjectID()
}
_, err := crawlerCol.UpdateOne(nil, bson.M{"_id": crawlerX.ID}, bson.M{"$set": crawlerX}, options.Update().SetUpsert(true))
if err != nil {
return primitive.NilObjectID, err
}
return crawlerX.ID, err
}
// Get returns a crawler identified by 'crawlerID'
func Get(crawlerID primitive.ObjectID) (*Crawler, error) {
res := crawlerCol.FindOne(nil, bson.M{"_id": crawlerID}, options.FindOne())
c := &Crawler{}
err := res.Decode(c)
if err != nil {
return nil, err
}
return c, nil
}
// GetAll returns an array of the registered crawlers
func GetAll() []*Crawler {
list := make([]*Crawler, 0, 10)
registeredCrawlersMtx.RLock()
for _, crawlers := range registeredCrawlers {
list = append(list, crawlers...)
}
registeredCrawlersMtx.RUnlock()
return list
}
// Remove removes the crawler from the database
func Remove(crawlerID primitive.ObjectID) error {
_, err := crawlerCol.DeleteOne(nil, bson.M{"_id": crawlerID})
return err
}
// Search sends search request to all the crawlers and pushes the result into the channel.
// Crawlers are categorized with their 'Source' tag.
func Search(ctx context.Context, keyword string) <-chan *SearchResponse {
crawlers := getRegisteredCrawlers()
if len(crawlers) == 0 {
log.Warn("No Crawler has been Registered")
return nil
}
resChan := make(chan *SearchResponse, len(crawlers))
go func() {
defer putRegisteredCrawlers(crawlers)
waitGroup := pools.AcquireWaitGroup()
for _, c := range crawlers {
waitGroup.Add(1)
go func(c *Crawler) {
defer waitGroup.Done()
res, err := c.SendRequest(ctx, keyword)
if err != nil {
log.Warn("Error On Crawler Request",
zap.Error(err),
zap.String("CrawlerUrl", c.Url),
zap.String("Keyword", keyword),
)
return
}
resChan <- res
}(c)
}
waitGroup.Wait()
pools.ReleaseWaitGroup(waitGroup)
close(resChan)
}()
return resChan
}
func getRegisteredCrawlers() []*Crawler {
list, ok := registeredCrawlersPool.Get().([]*Crawler)
if ok {
return list
}
list = make([]*Crawler, 0, len(registeredCrawlers))
registeredCrawlersMtx.RLock()
for _, crawlers := range registeredCrawlers {
idx := tools.RandomInt(len(crawlers))
list = append(list, crawlers[idx])
}
registeredCrawlersMtx.RUnlock()
return list
}
func putRegisteredCrawlers(list []*Crawler) {
registeredCrawlersPool.Put(list)
}
// Crawler
type Crawler struct {
httpClient http.Client `bson:"-"`
ID primitive.ObjectID `bson:"_id" json:"id"`
Url string `bson:"url" json:"url"`
Name string `bson:"name" json:"name"`
Description string `bson:"desc" json:"description"`
Source string `bson:"source" json:"source"`
DownloaderJobs int `bson:"downloader_jobs" json:"downloader_jobs"`
}
func (c *Crawler) SendRequest(ctx context.Context, keyword string) (*SearchResponse, error) {
if ctx == nil {
ctx = context.Background()
}
c.httpClient.Timeout = config.HttpRequestTimeout
crawlerUrl := fmt.Sprintf("%s/%s/%s", c.Url, tools.RandomID(24), url.PathEscape(keyword))
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, crawlerUrl, nil)
if err != nil {
return nil, err
}
httpRes, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, err
}
if httpRes.StatusCode != http.StatusOK && httpRes.StatusCode != http.StatusAccepted {
return nil, fmt.Errorf("invalid http response, got %d", httpRes.StatusCode)
}
resBytes, err := ioutil.ReadAll(httpRes.Body)
if err != nil {
return nil, err
}
res := &SearchResponse{}
err = res.UnmarshalJSON(resBytes)
if err != nil {
return nil, err
}
return res, nil
}
|
// Copyright 2020 Liquidata, 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
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doltdb
import (
"context"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dolthub/dolt/go/libraries/doltcore/dbfactory"
"github.com/dolthub/dolt/go/libraries/doltcore/row"
"github.com/dolthub/dolt/go/libraries/doltcore/schema"
"github.com/dolthub/dolt/go/store/types"
)
// The number of times we will loop through the tests to ensure consistent results
const indexEditorConcurrencyIterations = 1000
// The number of rows we expect the test to end up with
const indexEditorConcurrencyFinalCount = 100
func TestIndexEditorConcurrency(t *testing.T) {
format := types.Format_7_18
db, err := dbfactory.MemFactory{}.CreateDB(context.Background(), format, nil, nil)
require.NoError(t, err)
colColl, err := schema.NewColCollection(
schema.NewColumn("pk", 0, types.IntKind, true),
schema.NewColumn("v1", 1, types.IntKind, false),
schema.NewColumn("v2", 2, types.IntKind, false))
require.NoError(t, err)
tableSch := schema.SchemaFromCols(colColl)
index, err := tableSch.Indexes().AddIndexByColNames("idx_concurrency", []string{"v1"}, schema.IndexProperties{IsUnique: false, Comment: ""})
require.NoError(t, err)
indexSch := index.Schema()
emptyMap, err := types.NewMap(context.Background(), db)
require.NoError(t, err)
for i := 0; i < indexEditorConcurrencyIterations; i++ {
indexEditor := NewIndexEditor(index, emptyMap)
wg := &sync.WaitGroup{}
for j := 0; j < indexEditorConcurrencyFinalCount*2; j++ {
wg.Add(1)
go func(val int) {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), nil, dRow))
wg.Done()
}(j)
}
wg.Wait()
for j := 0; j < indexEditorConcurrencyFinalCount; j++ {
wg.Add(1)
go func(val int) {
dOldRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val),
})
require.NoError(t, err)
dNewRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val + 1),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), dOldRow, dNewRow))
wg.Done()
}(j)
}
// We let the Updates and Deletes execute at the same time
for j := indexEditorConcurrencyFinalCount; j < indexEditorConcurrencyFinalCount*2; j++ {
wg.Add(1)
go func(val int) {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), dRow, nil))
wg.Done()
}(j)
}
wg.Wait()
newIndexData, err := indexEditor.Map(context.Background())
require.NoError(t, err)
if assert.Equal(t, uint64(indexEditorConcurrencyFinalCount), newIndexData.Len()) {
iterIndex := 0
_ = newIndexData.IterAll(context.Background(), func(key, value types.Value) error {
dReadRow, err := row.FromNoms(indexSch, key.(types.Tuple), value.(types.Tuple))
require.NoError(t, err)
dReadVals, err := row.GetTaggedVals(dReadRow)
require.NoError(t, err)
assert.Equal(t, row.TaggedValues{
0: types.Int(iterIndex),
1: types.Int(iterIndex + 1),
}, dReadVals)
iterIndex++
return nil
})
}
}
}
func TestIndexEditorConcurrencyPostInsert(t *testing.T) {
format := types.Format_7_18
db, err := dbfactory.MemFactory{}.CreateDB(context.Background(), format, nil, nil)
require.NoError(t, err)
colColl, err := schema.NewColCollection(
schema.NewColumn("pk", 0, types.IntKind, true),
schema.NewColumn("v1", 1, types.IntKind, false),
schema.NewColumn("v2", 2, types.IntKind, false))
require.NoError(t, err)
tableSch := schema.SchemaFromCols(colColl)
index, err := tableSch.Indexes().AddIndexByColNames("idx_concurrency", []string{"v1"}, schema.IndexProperties{IsUnique: false, Comment: ""})
require.NoError(t, err)
indexSch := index.Schema()
emptyMap, err := types.NewMap(context.Background(), db)
require.NoError(t, err)
indexEditor := NewIndexEditor(index, emptyMap)
for i := 0; i < indexEditorConcurrencyFinalCount*2; i++ {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(i),
1: types.Int(i),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), nil, dRow))
}
indexData, err := indexEditor.Map(context.Background())
require.NoError(t, err)
for i := 0; i < indexEditorConcurrencyIterations; i++ {
indexEditor := NewIndexEditor(index, indexData)
wg := &sync.WaitGroup{}
for j := 0; j < indexEditorConcurrencyFinalCount; j++ {
wg.Add(1)
go func(val int) {
dOldRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val),
})
require.NoError(t, err)
dNewRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val + 1),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), dOldRow, dNewRow))
wg.Done()
}(j)
}
for j := indexEditorConcurrencyFinalCount; j < indexEditorConcurrencyFinalCount*2; j++ {
wg.Add(1)
go func(val int) {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), dRow, nil))
wg.Done()
}(j)
}
wg.Wait()
newIndexData, err := indexEditor.Map(context.Background())
require.NoError(t, err)
if assert.Equal(t, uint64(indexEditorConcurrencyFinalCount), newIndexData.Len()) {
iterIndex := 0
_ = newIndexData.IterAll(context.Background(), func(key, value types.Value) error {
dReadRow, err := row.FromNoms(indexSch, key.(types.Tuple), value.(types.Tuple))
require.NoError(t, err)
dReadVals, err := row.GetTaggedVals(dReadRow)
require.NoError(t, err)
assert.Equal(t, row.TaggedValues{
0: types.Int(iterIndex),
1: types.Int(iterIndex + 1),
}, dReadVals)
iterIndex++
return nil
})
}
}
}
func TestIndexEditorConcurrencyUnique(t *testing.T) {
format := types.Format_7_18
db, err := dbfactory.MemFactory{}.CreateDB(context.Background(), format, nil, nil)
require.NoError(t, err)
colColl, err := schema.NewColCollection(
schema.NewColumn("pk", 0, types.IntKind, true),
schema.NewColumn("v1", 1, types.IntKind, false),
schema.NewColumn("v2", 2, types.IntKind, false))
require.NoError(t, err)
tableSch := schema.SchemaFromCols(colColl)
index, err := tableSch.Indexes().AddIndexByColNames("idx_concurrency", []string{"v1"}, schema.IndexProperties{IsUnique: true, Comment: ""})
require.NoError(t, err)
indexSch := index.Schema()
emptyMap, err := types.NewMap(context.Background(), db)
require.NoError(t, err)
for i := 0; i < indexEditorConcurrencyIterations; i++ {
indexEditor := NewIndexEditor(index, emptyMap)
wg := &sync.WaitGroup{}
for j := 0; j < indexEditorConcurrencyFinalCount*2; j++ {
wg.Add(1)
go func(val int) {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), nil, dRow))
wg.Done()
}(j)
}
wg.Wait()
for j := 0; j < indexEditorConcurrencyFinalCount; j++ {
wg.Add(1)
go func(val int) {
dOldRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val),
})
require.NoError(t, err)
dNewRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val + 1),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), dOldRow, dNewRow))
wg.Done()
}(j)
}
// We let the Updates and Deletes execute at the same time
for j := indexEditorConcurrencyFinalCount; j < indexEditorConcurrencyFinalCount*2; j++ {
wg.Add(1)
go func(val int) {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(val),
1: types.Int(val),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), dRow, nil))
wg.Done()
}(j)
}
wg.Wait()
newIndexData, err := indexEditor.Map(context.Background())
require.NoError(t, err)
if assert.Equal(t, uint64(indexEditorConcurrencyFinalCount), newIndexData.Len()) {
iterIndex := 0
_ = newIndexData.IterAll(context.Background(), func(key, value types.Value) error {
dReadRow, err := row.FromNoms(indexSch, key.(types.Tuple), value.(types.Tuple))
require.NoError(t, err)
dReadVals, err := row.GetTaggedVals(dReadRow)
require.NoError(t, err)
assert.Equal(t, row.TaggedValues{
0: types.Int(iterIndex),
1: types.Int(iterIndex + 1),
}, dReadVals)
iterIndex++
return nil
})
}
}
}
func TestIndexEditorUniqueMultipleNil(t *testing.T) {
format := types.Format_7_18
db, err := dbfactory.MemFactory{}.CreateDB(context.Background(), format, nil, nil)
require.NoError(t, err)
colColl, err := schema.NewColCollection(
schema.NewColumn("pk", 0, types.IntKind, true),
schema.NewColumn("v1", 1, types.IntKind, false))
require.NoError(t, err)
tableSch := schema.SchemaFromCols(colColl)
index, err := tableSch.Indexes().AddIndexByColNames("idx_unique", []string{"v1"}, schema.IndexProperties{IsUnique: true, Comment: ""})
require.NoError(t, err)
indexSch := index.Schema()
emptyMap, err := types.NewMap(context.Background(), db)
require.NoError(t, err)
indexEditor := NewIndexEditor(index, emptyMap)
for i := 0; i < 3; i++ {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.NullValue,
1: types.Int(i),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), nil, dRow))
}
newIndexData, err := indexEditor.Map(context.Background())
require.NoError(t, err)
if assert.Equal(t, uint64(3), newIndexData.Len()) {
index := 0
_ = newIndexData.IterAll(context.Background(), func(key, value types.Value) error {
dReadRow, err := row.FromNoms(indexSch, key.(types.Tuple), value.(types.Tuple))
require.NoError(t, err)
dReadVals, err := row.GetTaggedVals(dReadRow)
require.NoError(t, err)
assert.Equal(t, row.TaggedValues{
1: types.Int(index), // We don't encode NULL values
}, dReadVals)
index++
return nil
})
}
}
func TestIndexEditorWriteAfterFlush(t *testing.T) {
format := types.Format_7_18
db, err := dbfactory.MemFactory{}.CreateDB(context.Background(), format, nil, nil)
require.NoError(t, err)
colColl, err := schema.NewColCollection(
schema.NewColumn("pk", 0, types.IntKind, true),
schema.NewColumn("v1", 1, types.IntKind, false),
schema.NewColumn("v2", 2, types.IntKind, false))
require.NoError(t, err)
tableSch := schema.SchemaFromCols(colColl)
index, err := tableSch.Indexes().AddIndexByColNames("idx_concurrency", []string{"v1"}, schema.IndexProperties{IsUnique: false, Comment: ""})
require.NoError(t, err)
indexSch := index.Schema()
emptyMap, err := types.NewMap(context.Background(), db)
require.NoError(t, err)
indexEditor := NewIndexEditor(index, emptyMap)
require.NoError(t, err)
for i := 0; i < 20; i++ {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(i),
1: types.Int(i),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), nil, dRow))
}
require.NoError(t, indexEditor.Flush(context.Background()))
for i := 10; i < 20; i++ {
dRow, err := row.New(format, indexSch, row.TaggedValues{
0: types.Int(i),
1: types.Int(i),
})
require.NoError(t, err)
require.NoError(t, indexEditor.UpdateIndex(context.Background(), dRow, nil))
}
newIndexData, err := indexEditor.Map(context.Background())
require.NoError(t, err)
if assert.Equal(t, uint64(10), newIndexData.Len()) {
iterIndex := 0
_ = newIndexData.IterAll(context.Background(), func(key, value types.Value) error {
dReadRow, err := row.FromNoms(indexSch, key.(types.Tuple), value.(types.Tuple))
require.NoError(t, err)
dReadVals, err := row.GetTaggedVals(dReadRow)
require.NoError(t, err)
assert.Equal(t, row.TaggedValues{
0: types.Int(iterIndex),
1: types.Int(iterIndex),
}, dReadVals)
iterIndex++
return nil
})
}
sameIndexData, err := indexEditor.Map(context.Background())
require.NoError(t, err)
assert.True(t, sameIndexData.Equals(newIndexData))
}
|
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
timeout := make(chan int, 1)
go func() {
// time.Sleep(time.Second)
timeout <- 1
}()
go func() {
// time.Sleep(time.Second)
ch <- 30
}()
time.Sleep(time.Second)
// 监听channel上数据流动, ch,timeout 谁先来,随机选择执行
select {
case <-ch:
fmt.Println("come to read ch!")
case <-timeout:
fmt.Println("come to timeout!")
// default: // 如果上面都没有成功,则进入 default 处理流程
// fmt.Println("default执行语句")
}
} |
package basic
import "fmt"
func VariableGo() {
fmt.Println("hello world")
/*
VALUES
*/
fmt.Println("go" + "lang")
fmt.Println("Penjumlahan 1+1 = ", 1+1)
fmt.Println("Float 7.0/3.0 = ", 7.0/3.0)
fmt.Println(true && false)
/*
Variables
- bisa diclare 1 atau lebih variable sekaligus
- go langsung bs tau tipe variable dari nilai yang disikan
- variabel yg ga diisi nilai nya akan disikan nilai default
int, float = 0
string = '',
boolean = false
- syntax := dipake buat initialize variable baru
- const variabel sama kayak di js gbs di assign lagi constant
*/
var a, b int = 1, 2
fmt.Println(a, b)
var name = "aji"
fmt.Println("nama saya : ", name)
var isBoolean bool
fmt.Println(isBoolean)
myHobbies := "Playing Football"
fmt.Println(myHobbies)
const n = 500000
fmt.Println(n)
}
|
package handlers
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"github.com/Volkov-D-A/vk-stitch-bot/pkg/config"
"github.com/Volkov-D-A/vk-stitch-bot/pkg/services"
"github.com/Volkov-D-A/vk-stitch-bot/pkg/models"
"github.com/Volkov-D-A/vk-stitch-bot/pkg/logs"
)
var (
errSecretMismatch = errors.New("secrets from api and local do not match")
errWrongGroupId = errors.New("VK group ID from VK api is invalid")
)
//CallbackHandler base struct for callback handler
type CallbackHandler struct {
services *services.Services
logger *logs.Logger
config *config.Config
}
//NewCallbackHandler return a new callback handler
func NewCallbackHandler(services *services.Services, logger *logs.Logger, config *config.Config) *CallbackHandler {
return &CallbackHandler{
services: services,
logger: logger,
config: config,
}
}
//Post base handler for callback requests from VK api
func (cb *CallbackHandler) Post(w http.ResponseWriter, r *http.Request) {
//Check type of event
req := models.CallbackRequest{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
cb.logger.Errorf("error while decoding JSON: %v", err)
return
}
//Check group id in callback request from api
if req.GroupId.String() != cb.config.VK.Group {
cb.logger.Error(errWrongGroupId)
return
}
//Check secret in callback request from api
if req.Secret != cb.config.Callback.Secret {
cb.logger.Error(errSecretMismatch)
return
}
// Switch action while type of event is
switch req.EventType {
case "confirmation":
if err = cb.handleConfirmationEvent(w); err != nil {
cb.logger.Errorf("error while handling confirmation event: %v", err)
}
return
case "message_deny":
if err = cb.handleMessageDenyEvent(&req); err != nil {
cb.logger.Errorf("error while handling message_deny event: %v", err)
}
case "message_allow":
if err = cb.handleMessageAllowEvent(&req); err != nil {
cb.logger.Errorf("error while handling message_allow event: %v", err)
}
case "message_new":
if err = cb.handleMessageNewEvent(&req); err != nil {
cb.logger.Errorf("error while handling message_new event: %v", err)
}
}
w.WriteHeader(http.StatusOK)
_, err = w.Write([]byte("ok"))
if err != nil {
cb.logger.Errorf("error while sending response to VK api: %v", err)
}
}
//InitRoutes initializing routes for callback handler
func (cb *CallbackHandler) InitRoutes() *http.ServeMux {
//Route handlers
mux := http.NewServeMux()
mux.HandleFunc("/callback", cb.Post)
return mux
}
//handleConfirmationEvent handle confirmation event from callback api
func (cb *CallbackHandler) handleConfirmationEvent(w http.ResponseWriter) error {
err := cb.services.SendConfirmationResponse(w)
if err != nil {
return fmt.Errorf("error while sending confirmation response: %v", err)
}
return nil
}
//handleMessageAllowEvent handle message_allow event from callback api
func (cb *CallbackHandler) handleMessageAllowEvent(req *models.CallbackRequest) error {
ma := models.MessageAllow{}
if err := json.Unmarshal(req.EventObject, &ma); err != nil {
return fmt.Errorf("error while unmarshaling 'message_allow' event object: %v", err)
}
if err := cb.services.Messaging.AddRecipient(&models.MessageRecipient{Id: ma.UserId}); err != nil {
return fmt.Errorf("error while adding recipient %v", err)
}
return nil
}
//handleMessageDenyEvent handle message_deny event from callback api
func (cb *CallbackHandler) handleMessageDenyEvent(req *models.CallbackRequest) error {
md := models.MessageDeny{}
if err := json.Unmarshal(req.EventObject, &md); err != nil {
return fmt.Errorf("error while unmarshaling 'message_deny' event object: %v", err)
}
if err := cb.services.Messaging.DeleteRecipient(&models.MessageRecipient{Id: md.UserId}); err != nil {
return fmt.Errorf("error while deleting recipient %v", err)
}
return nil
}
//handleNewMessageEvent handle new_message callback request and if contains target string sending reply message and bot keyboard
func (cb *CallbackHandler) handleMessageNewEvent(req *models.CallbackRequest) error {
ms := models.TypeMessageNew{}
if err := json.Unmarshal(req.EventObject, &ms); err != nil {
return fmt.Errorf("error while unmarshaling 'message_new' event object: %v", err)
}
//Case 1: Interesting product -> sending bot keyboard
if (strings.Contains(ms.Message.MessageText, "Меня заинтересовал этот товар.") || strings.Contains(ms.Message.MessageText, "Меня заинтересовал данный товар.")) && (ms.MessageFromId == 50126581 || ms.MessageFromId == 22478488) {
if err := cb.services.Keyboard.SendProductKeyboard(&models.MessageRecipient{Id: ms.MessageFromId}); err != nil {
return fmt.Errorf("error sending product keyboard: %v", err)
}
}
//Case 2: Pushed button with payload -> sending reply to user
if ms.MessagePayload != "" {
pl := models.Payload{}
if err := json.Unmarshal([]byte(ms.Message.MessagePayload), &pl); err != nil {
return fmt.Errorf("error unmarshalling payload: %v", err)
}
if err := cb.services.ReplyToKeyboard(&pl, &models.MessageRecipient{Id: ms.MessageFromId}); err != nil {
return fmt.Errorf("error while sending reply to keyboard push: %v", err)
}
}
//Case 3: Service message -> do mailing message to recipients
//if strings.Contains(ms.Message.MessageText, "@@@!@@@") && ms.MessageFromId == 22478488 {
// // Mailing
//}
return nil
}
|
package main
import (
"net"
)
type XClient struct {
UserID int64
client *net.Conn
}
func (c *XClient) Login() {
}
func (c *XClient) Ping() {
}
|
package models
import (
"github.com/mobilemindtec/go-utils/beego/db"
)
type Cidade struct {
Id int64 `form:"-" json:",string,omitempty"`
Nome string `orm:"size(100)" valid:"Required;MaxSize(100)" form:""`
Estado *Estado `orm:"rel(fk);on_delete(do_nothing)" valid:"Required;" form:""`
Session *db.Session `orm:"-" json:"-" inject:""`
}
func NewCidade(session *db.Session) *Cidade {
return &Cidade{Session: session}
}
func (this *Cidade) TableName() string {
return "cidades"
}
func (this *Cidade) IsPersisted() bool {
return this.Id > 0
}
func (this *Cidade) LoadRelated(entity *Cidade) {
this.Session.GetDb().LoadRelated(entity, "Estado")
}
func (this *Cidade) ListByEstado(estado *Estado) (*[]*Cidade, error) {
var results []*Cidade
query, err := this.Session.Query(this)
if err != nil {
return nil, err
}
if err := this.Session.ToList(query.Filter("Estado", estado), &results); err != nil {
return nil, err
}
return &results, err
}
func (this *Cidade) FindByNameAndEstado(nome string, estado *Estado) (*Cidade, error) {
result := new(Cidade)
criteria := db.NewCriteria(this.Session, result, nil).Eq("Nome", nome).Eq("Estado", estado).One()
return result, criteria.Error
}
func (this *Cidade) FindByNameAndEstadoUf(nome string, uf string) (*Cidade, error) {
result := new(Cidade)
criteria := db.NewCriteria(this.Session, result, nil).Eq("Nome", nome).Eq("Estado__Uf", uf).SetRelatedSel("Estado").One()
return result, criteria.Error
}
|
package optioner_test
import (
"testing"
"github.com/boundedinfinity/go-optioner"
"github.com/stretchr/testify/assert"
)
func Test_Some_with_string(t *testing.T) {
actual := optioner.Some("s")
assert.Equal(t, actual.Empty(), false)
assert.Equal(t, actual.Defined(), true)
assert.Equal(t, actual.Get(), "s")
assert.Equal(t, actual.OrElse("x"), "s")
}
func Test_Some_with_int(t *testing.T) {
actual := optioner.Some(1)
assert.Equal(t, actual.Empty(), false)
assert.Equal(t, actual.Defined(), true)
assert.Equal(t, actual.Get(), 1)
assert.Equal(t, actual.OrElse(1), 1)
}
func Test_Some_with_boolean(t *testing.T) {
actual := optioner.Some(false)
assert.Equal(t, actual.Empty(), false)
assert.Equal(t, actual.Defined(), true)
assert.Equal(t, actual.Get(), false)
assert.Equal(t, actual.OrElse(true), false)
}
func Test_None_with_string(t *testing.T) {
actual := optioner.None[string]()
assert.Equal(t, actual.Empty(), true)
assert.Equal(t, actual.Defined(), false)
assert.Equal(t, actual.Get(), "")
assert.Equal(t, actual.OrElse("x"), "x")
}
func Test_None_with_int(t *testing.T) {
actual := optioner.None[int]()
assert.Equal(t, actual.Empty(), true)
assert.Equal(t, actual.Defined(), false)
assert.Equal(t, actual.Get(), 0)
assert.Equal(t, actual.OrElse(1), 1)
}
func Test_None_with_bool(t *testing.T) {
actual := optioner.None[bool]()
assert.Equal(t, actual.Empty(), true)
assert.Equal(t, actual.Defined(), false)
assert.Equal(t, actual.Get(), false)
assert.Equal(t, actual.OrElse(true), true)
}
func Test_Option_with_nil_string(t *testing.T) {
actual := optioner.Of[string](nil)
assert.Equal(t, actual.Empty(), true)
assert.Equal(t, actual.Defined(), false)
assert.Equal(t, actual.Get(), "")
assert.Equal(t, actual.OrElse("x"), "x")
}
func Test_Option_with_string(t *testing.T) {
v := "s"
actual := optioner.Of(&v)
assert.Equal(t, actual.Empty(), false)
assert.Equal(t, actual.Defined(), true)
assert.Equal(t, actual.Get(), "s")
assert.Equal(t, actual.OrElse("x"), "s")
}
func Test_Option_with_nil_int(t *testing.T) {
actual := optioner.Of[int](nil)
assert.Equal(t, actual.Empty(), true)
assert.Equal(t, actual.Defined(), false)
assert.Equal(t, actual.Get(), 0)
assert.Equal(t, actual.OrElse(1), 1)
}
func Test_Option_with_int(t *testing.T) {
v := 1
actual := optioner.Of(&v)
assert.Equal(t, actual.Empty(), false)
assert.Equal(t, actual.Defined(), true)
assert.Equal(t, actual.Get(), 1)
assert.Equal(t, actual.OrElse(2), 1)
}
|
package main
import (
"log"
"os"
"text/template"
"time"
"tourOfGolang/ch4/github"
)
// !+template
const templ = `
{{.TotalCount}} issues:
{{range .Items}}--------------------
Number:{{.Number}}
User: {{.User.Login}}
Title: {{.Title | printf "%.64s"}}
Age: {{.CreatedAt | daysAgo}} hours ago
{{end}}
`
// !-template
func daysAgo(t time.Time) int {
return int(time.Since(t).Hours())
}
func main() {
result, err := github.SearchIssues(os.Args[1:])
if err != nil {
log.Fatal(err)
}
report, err := template.New("report").
Funcs(template.FuncMap{"daysAgo": daysAgo}).
Parse(templ)
if err != nil {
log.Fatal(err)
}
err = report.Execute(os.Stdout, result)
if err != nil {
log.Fatal(err)
}
// must()
}
//
func must() {
result, err := github.SearchIssues(os.Args[1:])
if err != nil {
log.Fatal(err)
}
report := template.Must(template.
New("report").
Funcs(template.FuncMap{"daysAgo": daysAgo}).
Parse(templ))
err = report.Execute(os.Stdout, result)
if err != nil {
log.Fatal(err)
}
}
/*
// !+ textoutput
$ go run main.go repo:shadowsocks/shadowsocks/
1422 issues:
--------------------
Number:1460
User: SunR54
Title: SS端口和SSH端口有什么联系吗
Age: 2019-05-29T15:30:35Z
--------------------
Number:1459
User: uebb
Title: 为什么SSR成功连接 没办法打开youtube
Age: 2019-05-28T08:22:30Z
--------------------
Number:1458
User: walkingaway
Title: 免费ss账号,长期更新
Age: 2019-05-27T01:12:07Z
--------------------
Number:1457
User: xiaotana
Title: super Wingy
Age: 2019-05-21T15:08:19Z
--------------------
...
// !- textoutput
*/
|
package factory
import (
"fmt"
"github.com/mitchellh/cli"
"seeder/constants"
)
func Version() (cli.Command, error) {
version := &versionCommandCLI{}
return version, nil
}
type versionCommandCLI struct {
Args []string
}
func (c *versionCommandCLI) Run(args []string) int {
c.Args = args
fmt.Println(constants.APP_NAME + ", version " + constants.APP_VERSION)
return 0
}
func (c *versionCommandCLI) Synopsis() string { return "Usage: seeder version" }
func (c *versionCommandCLI) Help() string {
return `
Usage: seeder version
Gets the current application version of the CLI.
`
}
|
package cli
import (
"fmt"
"index/suffixarray"
"io"
"regexp"
"sort"
"strings"
"github.com/andreyvit/diff"
"github.com/fatih/color"
)
// SearchingCommand interface to describe a command that performs a search operation
type SearchingCommand interface {
GetSearchParams() SearchParameters
}
// SearchParameters struct are parameters common to a command that performs a search operation
type SearchParameters struct {
Search string
Replacement *string
Mode KeyValueMode
IsRegexp bool
}
// Match structure to keep indices of matched and replaced terms
type Match struct {
path string
key string
value string
// sorted slices of indices of match starts and length
keyIndex [][]int
valueIndex [][]int
// in-line diffs of key and value replacements
keyLineDiff string
valueLineDiff string
// final strings after replacement
replacedKey string
replacedValue string
}
// Searcher provides matching and replacement methods while maintaining references to the command
// that provides an interface to search operations. Also maintains reference to a compiled regexp.
type Searcher struct {
cmd SearchingCommand
regexp *regexp.Regexp
}
// NewSearcher creates a new Searcher container for performing search and optionally replace
func NewSearcher(cmd SearchingCommand) (*Searcher, error) {
var re *regexp.Regexp
var err error
params := cmd.GetSearchParams()
if params.IsRegexp {
re, err = regexp.Compile(params.Search)
if err != nil {
return nil, fmt.Errorf("cannot parse regex pattern")
}
}
return &Searcher{cmd: cmd, regexp: re}, nil
}
// IsMode returns true if the specified mode is enabled
func (s *Searcher) IsMode(mode KeyValueMode) bool {
return s.cmd.GetSearchParams().Mode&mode == mode
}
// DoSearch searches with either regexp or substring search methods
func (s *Searcher) DoSearch(path string, k string, v string) (m []*Match) {
// Default to original strings
replacedKey, keyLineDiff := k, k
replacedValue, valueLineDiff := v, v
var keyMatchPairs, valueMatchPairs [][]int
if s.IsMode(ModeKeys) {
keyMatchPairs, replacedKey, keyLineDiff = s.matchData(k, s.cmd.GetSearchParams().IsRegexp)
}
if s.IsMode(ModeValues) {
valueMatchPairs, replacedValue, valueLineDiff = s.matchData(v, s.cmd.GetSearchParams().IsRegexp)
}
if len(keyMatchPairs) > 0 || len(valueMatchPairs) > 0 {
m = []*Match{
{
path: path,
key: k,
value: v,
keyIndex: keyMatchPairs,
valueIndex: valueMatchPairs,
keyLineDiff: keyLineDiff,
valueLineDiff: valueLineDiff,
replacedKey: replacedKey,
replacedValue: replacedValue,
},
}
}
return m
}
func (match *Match) print(out io.Writer, diff bool) {
if diff == true {
fmt.Fprintf(out, "%s> %s = %s\n", match.path, match.keyLineDiff, match.valueLineDiff)
} else {
fmt.Fprintf(out, "%s> %s = %s\n", match.path, match.highlightMatches(match.key, match.keyIndex), match.highlightMatches(match.value, match.valueIndex))
}
}
// highlightMatches will take an array of index and lens and highlight them
func (match *Match) highlightMatches(s string, matches [][]int) (result string) {
cur := 0
if len(matches) > 0 {
for _, pair := range matches {
next := pair[0]
length := pair[1]
end := next + length
result += s[cur:next]
result += color.New(color.FgYellow).SprintFunc()(s[next:end])
cur = end
}
result += s[cur:]
} else {
return s
}
return result
}
// highlightLineDiff will consume (~~del~~)(++add++) markup and colorize in its place
func (s *Searcher) highlightLineDiff(d string) string {
var buf, res []byte
removeMode, addMode := false, false
removeColor := color.New(color.FgWhite).Add(color.BgRed)
addColor := color.New(color.FgWhite).Add(color.BgGreen)
for _, b := range []byte(d) {
buf = append(buf, b)
if string(buf) == "(~~" && !removeMode && !addMode {
buf = make([]byte, 0)
removeMode = true
} else if len(buf) > 3 && string(buf[len(buf)-3:]) == "~~)" && removeMode {
res = append(res, removeColor.SprintFunc()(string(buf[0:len(buf)-3]))...)
buf = make([]byte, 0)
removeMode = false
} else if string(buf) == "(++" && !removeMode && !addMode {
buf = make([]byte, 0)
addMode = true
} else if len(buf) > 3 && string(buf[len(buf)-3:]) == "++)" && addMode {
res = append(res, addColor.SprintFunc()(string(buf[0:len(buf)-3]))...)
buf = make([]byte, 0)
addMode = false
}
}
return string(append(res, buf...))
}
func (s *Searcher) matchData(subject string, isRegexp bool) (matchPairs [][]int, replaced string, inlineDiff string) {
replaced, inlineDiff = subject, subject
matchPairs = make([][]int, 0)
if isRegexp {
matchPairs = s.regexp.FindAllIndex([]byte(subject), -1)
} else {
index := suffixarray.New([]byte(subject))
matches := index.Lookup([]byte(s.cmd.GetSearchParams().Search), -1)
sort.Ints(matches)
substrLength := len(s.cmd.GetSearchParams().Search)
for _, offset := range matches {
matchPairs = append(matchPairs, []int{offset, substrLength})
}
}
if s.cmd.GetSearchParams().Replacement != nil {
if isRegexp {
replaced = s.regexp.ReplaceAllString(subject, *s.cmd.GetSearchParams().Replacement)
} else {
replaced = strings.ReplaceAll(subject, s.cmd.GetSearchParams().Search, *s.cmd.GetSearchParams().Replacement)
}
inlineDiff = s.highlightLineDiff(diff.CharacterDiff(subject, replaced))
}
return matchPairs, replaced, inlineDiff
}
|
package requests
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
"github.com/atomicjolt/canvasapi/models"
)
// ListQuestionsInQuizOrSubmission Returns the paginated list of QuizQuestions in this quiz.
// https://canvas.instructure.com/doc/api/quiz_questions.html
//
// Path Parameters:
// # Path.CourseID (Required) ID
// # Path.QuizID (Required) ID
//
// Query Parameters:
// # Query.QuizSubmissionID (Optional) If specified, the endpoint will return the questions that were presented
// for that submission. This is useful if the quiz has been modified after
// the submission was created and the latest quiz version's set of questions
// does not match the submission's.
// NOTE: you must specify quiz_submission_attempt as well if you specify this
// parameter.
// # Query.QuizSubmissionAttempt (Optional) The attempt of the submission you want the questions for.
//
type ListQuestionsInQuizOrSubmission struct {
Path struct {
CourseID string `json:"course_id" url:"course_id,omitempty"` // (Required)
QuizID string `json:"quiz_id" url:"quiz_id,omitempty"` // (Required)
} `json:"path"`
Query struct {
QuizSubmissionID int64 `json:"quiz_submission_id" url:"quiz_submission_id,omitempty"` // (Optional)
QuizSubmissionAttempt int64 `json:"quiz_submission_attempt" url:"quiz_submission_attempt,omitempty"` // (Optional)
} `json:"query"`
}
func (t *ListQuestionsInQuizOrSubmission) GetMethod() string {
return "GET"
}
func (t *ListQuestionsInQuizOrSubmission) GetURLPath() string {
path := "courses/{course_id}/quizzes/{quiz_id}/questions"
path = strings.ReplaceAll(path, "{course_id}", fmt.Sprintf("%v", t.Path.CourseID))
path = strings.ReplaceAll(path, "{quiz_id}", fmt.Sprintf("%v", t.Path.QuizID))
return path
}
func (t *ListQuestionsInQuizOrSubmission) GetQuery() (string, error) {
v, err := query.Values(t.Query)
if err != nil {
return "", err
}
return v.Encode(), nil
}
func (t *ListQuestionsInQuizOrSubmission) GetBody() (url.Values, error) {
return nil, nil
}
func (t *ListQuestionsInQuizOrSubmission) GetJSON() ([]byte, error) {
return nil, nil
}
func (t *ListQuestionsInQuizOrSubmission) HasErrors() error {
errs := []string{}
if t.Path.CourseID == "" {
errs = append(errs, "'Path.CourseID' is required")
}
if t.Path.QuizID == "" {
errs = append(errs, "'Path.QuizID' is required")
}
if len(errs) > 0 {
return fmt.Errorf(strings.Join(errs, ", "))
}
return nil
}
func (t *ListQuestionsInQuizOrSubmission) Do(c *canvasapi.Canvas, next *url.URL) ([]*models.QuizQuestion, *canvasapi.PagedResource, error) {
var err error
var response *http.Response
if next != nil {
response, err = c.Send(next, t.GetMethod(), nil)
} else {
response, err = c.SendRequest(t)
}
if err != nil {
return nil, nil, err
}
if err != nil {
return nil, nil, err
}
body, err := ioutil.ReadAll(response.Body)
response.Body.Close()
if err != nil {
return nil, nil, err
}
ret := []*models.QuizQuestion{}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, nil, err
}
pagedResource, err := canvasapi.ExtractPagedResource(response.Header)
if err != nil {
return nil, nil, err
}
return ret, pagedResource, nil
}
|
package main
import (
"bytes"
"crypto/tls"
"encoding/binary"
"fmt"
)
func main() {
data := []byte("[这里才是一个完整的数据包]")
l := len(data)
fmt.Println(l)
magicNum := make([]byte, 4)
binary.BigEndian.PutUint32(magicNum, 0x123456)
lenNum := make([]byte, 2)
binary.BigEndian.PutUint16(lenNum, uint16(l))
packetBuf := bytes.NewBuffer(magicNum)
packetBuf.Write(lenNum)
packetBuf.Write(data)
//注意这里要使用证书中包含的主机名称
tlsConfig := &tls.Config{InsecureSkipVerify: true}
conn, err := tls.Dial("tcp", "zyy.centos:443", tlsConfig)
if err != nil {
fmt.Printf("connect failed, err : %v\n", err.Error())
return
}
for i := 0; i < 1000; i++ {
_, err = conn.Write(packetBuf.Bytes())
if err != nil {
fmt.Printf("write failed , err : %v\n", err)
break
}
}
}
|
package stringUtil
import (
"testing"
)
func TestIsNum(t *testing.T) {
t.Log(IsNum("sfd"))
t.Log(IsNum("123"))
t.Log(IsNum("123.3"))
}
func TestSplit(t *testing.T) {
for _,s:=range Split("sfd,,ff,ffs",","){
t.Log(s)
}
}
|
package search
import "math"
func BinarySortExist(arr []int, v int) bool {
if arr == nil || len(arr) == 0 {
return false
}
if len(arr) == 1 {
if arr[0] == v {
return true
} else {
return false
}
}
L := 0
R := len(arr) - 1
for L < R {
mid := L + (R-L)/2
if arr[mid] == v {
return true
} else if arr[mid] > v {
R = mid - 1
} else {
L = mid + 1
}
}
return arr[L] == v
}
// 在arr上,找满足>=value的最左位置
func BinarySortSearchLeft(arr []int, value int) int {
idx := -1
if arr == nil || len(arr) == 0 {
return idx
}
L := 0
R := len(arr) - 1
for L <= R {
mid := L + (R-L)/2
if arr[mid] >= value {
idx = mid
R = mid - 1
} else {
L = mid + 1
}
}
return idx
}
// 在arr上,找满足<=value的最右位置
func BinarySortSearchRight(arr []int, value int) int {
idx := -1
if arr == nil || len(arr) == 0 {
return idx
}
L := 0
R := len(arr) - 1
for L <= R {
mid := L + (R-L)/2
if arr[mid] <= value {
idx = mid
L = mid + 1
} else {
R = mid - 1
}
}
return idx
}
func MaxNumSearch(arr []int) int {
if arr == nil || len(arr) == 0 {
return math.MinInt32
}
m := process(arr, 0, len(arr)-1)
return int(m)
}
func process(arr []int, L, R int) float64 {
if L == R {
return float64(arr[L])
}
mid := L + ((R - L) >> 1)
left := process(arr, L, mid)
right := process(arr, mid+1, R)
return math.Max(left, right)
}
|
package main
/*
Given an array A of 0s and 1s, divide the array into 3 non-empty parts such that all of these parts represent the same binary value.
If it is possible, return any [i, j] with i+1 < j, such that:
A[0], A[1], ..., A[i] is the first part;
A[i+1], A[i+2], ..., A[j-1] is the second part, and
A[j], A[j+1], ..., A[A.length - 1] is the third part.
All three parts have equal binary value.
If it is not possible, return [-1, -1].
Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.
Example 1:
Input: [1,0,1,0,1]
Output: [0,3]
Example 2:
Input: [1,1,0,1,1]
Output: [-1,-1]
Note:
3 <= A.length <= 30000
A[i] == 0 or A[i] == 1
*/
import (
"fmt"
)
func main() {
/*
fmt.Println(threeEqualParts([]int{0,0,0,1,0,1,0,1,0,1,1,0,1}))
fmt.Println(threeEqualParts([]int{1,0,1,0,1}))//0,3
fmt.Println(threeEqualParts([]int{1,1,0,1,1}))//-1,-1
fmt.Println(threeEqualParts([]int{0,0,0,0,0}))//0,4
fmt.Println(threeEqualParts([]int{1,1,0,0,1})) //0,2
*/
fmt.Println(threeEqualParts([]int{0,1,1,0,0,1,1,1,1,1})) //-1,-1
}
/*
边界情况较多. 需要思路清晰,前导0是无效的,后面0是ok的.
解法:
1.先确定第三个区间.因为后缀0有效,找到第三个区间第一个是1的,代码中的third
2.找第一个区间.逻辑是,去掉前导0后,跟third相同即可.
3.从1,2获得了一个有效第二区间,从nozero+len(third) 到 len(A)-len(third)
这部分也去掉前导0,看剩余的是否有相同的前缀,并且不同的部分,全都是0
*/
func threeEqualParts(A []int) []int {
nozero := 0
for i:=0;i<len(A)&&A[i]==0;i++ {
nozero += 1
}
if nozero == len(A) {return []int{0,len(A)-1}} // no 1
cnt1 := 0
for i:=0;i<len(A);i++ {
if A[i]==1{cnt1+=1}
}
//if cnt1%3!=0 {return []int{-1,-1}}
for i:=len(A)-1;i>(len(A)-1-len(A)/3);i-- {
if A[i] == 0 {continue} // only consider startwith 1
third := A[i:]
if !hasSubfixOnlyZero(nozero,A,third) {continue}
//fmt.Println(third,A[(nozero+len(third)):i])
idx := containOnlyZero(nozero+len(third),i,A,third)
if idx >= 0 {
return []int{nozero+len(third)-1,idx}
}
}
return []int{-1,-1}
}
func containOnlyZero(start,end int,A []int,third []int) int {
// 去掉A的前导0,看A=third + 0
i := start
for i=start;i<len(A)&&A[i]==0;i++ {
start += 1
}
for i=start;i<start+len(third);i++ {
if A[i]!=third[i-start] {
return -1
}
}
idx := i
for ;i<end;i++ {
if A[i]==1{return -1}
}
return idx
}
func hasSubfixOnlyZero(nozero int, A []int, third []int) bool {
for i:=nozero;i<len(third)+nozero;i++ {
if A[i]!=third[i-nozero] {
return false
}
}
return true
}
////////////////
func threeEqualParts1(A []int) []int {
pre0 := 0
for i:=0;i<len(A)&&A[i]==0;i++ {
pre0 += 1
}
A = A[pre0:]
for i:=1;i<=(pre0+len(A))/3&&i<len(A);i++ {
idx,same := hasSubfix(A,i)
if idx < 0 {
continue
}
//fmt.Println(A[:i],same,A[i:idx])
leftz := hasprefixOnlyZero(same,A[i:idx])
if leftz >= 0 {
return []int{pre0+i-1,pre0+idx-leftz}
}
}
return []int{-1,-1}
}
func hasprefixOnlyZero(A []int, B []int) int {
if len(A) > len(B) {return -1}
a,b := 0,0
for i:=0;i<len(B)&&B[i]==0;i++ {b += 1}
for ;a<len(A)&&b<len(B)&&A[a]==B[b];a,b=a+1,b+1 {}
left:=len(B)-b
for ;b<len(B);b++ {
if B[b]==1 {return -1}
}
return left
}
func hasSubfix(A []int, ii int) (int,[]int) {
for i:=0;i<ii;i++ {
if A[i]!=A[len(A)-ii+i] {
return -1,nil
}
}
return len(A)-ii,A[:ii]
} |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package wiredhostapd contains utilities for establishing a hostapd server for use with 'driver=wired'
// (i.e., Ethernet or similar).
package wiredhostapd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.