code
stringlengths 67
15.9k
| labels
listlengths 1
4
|
---|---|
package _834_sum_of_distances_in_tree
type Node struct {
val int
children []*Node
parent *Node
sum int
numChildren int
}
func (this *Node) addChild(child *Node) {
this.children = append(this.children, child)
}
func (this *Node) removeChild(child *Node) {
var i = -1
for j, node := range this.children {
if child == node {
i = j
break
}
}
if i < 0 {
return
}
this.children[i] = this.children[len(this.children)-1]
this.children = this.children[:len(this.children)-1]
}
func (this *Node) setParent(parent *Node) {
this.parent = parent
}
func setParent(root *Node, N int) {
nodes := []*Node{root}
stack := make([]*Node, 0, N)
depth := 1
for {
stack = append(stack, nodes...)
var next []*Node
for _, node := range nodes {
for _, child := range node.children {
child.removeChild(node)
child.setParent(node)
next = append(next, child)
}
}
if next == nil {
break
}
nodes = next
root.sum += len(nodes) * depth
depth++
}
for i := 0; i < N; i++ {
node := stack[N-i-1]
if len(node.children) == 0 {
node.numChildren = 0
} else {
for _, child := range node.children {
node.numChildren += child.numChildren
}
node.numChildren += len(node.children)
}
}
}
func calcSum(root *Node, N int) {
nodes := root.children
for {
var next []*Node
for _, node := range nodes {
node.sum += node.parent.sum + (N - node.numChildren - 2) - node.numChildren
next = append(next, node.children...)
}
if next == nil {
break
}
nodes = next
}
}
func sumOfDistancesInTree(N int, edges [][]int) []int {
if N <= 1 {
return []int{0}
}
nodes := make([]*Node, N)
for i := range nodes {
nodes[i] = &Node{
val: i,
}
}
for _, e := range edges {
a, b := nodes[e[0]], nodes[e[1]]
a.addChild(b)
b.addChild(a)
}
setParent(nodes[0], N)
calcSum(nodes[0], N)
ret := make([]int, N)
for i := 0; i < N; i++ {
ret[i] = nodes[i].sum
}
return ret
}
|
[
2
] |
package main
import (
"encoding/binary"
"flag"
"fmt"
"io"
"net"
"os"
"runtime/debug"
"sync"
)
var serverAddr string
var agentMode string
const xor byte = 0x64
/*Tunnel 代理隧道*/
type Tunnel struct {
clientConn net.Conn
serverConn net.Conn
connWait sync.WaitGroup
}
func newTunnel(c net.Conn) *Tunnel {
t := new(Tunnel)
t.clientConn = c
t.connWait.Add(2)
return t
}
func main() {
var listenAddr string
flag.StringVar(&serverAddr, "s", "192.168.222.131:1080", "server agent addr default (192.168.222.131:1080)")
flag.StringVar(&listenAddr, "l", "0.0.0.0:1080", "listen addr default (0.0.0.0:1080)")
flag.StringVar(&agentMode, "m", "client", "agent mode default (client)")
flag.Parse()
var listen net.Listener
var err error
listen, err = net.Listen("tcp", listenAddr)
if err != nil {
fmt.Println("error listening:", err)
os.Exit(1)
}
defer listen.Close()
fmt.Printf("run mode %s listening on %s\n", agentMode, listenAddr)
for {
conn, err := listen.Accept()
if err != nil {
fmt.Println("error accepting: ", err)
os.Exit(1)
}
t := newTunnel(conn)
if agentMode == "client" {
go processClientShake(t)
} else {
go processServerShake(t)
}
}
}
func processClientShake(t *Tunnel) {
defer func() {
t.clientConn.Close()
if t.serverConn != nil {
t.serverConn.Close()
}
if err := recover(); err != nil {
fmt.Printf("panic: %v\n\n%s", err, debug.Stack())
}
}()
var err error
var recvBuf [64]byte
// 接收第一次握手信息
_, err = io.ReadFull(t.clientConn, recvBuf[0:3])
if err != nil {
fmt.Println("Read error ", err.Error())
return
}
if recvBuf[0] != 0x05 || recvBuf[1] != 0x01 || recvBuf[2] != 0x00 {
fmt.Println("Invalid socks5 format")
return
}
// 发送第一次握手应答
var sendBuf [64]byte
sendBuf[0] = 0x05
sendBuf[1] = 0x00
_, err = t.clientConn.Write(sendBuf[0:2])
if err != nil {
fmt.Println("Write error ", err.Error())
return
}
// 接收第二次握手信息
_, err = io.ReadFull(t.clientConn, recvBuf[0:4])
if err != nil {
fmt.Println("Read error ", err.Error())
return
}
var sendLen int
sendBuf[0] = 0x05
sendBuf[1] = 0x00
sendBuf[2] = 0x00
sendBuf[3] = recvBuf[3]
var textAddr string
ATYPE := recvBuf[3]
if ATYPE == 0x01 {
_, err := io.ReadFull(t.clientConn, recvBuf[4:10])
if err != nil {
fmt.Println("Read error ", err.Error())
return
}
port := binary.BigEndian.Uint16(recvBuf[8:10])
textAddr = fmt.Sprintf("%d.%d.%d.%d:%d", recvBuf[4], recvBuf[5], recvBuf[6], recvBuf[7], port)
copy(sendBuf[4:], recvBuf[4:10])
sendLen = 10
} else if ATYPE == 0x03 {
_, err = io.ReadFull(t.clientConn, recvBuf[4:5])
if err != nil {
fmt.Println("Read error ", err.Error())
return
}
domainLen := recvBuf[4]
_, err = io.ReadFull(t.clientConn, recvBuf[5:5+domainLen+2])
if err != nil {
fmt.Println("Read error ", err.Error())
return
}
port := binary.BigEndian.Uint16(recvBuf[5+domainLen : 5+domainLen+2])
textAddr = fmt.Sprintf("%s:%d", string(recvBuf[5:5+recvBuf[4]]), port)
copy(sendBuf[4:], recvBuf[4:4+domainLen+3])
sendLen = int(domainLen + 7)
}
// 发送第二次握手应答
_, err = t.clientConn.Write(sendBuf[0:sendLen])
if err != nil {
fmt.Println("Write error ", err.Error())
return
}
fmt.Printf("shake sucessful %v %s\n", t.clientConn.RemoteAddr(), textAddr)
serverConn, err := net.Dial("tcp", serverAddr)
if err != nil {
fmt.Println("Dial error ", err.Error())
return
}
t.serverConn = serverConn
// 发消息给服务器
sendBuf[0] = byte(len(textAddr))
for i := 0; i < len(textAddr); i++ {
sendBuf[i+1] = textAddr[i] ^ xor
}
_, err = t.serverConn.Write(sendBuf[:len(textAddr)+1])
if err != nil {
fmt.Println("Write error ", err.Error())
return
}
go processRecv(t)
go processSend(t)
t.connWait.Wait()
}
func processServerShake(t *Tunnel) {
defer func() {
t.clientConn.Close()
if t.serverConn != nil {
t.serverConn.Close()
}
if err := recover(); err != nil {
fmt.Printf("panic: %v\n\n%s", err, debug.Stack())
}
}()
var err error
var recvBuf [64]byte
// 接收第一次握手信息
_, err = io.ReadFull(t.clientConn, recvBuf[0:1])
if err != nil {
fmt.Println("Read error ", err.Error())
return
}
addrLen := int(recvBuf[0])
_, err = io.ReadFull(t.clientConn, recvBuf[1:1+addrLen])
if err != nil {
fmt.Println("Read error ", err.Error())
return
}
for i := 0; i < addrLen; i++ {
recvBuf[i+1] = recvBuf[i+1] ^ xor
}
targetAddr := string(recvBuf[1 : 1+addrLen])
fmt.Printf("shake sucessful %v %s\n", t.clientConn.RemoteAddr(), targetAddr)
targetConn, err := net.Dial("tcp", targetAddr)
if err != nil {
fmt.Println("Dial error ", err.Error())
return
}
t.serverConn = targetConn
go processRecv(t)
go processSend(t)
t.connWait.Wait()
}
func processSend(t *Tunnel) {
var recvBuf [1024]byte
for {
n, err := t.clientConn.Read(recvBuf[:])
if err != nil {
fmt.Println("Read error ", err.Error())
break
}
// 加密
for i := 0; i < n; i++ {
recvBuf[i] = recvBuf[i] ^ xor
}
_, err = t.serverConn.Write(recvBuf[:n])
if err != nil {
fmt.Println("Write error ", err.Error())
break
}
}
t.connWait.Done()
}
func processRecv(t *Tunnel) {
var recvBuf [1024]byte
for {
n, err := t.serverConn.Read(recvBuf[:])
if err != nil {
fmt.Println("Read error ", err.Error())
break
}
// 解密
for i := 0; i < n; i++ {
recvBuf[i] = recvBuf[i] ^ xor
}
_, err = t.clientConn.Write(recvBuf[:n])
if err != nil {
fmt.Println("Write error ", err.Error())
break
}
}
t.connWait.Done()
}
|
[
0
] |
package main
import "fmt"
func main() {
trie := Constructor()
trie.Insert("apple")
trie.Insert("pea")
fmt.Println(trie.Search("apple"))
fmt.Println(trie.Search("app"))
fmt.Println(trie.StartsWith("app"))
fmt.Println(trie.StartsWith("apb"))
}
type Trie struct {
next [26]*Trie
isEnd bool
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) Insert(word string) {
cur := this
for _, v := range word {
v = v-'a'
if cur.next[v] == nil {
cur.next[v] = &Trie{}
}
cur = cur.next[v]
}
cur.isEnd = true
}
func (this *Trie) Search(word string) bool {
cur := this
for _, v := range word {
if cur = cur.next[v-'a']; cur == nil {
return false
}
}
return cur.isEnd
}
func (this *Trie) StartsWith(prefix string) bool {
cur := this
for _, v := range prefix {
if cur = cur.next[v-'a']; cur == nil {
return false
}
}
return true
}
|
[
0
] |
package zmath
import (
"fmt"
"math"
)
// Set represents a slice of type float64
type Set []float64
// ToLinear copies by value a [][]float64 to []float64. Any Changes made to the returned Set can then
// be committed to the [][]float64 with the To2D function.
func ToLinear(data Map) Set {
linearData := make(Set, 0, int(data.Area()))
for i := range data {
linearData = append(linearData, data[i]...)
}
return linearData
}
// To2D copies by value a []float64 into a pre-existing [][]float64
func (s Set) To2D(to [][]float64) [][]float64 {
idx := 0
for i := 0; i < len(to); i++ {
for j := 0; j < len(to[i]); j++ {
to[i][j] = s[idx]
idx++
}
}
return to
}
// IndicesBetween returns the number of indices between the two values provided. Assumes the Set is pre-sorted.
func (s Set) IndicesBetween(min, max float64) int {
idxMin := s.IndexOfClosest(min)
idxMax := s.IndexOfClosest(max)
return idxMax - idxMin
}
// IndexOf returns the lowest index of the desired item in the Set, or -1 if not found
func (s Set) IndexOf(value float64) int {
for i, item := range s {
if item == value {
return i
}
}
return -1
}
// IndexOfClosest returns the index of the item closest to the desired value. Assumes the Set is pre-sorted.
func (s Set) IndexOfClosest(value float64) int {
idx := s.IndexOf(value)
if idx != -1 { // if data contains the exact value (yay)
return idx
}
if value < s.GetMin() {
return 0
} else if value > s.GetMax() {
return len(s) - 1
}
for i, item := range s {
if item > value {
return i
}
}
return -1
}
// GetMin returns the min of a Set
func (s Set) GetMin() float64 {
min := s[0]
for _, item := range s {
if min > item {
min = item
}
}
return min
}
// GetMax returns the max of a Set
func (s Set) GetMax() float64 {
max := s[0]
for _, item := range s {
if max < item {
max = item
}
}
return max
}
// GetRange returns the range of a Set. This is computationally faster than GetMaxOf() - GetMinOf() if you
// only need the range for a given task.
func (s Set) GetRange() float64 {
min, max := s[0], s[0]
for _, item := range s {
if min > item {
min = item
}
if max < item {
max = item
}
}
return max - min
}
// GetMedian returns the median of a Set
func (s Set) GetMedian() float64 {
dataCopy := make(Set, 0, len(s))
copy(dataCopy, s)
dataCopy.Sort()
var median float64
idx := len(s) / 2
if len(s)%2 == 1 { // if len(data) is odd
median = s[idx]
} else {
median = (s[idx] + s[idx-1]) / 2.0
}
return median
}
// GetMean returns the mean of a Set
func (s Set) GetMean() float64 {
var sum float64
for _, item := range s {
sum += item
}
return sum / float64(len(s))
}
// GetVariance returns the variance of a Set
func (s Set) GetVariance() float64 {
var squareSum float64
mean := s.GetMean()
for _, item := range s {
squareSum += math.Pow(mean-item, 2)
}
return squareSum / float64(len(s))
}
// GetStd returns the standard deviation of a Set
func (s Set) GetStd() float64 {
return math.Sqrt(s.GetVariance())
}
// Zero zeroes a Set
func (s Set) Zero() Set {
for i := 0; i < len(s); i++ {
s[i] = 0
}
return s
}
// Copy deepcopies the called Set into a new Set and returns the new one
func (s Set) Copy() Set {
newSet := make(Set, len(s))
copy(newSet, s)
return newSet
}
// Interpolate linearly adjusts the data to a new min and max
func (s Set) Interpolate(newMin, newMax float64) Set {
oldMin := s.GetMin()
oldMax := s.GetMax()
oldRange := oldMax - oldMin
newRange := newMax - newMin
for i := range s {
s[i] = ((s[i]-oldMin)/oldRange)*newRange + newMin
}
return s
}
// MakeUniform makes the called Set follow a uniform distribution
func (s Set) MakeUniform() Set {
var (
length = float64(len(s)) - 1
sorted = s.Copy().Sort()
retSet = make(Set, len(s))
)
for i, val := range s {
retSet[i] = float64(sorted.IndexOf(val)) / length
}
copy(s, retSet)
return s
}
// Sort sorts a Set with a quicksort implementation
func (s Set) Sort() Set {
if len(s) < 2 {
return s
}
left, right := 0, len(s)-1
pivotIndex := len(s) / 2
s[pivotIndex], s[right] = s[right], s[pivotIndex]
for i := range s {
if s[i] < s[right] {
s[i], s[left] = s[left], s[i]
left++
}
}
s[left], s[right] = s[right], s[left]
// Recursively call sort
Set(s[:left]).Sort()
Set(s[left+1:]).Sort()
return s
}
// Stats contains basic statistical analysis about a Set
type Stats struct {
Size, _ int
Min float64
Max float64
Range float64
Median float64
Mean float64
Variance float64
Std float64
}
// GetAnalysis returns an Analysis struct according to the contents of the Set
func (s Set) GetAnalysis() *Stats {
min, max := s.GetMin(), s.GetMax()
variance := s.GetVariance()
return &Stats{
Size: len(s),
Min: min,
Max: max,
Range: max - min,
Median: s.GetMedian(),
Mean: s.GetMean(),
Variance: variance,
Std: math.Sqrt(variance),
}
}
// PrintAnalysis outputs the analysis to the terminal
func PrintAnalysis(a *Stats) {
fmt.Println("N: ", a.Size)
fmt.Println("Min: ", a.Min)
fmt.Println("Max: ", a.Max)
fmt.Println("Range: ", a.Range)
fmt.Println("Median: ", a.Median)
fmt.Println("Mean: ", a.Mean)
fmt.Println("Variance: ", a.Variance)
fmt.Println("Std: ", a.Std)
}
// PrintBasicHistogram prints out what percentages of the dataset are within certain histogram ranges.
// Use on a noise map (simplex, perlin, etc.) for some interesting insights!
func (s Set) PrintBasicHistogram() {
sorted := make(Set, len(s))
copy(sorted, s)
sorted.Sort()
std := s.GetStd()
mean := s.GetMean()
for s := -3.; s < 3; s++ {
min, max := mean+s*std, mean+(s+1)*std
gap := 100.0 * (float64(sorted.IndicesBetween(min, max)) / float64(len(sorted)))
fmt.Printf("Between %v and %v stds: %v%% of the data\n", s, s+1, gap)
}
}
|
[
1
] |
package main
import (
"bytes"
"os"
"strings"
"testing"
"time"
)
type fakeRandomTimeGenerator struct {
MinLaptime float64
MaxLaptime float64
}
func (f fakeRandomTimeGenerator) CreateRandomTime() float64 {
return 1
}
func TestStartSession(t *testing.T) {
t.Run("Session starts and finishes on time", func(t *testing.T) {
sessionChannel := make(chan struct{})
rs := RaceSession{
SessionChannel: sessionChannel,
SessionTime: 5,
Printer: os.Stdout,
}
go rs.startSession()
select {
case <-rs.SessionChannel:
return
case <-time.After(time.Second * time.Duration(rs.SessionTime+1)):
t.Error("Session channel should have stopped")
}
})
t.Run("Session starts and prints the correct data to terminal", func(t *testing.T) {
sessionChannel := make(chan struct{})
buffer := &bytes.Buffer{}
rs := RaceSession{
SessionChannel: sessionChannel,
SessionTime: 1,
Printer: buffer,
}
go rs.startSession()
<-sessionChannel
output := buffer.String()
want := `GO GO GO!
🏁 🏁 🏁 🏁 🏁
`
if output != want {
t.Errorf("got '%s' want '%s'", output, want)
}
})
}
func TestRace(t *testing.T) {
sessionChannel := make(chan struct{})
rtg := fakeRandomTimeGenerator{
MinLaptime: 1,
MaxLaptime: 2,
}
buffer := &bytes.Buffer{}
rs := RaceSession{
SessionChannel: sessionChannel,
SessionTime: 5,
Printer: buffer,
RandomTimeGenerator: rtg,
}
racer := Racer{
KartNumber: 1,
}
go rs.startSession()
finalRacer := rs.race(&racer)
lines := strings.Split(buffer.String(), "\n")
printedLaptimes := 0
for _, i := range lines {
if strings.HasPrefix(i, "Kart: 1") {
printedLaptimes = printedLaptimes + 1
}
}
if len(finalRacer.Times) != printedLaptimes {
t.Errorf("racer completed '%v' laps but only '%v' laps were printed", len(finalRacer.Times), printedLaptimes)
}
if lines[0] != "GO GO GO!" {
t.Error("first line is incorrect")
}
if lines[len(lines)-3] != "🏁 🏁 🏁 🏁 🏁" {
t.Error("second to last line printed should be 🏁 🏁 🏁 🏁 🏁")
}
}
|
[
0
] |
// Package vet is an API for gomodvet (a simple prototype of a potential future 'go mod vet' or similar).
//
// See the README at https://github.com/thepudds/gomodvet for more details.
package vet
import (
"fmt"
"os/exec"
"regexp"
"sort"
"strings"
"github.com/rogpeppe/go-internal/semver"
"github.com/thepudds/gomodvet/buildlist"
"github.com/thepudds/gomodvet/modfile"
"github.com/thepudds/gomodvet/modgraph"
)
// GoModNeedsUpdate reports if the current 'go.mod' would be updated by
// a 'go build', 'go list', or similar command.
// Rule: gomodvet-001.
func GoModNeedsUpdate(verbose bool) (bool, error) {
// TODO: better way to check this that is more specific to readonly.
// Probably better to check 'go' output for the specific error?
// Note that 'go list -mod=readonly -m all' does not complain if an update is needed,
// but 'go list -mod=readonly' does complain.
out, err := exec.Command("go", "list", "-mod=readonly", "./...").CombinedOutput()
if err != nil {
if verbose {
fmt.Println("gomodvet: error reported when running 'go list -mod=readonly':", string(out))
}
out2, err2 := exec.Command("go", "list", "./...").CombinedOutput()
if err2 != nil {
// error with -mod=readonly, but also without -mod=readonly, so this is likely an error
// unrelated to whether or not an update is needed.
fmt.Println("gomodvet: error reported when running 'go list':", string(out2))
return false, err2
}
// // error with -mod=readonly, but not without -mod=readonly, so likely due to the -mod=readonly
fmt.Println("gomodvet-001: the current module's 'go.mod' file would be updated by a 'go build' or 'go list. Please update prior to using gomodvet.")
return true, nil
}
return false, nil
}
// Upgrades reports if the are any upgrades for any direct and indirect dependencies.
// It returns true if upgrades are needed.
// Rule: gomodvet-002
func Upgrades(verbose bool) (bool, error) {
mods, err := buildlist.ResolveUpgrades()
if err != nil {
return false, err
}
flagged := false
for _, mod := range mods {
if verbose {
fmt.Printf("gomodvet: upgrades: module %s: %+v\n", mod.Path, mod)
}
if mod.Update != nil {
fmt.Println("gomodvet-002: dependencies have available updates: ", mod.Path, mod.Update.Version)
flagged = true
}
}
return flagged, nil
}
// MultipleMajor reports if the current module has any dependencies with multiple major versions.
// For example, if the current module is 'foo', it reports if there is a 'bar' and 'bar/v3' as dependencies of 'foo'.
// It returns true if multiple major versions are found.
// Note that this looks for Semantic Import Version '/vN' versions, not gopkg.in versions. (Probably reasonable to not flag gopkg.in?)
// Could use SplitPathVersion from https://github.com/rogpeppe/go-internal/blob/master/module/module.go#L274
// Rule: gomodvet-003
func MultipleMajor(verbose bool) (bool, error) {
// TODO: non-regexp parsing of '/vN'?
re := regexp.MustCompile("/v[0-9]+$")
// track our paths in { strippedPath: fullPath, ... } map.
paths := make(map[string]string)
mods, err := buildlist.Resolve()
if err != nil {
fmt.Println("gomodvet:", err)
return false, err
}
flagged := false
for _, mod := range mods {
if verbose {
fmt.Printf("gomodvet: multiplemajors: module %s: %+v\n", mod.Path, mod)
}
strippedPath := re.ReplaceAllString(mod.Path, "")
if priorPath, ok := paths[strippedPath]; ok {
fmt.Println("gomodvet-003: a module has multiple major versions in this build: ", priorPath, mod.Path)
flagged = true
}
paths[strippedPath] = mod.Path
}
return flagged, nil
}
// ConflictingRequires reports if the current module or any dependencies have:
// -- different v0 versions of a shared dependency.
// -- a v0 version of a shared dependency plus a v1 version.
// -- a vN+incompatible (N > 2) version of a shared dependency plus a v0, v1, or other vN+incompatible.
// It returns true if so.
// Rule: gomodvet-004
func ConflictingRequires(verbose bool) (bool, error) {
// obtain the set of requires by all modules in our build (via 'go mod graph').
// this takes into account replace directives.
requires, err := modgraph.Requirements()
if err != nil {
return false, err
}
// track our paths and versions in { path: {version, version, ...}, ... } map.
paths := make(map[string][]string)
for _, require := range requires {
f := strings.Split(require, "@")
if len(f) != 2 {
return false, fmt.Errorf("unexpected requirement: %s", require)
}
path, version := f[0], f[1]
if !semver.IsValid(version) {
return false, fmt.Errorf("invalid semver version: %s", require)
}
// Probably not needed, but might as well use the canonical semver version. That strips "+incompatible",
// which we need to preserve. Thus, we check here for "+incompatible" and add it back if needed.
if semver.Build(version) == "+incompatible" {
paths[path] = append(paths[path], semver.Canonical(version)+"+incompatible")
} else {
paths[path] = append(paths[path], semver.Canonical(version))
}
}
// for each path, loop over its versions (in semantic order) and build up a list
// of potential conflicts.
flagged := false
for path, versions := range paths {
sort.Slice(versions, func(i, j int) bool { return -1 == semver.Compare(versions[i], versions[j]) })
if verbose {
fmt.Printf("gomodvet: conflictingrequires: module %q has require versions: %v\n", path, versions)
}
priorVersion := ""
var potentialIncompats []string
for _, version := range versions {
if version == priorVersion {
continue
}
if isBeforeV1(version) {
// all pre-v1 versions are potentially incompatible
potentialIncompats = append(potentialIncompats, version)
} else if isV1(version) && !isV1(priorVersion) {
// the first v1 version seen is potentially incompatible with any v0, v2+incompatible, v3+incompatible, etc.
potentialIncompats = append(potentialIncompats, version)
} else if isV2OrHigherIncompat(version) && semver.Major(version) != semver.Major(priorVersion) {
// the first major version v2+incompatible, v3+incompatible, etc is potentially incompatible.
// (If two v2+incompatible versions are seen, in theory they should be compatible with each other).
potentialIncompats = append(potentialIncompats, version)
}
priorVersion = version
}
if len(potentialIncompats) > 1 {
// mutiple potential incompatible versions, which means they can be incompatible with each other.
fmt.Printf("gomodvet-004: module %q was required with potentially incompatible versions: %s\n",
path, strings.Join(potentialIncompats, ", "))
flagged = true
}
}
return flagged, nil
}
// ExcludedVersion reports if the current module or any dependencies are using a version excluded by a dependency.
// It returns true if so.
// Currently requires main module's go.mod being in a consistent state (e.g., after a 'go list' or 'go build'), such that
// the main module does not have a go.mod file using something it excludes.
// gomodvet enforces this requirement.
//
// ExcludedVersion also assumes versions in any 'go.mod' file in the build is using canonical version strings.
// The 'go' tool also enforces this when run (with some rare possible exceptions like multiple valid tags for a single commit),
// but a person could check in any given 'go.mod' file prior to letting the 'go' tool use canonical version strings. If
// that were to happen, the current ExcludedVersion could have a false negative (that is, potentially miss flagging something).
// Rule: gomodvet-005
func ExcludedVersion(verbose bool) (bool, error) {
report := func(err error) error { return fmt.Errorf("excludedversion: %v", err) }
// track our versions in { path: version } map.
versions := make(map[string]string)
mods, err := buildlist.Resolve()
if err != nil {
return false, report(err)
}
// build up our reference map
for _, mod := range mods {
if verbose {
fmt.Printf("gomodvet: excludedversion: module %s: %+v\n", mod.Path, mod)
}
versions[mod.Path] = mod.Version
}
// do our check by parsing each 'go.mod' file being used,
// and check if we are using a path/version combination excluded
// by one of a go.mod file in our dependecies
flagged := false
for _, mod := range mods {
if mod.Main {
// here we assume the main module's 'go.mod' is in a consistent state,
// and not using something excluded in its own 'go.mod' file. The 'go' tool
// enforces this on a 'go build', 'go mod tidy', etc.
continue
}
file, err := modfile.Parse(mod.GoMod)
if err != nil {
return false, report(err)
}
for _, exclude := range file.Exclude {
usingVersion, ok := versions[exclude.Path]
if !ok {
continue
}
if usingVersion == exclude.Version {
fmt.Printf("gomodvet-005: a module is using a version excluded by another module. excluded version: %s %s\n",
exclude.Path, exclude.Version)
flagged = true
}
}
}
return flagged, nil
}
// Prerelease reports if the current module or any dependencies are using a prerelease semver version
// (exclusive of pseudo-versions, which are also prerelease versions according to semver spec but are reported separately).
// It returns true if so.
// Rule: gomodvet-006
func Prerelease(verbose bool) (bool, error) {
mods, err := buildlist.Resolve()
if err != nil {
return false, fmt.Errorf("prerelease: %v", err)
}
flagged := false
for _, mod := range mods {
if verbose {
fmt.Printf("gomodvet: prerelease: module %s: %+v\n", mod.Path, mod)
}
if isPrerelease(mod.Version) {
fmt.Printf("gomodvet-006: a module is using a prerelease version: %s %s\n",
mod.Path, mod.Version)
flagged = true
}
}
return flagged, nil
}
// PseudoVersion reports if the current module or any dependencies are using a prerelease semver version
// (exclusive of pseudo-versions, which are also prerelease versions according to semver spec but are reported separately).
// It returns true if so.
// Rule: gomodvet-007
func PseudoVersion(verbose bool) (bool, error) {
mods, err := buildlist.Resolve()
if err != nil {
return false, fmt.Errorf("pseudoversion: %v", err)
}
flagged := false
for _, mod := range mods {
if verbose {
fmt.Printf("gomodvet: pseudoversion: module %s: %+v\n", mod.Path, mod)
}
if isPseudoVersion(mod.Version) {
fmt.Printf("gomodvet-007: a module is using a pseudoversion version: %s %s\n",
mod.Path, mod.Version)
flagged = true
}
}
return flagged, nil
}
// Replace reports if the current go.mod has 'replace' directives.
// It returns true if so.
// The parses the 'go.mod' for the main module, and hence can report
// true if the main module's 'go.mod' has ineffective replace directives.
// Part of the use case is some people never want to check in a replace directive,
// and this can be used to check that.
// Rule: gomodvet-008
func Replace(verbose bool) (bool, error) {
mods, err := buildlist.Resolve()
if err != nil {
return false, fmt.Errorf("replace: %v", err)
}
flagged := false
for _, mod := range mods {
if !mod.Main {
continue
}
if verbose {
fmt.Printf("gomodvet: replacement: module %s: %+v\n", mod.Path, mod)
}
file, err := modfile.Parse(mod.GoMod)
if err != nil {
return false, fmt.Errorf("replace: %v", err)
}
if len(file.Replace) > 0 {
fmt.Printf("gomodvet-008: the main module has 'replace' directives\n")
flagged = true
}
}
return flagged, nil
}
func isPseudoVersion(version string) bool {
// regexp from cmd/go/internal/modfetch/pseudo.go
re := regexp.MustCompile(`^v[0-9]+\.(0\.0-|\d+\.\d+-([^+]*\.)?0\.)\d{14}-[A-Za-z0-9]+(\+incompatible)?$`)
return semver.IsValid(version) && re.MatchString(version)
}
func isPrerelease(version string) bool {
return semver.IsValid(version) && !isPseudoVersion(version) && semver.Prerelease(version) != ""
}
// isBeforeV1 reports if a version is prio to v1.0.0, according to semver.
// v0.9.0 and v1.0.0-alpha are examples of versions before v1.0.0.
func isBeforeV1(version string) bool {
return semver.IsValid(version) && semver.Compare(version, "v1.0.0") < 0
}
// isV1 reports if the major version is 'v1' (e.g., 'v1.2.3')
func isV1(version string) bool {
if !semver.IsValid(version) || isBeforeV1(version) {
return false
}
return semver.Major(version) == "v1"
}
// isV2OrHigherIncompat reports if version has a v2+ major version and is "+incompatible" (e.g., "2.0.0+incompatible")
func isV2OrHigherIncompat(version string) bool {
if !semver.IsValid(version) {
return false
}
major := semver.Major(version)
// minor nuance: here we are purposefully attempting to treat v2.0.0-alpha as a "v2" release
return major != "v0" && major != "v1" && semver.Build(version) == "+incompatible"
}
// TODO: rule to check if mod graph has any invalid semver tags?
// I think not possible to get invalid semver tags via mod graph; I suspect would be error.
// already get error (as error, not vet check): invalid module version "bad": version must be of the form v1.2.3
// or maybe if any go.mod have invalid semver tags for require?
// go mod edit -json reject 'bad' as semver tag... so no need?
// add test? 'require foo bad' -> invalid module version "bad": unknown revision bad
|
[
5
] |
package main
import (
"fmt"
"sync"
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/sdl"
)
const (
birdWidth = 50
birdHeigth = 43
initY = 300
initX = 10
gravity = 0.1
)
type bird struct {
mu sync.RWMutex
textures []*sdl.Texture
speed float64
y, x int32
dead bool
}
func newBird(r *sdl.Renderer) (*bird, error) {
var textures []*sdl.Texture
for i := 1; i <= 4; i++ {
path := fmt.Sprintf("res/img/bird_frame_%d.png", i)
texture, err := img.LoadTexture(r, path)
if err != nil {
return nil, fmt.Errorf("could not load bird, %v", err)
}
textures = append(textures, texture)
}
return &bird{
textures: textures,
y: initY,
x: initX,
dead: false}, nil
}
func (b *bird) update() {
b.y += int32(b.speed)
b.speed -= gravity
if b.y < 0 {
b.dead = true
}
}
func (b *bird) paint(r *sdl.Renderer, t uint64) error {
rect := &sdl.Rect{W: birdWidth, H: birdHeigth, X: b.x, Y: 600 - b.y - int32(birdHeigth/2)}
texIndex := (t / 10) % uint64(len(b.textures))
if err := r.Copy(b.textures[texIndex], nil, rect); err != nil {
return fmt.Errorf("could not copy bird, %v", err)
}
return nil
}
func (b *bird) jump() {
if b.speed < 0 {
b.speed = 3
} else if b.speed > 6 {
b.speed = 6
} else {
b.speed += 2
}
}
func (b *bird) isDead() bool {
return b.dead
}
func (b *bird) revive() {
b.speed = 0
b.y = initY
b.x = initX
b.dead = false
}
func (b *bird) move(m int) {
b.x += int32(m)
}
func (b *bird) hit(p *pipe) {
b.mu.Lock()
defer b.mu.Unlock()
if b.x+birdWidth < p.x {
return
}
if b.x > p.x+p.w {
return
}
if !p.inverted && b.y-birdHeigth/2 > p.h {
return
}
if p.inverted && height-p.h > b.y+birdHeigth/2 {
return
}
b.dead = true
}
|
[
5
] |
package main
import "sort"
func main() {
}
func smallestDistancePair(nums []int, k int) int {
sort.Ints(nums)
n := len(nums)
arr := make([]int, nums[n-1]-nums[0]+1)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
arr[nums[j]-nums[i]]++
}
}
count := 0
for i := 0; i < len(arr); i++ {
count = count + arr[i]
if count >= k {
return i
}
}
return 0
}
|
[
0
] |
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse and unparse this JSON data, add this code to your project and do:
//
// spec, err := UnmarshalSpec(bytes)
// bytes, err = spec.Marshal()
package examengine
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
)
func UnmarshalSpec(data []byte) (Spec, error) {
var r Spec
err := json.Unmarshal(data, &r)
return r, err
}
func (s *Spec) Marshal() ([]byte, error) {
return json.Marshal(s)
}
type Spec struct {
Manager *Manager
// Environment to use
Env string `json:"env"`
// HTTP Only: Source 'master' code to run the values
Source string `json:"source"`
// Entry type defines what sort of application it is
// argv - Values gets passed through the argument variables
// console - Gets passed through STDIN
// http - Values are passed through as rest APIs
Entry string `json:"entry"`
// Inputs determine the values to be passed on the source/test codes
// They can be static values or generated randomly
Data []Input `json:"data"`
// Determines how many passes to run the program
Passes int64 `json:"passes"`
// Timeout in milliseconds, stops the code from running for more than x number of times.
Timeout int64 `json:"timeout"`
// HTTP Only: Endpoints to test
HTTPEndpoints []HTTPEndpoint `json:"endpoints"`
}
type HTTPEndpoint struct {
Endpoint string `json:"endpoint"`
Body interface{} `json:"body"`
Method string `json:"method"`
RequestBody string `json:"requestBody"`
Expected string `json:"expected"`
}
type Input struct {
Arguments []string `json:"arguments"`
Expected string `json:"expected"`
}
type Test struct {
Passed bool `json:"passed"`
Inputs []string `json:"inputs"`
ExpectedOutput string `json:"expectedOutput"`
ActualOutput string `json:"actualOutput"`
}
func (s *Spec) execArgv(testPath string) []Test {
env, found := s.Manager.env.Environments[s.Env]
if !found {
panic(fmt.Errorf("enviroment '%v' not found for spec '%v'", s.Env))
}
var timeout int64 = 1000
if s.Timeout != 0 {
timeout = s.Timeout
}
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
defer cancel()
var tests []Test
for _, i := range s.Data {
var test Test
var args = i.Arguments
resultTest, err := env.Run(ctx, testPath, args)
if err != nil {
panic(err)
}
resOut, err := resultTest.CombinedOutput()
if err != nil {
panic(err)
}
var normalizedTestOutput = strings.TrimSpace(string(resOut))
test.Passed = string(i.Expected) == normalizedTestOutput
test.Inputs = args
test.ExpectedOutput = string(i.Expected)
test.ActualOutput = normalizedTestOutput
tests = append(tests, test)
}
return tests
}
func (s *Spec) execHTTP() []Test {
var tests []Test
for _, i := range s.HTTPEndpoints {
var tmpTest Test
var actual string
var url = "http://" + s.Source + i.Endpoint
if i.Method == "GET" {
actual = SendGet(url)
} else if i.Method == "POST" {
actual = SendPost(url, i.RequestBody)
} else {
panic("Unknown HTTP Method: " + i.Method)
}
tmpTest.Passed = actual == i.Expected
tmpTest.Inputs = []string{url, i.RequestBody}
tmpTest.ExpectedOutput = i.Expected
tmpTest.ActualOutput = actual
tests = append(tests, tmpTest)
}
return tests
}
// ExecuteTest runs the requested tests depending on test type (argv || http)
func (s *Spec) ExecuteTest(testPath string) []Test {
var tests []Test
switch s.Entry {
case "argv":
if testPath == "" {
panic("Test path is empty")
}
tests = s.execArgv(testPath)
case "http":
tests = s.execHTTP()
default:
panic(fmt.Errorf("cannot run test entry through: '%v'", s.Entry))
}
return tests
}
|
[
5
] |
package packet
import (
"errors"
"github.com/sandertv/gophertunnel/minecraft/nbt"
"go.minekube.com/gate/pkg/proto"
"go.minekube.com/gate/pkg/proto/util"
"go.minekube.com/gate/pkg/util/sets"
"io"
)
type JoinGame struct {
EntityId int
Gamemode int16
Dimension int
PartialHashedSeed int64 // 1.15+
Difficulty int16
MaxPlayers int16
LevelType *string // nil-able: removed in 1.16+
ViewDistance int // 1.14+
ReducedDebugInfo bool
ShowRespawnScreen bool
DimensionRegistry *DimensionRegistry // 1.16+
DimensionInfo *DimensionInfo // 1.16+
PreviousGamemode int16 // 1.16+
}
func (j *JoinGame) Encode(c *proto.PacketContext, wr io.Writer) error {
err := util.WriteInt32(wr, int32(j.EntityId))
if err != nil {
return err
}
err = util.WriteByte(wr, byte(j.Gamemode))
if err != nil {
return err
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_16) {
err = util.WriteByte(wr, byte(j.PreviousGamemode))
if err != nil {
return err
}
err = util.WriteStrings(wr, j.DimensionRegistry.LevelNames.UnsortedList())
if err != nil {
return err
}
err = nbt.NewEncoderWithEncoding(wr, nbt.BigEndian).Encode(j.DimensionRegistry.ToNBT())
if err != nil {
return err
}
err = util.WriteString(wr, j.DimensionInfo.RegistryId)
if err != nil {
return err
}
err = util.WriteString(wr, j.DimensionInfo.LevelName)
if err != nil {
return err
}
} else if c.Protocol.GreaterEqual(proto.Minecraft_1_9_1) {
err = util.WriteInt32(wr, int32(j.Dimension))
if err != nil {
return err
}
} else {
err = util.WriteByte(wr, byte(j.Dimension))
if err != nil {
return err
}
}
if c.Protocol.LowerEqual(proto.Minecraft_1_13_2) {
err = util.WriteByte(wr, byte(j.Difficulty))
if err != nil {
return err
}
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_15) {
err = util.WriteInt64(wr, j.PartialHashedSeed)
if err != nil {
return err
}
}
err = util.WriteByte(wr, byte(j.MaxPlayers))
if err != nil {
return err
}
if c.Protocol.Lower(proto.Minecraft_1_16) {
if j.LevelType == nil {
return errors.New("no level type specified")
}
err = util.WriteString(wr, *j.LevelType)
if err != nil {
return err
}
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_14) {
err = util.WriteVarInt(wr, j.ViewDistance)
if err != nil {
return err
}
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_8) {
err = util.WriteBool(wr, j.ReducedDebugInfo)
if err != nil {
return err
}
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_15) {
err = util.WriteBool(wr, j.ShowRespawnScreen)
if err != nil {
return err
}
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_16) {
err = util.WriteBool(wr, j.DimensionInfo.DebugType)
if err != nil {
return err
}
err = util.WriteBool(wr, j.DimensionInfo.Flat)
if err != nil {
return err
}
}
return nil
}
func (j *JoinGame) Decode(c *proto.PacketContext, rd io.Reader) (err error) {
j.EntityId, err = util.ReadInt(rd)
if err != nil {
return err
}
gamemode, err := util.ReadByte(rd)
if err != nil {
return err
}
j.Gamemode = int16(gamemode)
var dimensionIdentifier, levelName string
if c.Protocol.GreaterEqual(proto.Minecraft_1_16) {
previousGamemode, err := util.ReadByte(rd)
if err != nil {
return err
}
j.PreviousGamemode = int16(previousGamemode)
levelNames, err := util.ReadStringArray(rd)
if err != nil {
return err
}
var data util.NBT
if err = nbt.NewDecoderWithEncoding(rd, nbt.BigEndian).Decode(&data); err != nil {
return err
}
readData, err := FromGameData(data)
if err != nil {
return err
}
j.DimensionRegistry = &DimensionRegistry{
Dimensions: readData,
LevelNames: sets.NewString(levelNames...),
}
dimensionIdentifier, err = util.ReadString(rd)
if err != nil {
return err
}
levelName, err = util.ReadString(rd)
if err != nil {
return err
}
} else if c.Protocol.GreaterEqual(proto.Minecraft_1_9_1) {
j.Dimension, err = util.ReadInt(rd)
if err != nil {
return err
}
} else {
d, err := util.ReadByte(rd)
if err != nil {
return err
}
j.Dimension = int(d)
}
if c.Protocol.LowerEqual(proto.Minecraft_1_13_2) {
difficulty, err := util.ReadByte(rd)
if err != nil {
return err
}
j.Difficulty = int16(difficulty)
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_15) {
j.PartialHashedSeed, err = util.ReadInt64(rd)
if err != nil {
return err
}
}
maxPlayers, err := util.ReadByte(rd)
j.MaxPlayers = int16(maxPlayers)
if err != nil {
return err
}
if c.Protocol.Lower(proto.Minecraft_1_16) {
lt, err := util.ReadStringMax(rd, 16)
if err != nil {
return err
}
j.LevelType = <
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_14) {
j.ViewDistance, err = util.ReadVarInt(rd)
if err != nil {
return err
}
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_8) {
j.ReducedDebugInfo, err = util.ReadBool(rd)
if err != nil {
return err
}
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_15) {
j.ShowRespawnScreen, err = util.ReadBool(rd)
if err != nil {
return err
}
}
if c.Protocol.GreaterEqual(proto.Minecraft_1_16) {
debug, err := util.ReadBool(rd)
if err != nil {
return err
}
flat, err := util.ReadBool(rd)
if err != nil {
return err
}
j.DimensionInfo = &DimensionInfo{
RegistryId: dimensionIdentifier,
LevelName: levelName,
Flat: flat,
DebugType: debug,
}
}
return nil
}
var _ proto.Packet = (*JoinGame)(nil)
|
[
5
] |
package main
/////////////////////////////////////////////////////////////////////////
// Convert apple health data records to csv files.
// Tested with export.xml extracted from the zip file from iOS 14.3
// [email protected], Jan-02-2020
/////////////////////////////////////////////////////////////////////////
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/AlekSi/applehealth"
"github.com/AlekSi/applehealth/healthkit"
)
const appName = "applehealth2csv"
const version = "1.0.1"
var (
fileMap = make(map[string]*os.File)
filenameReplacedMap = make(map[string]string)
filenameMap = make(map[string]string)
debug = true
dataFile string
dir string
json = false
header = true
gf *os.File
nrecs = 0
fourSpace = " "
sevenSpace = " "
headerPrinted = false
t = "CSV"
)
const jsonHeaders = ` "sourceName",
"sourceVersion",
"device",
"Type",
"unit",
"creationDate",
"startDate",
"endDate",
"value"`
// open file for writing if it is not opened yet
// WARNING: file will be truncated if it already exists
func openFile(filename string) (file *os.File, error error) {
if fileMap[filename] != nil {
return fileMap[filename], nil
}
f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return nil, err
}
if json {
_, err := gf.Seek(-3, 1)
if err == nil {
if header {
fmt.Fprintf(gf, "]\n")
} else {
fmt.Fprintf(gf, "}\n")
}
fmt.Fprint(gf, "]\n")
}
}
headerPrinted = false
fileMap[filename] = f
gf = f
return f, nil
}
// Nice Trick!
// Ref: https://blog.stathat.com/2012/10/10/time_any_function_in_go.html
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
log.Printf("%s took %s to write %d Records\n", name, elapsed, nrecs)
}
func usage() {
fmt.Fprintf(os.Stderr, "%s v%s\n", appName, version)
fmt.Fprintf(os.Stderr, "https://www.muquit.com/\n")
fmt.Fprintf(os.Stderr, "A program to convert Apple Watch health data to CSV or JSON files\n\n")
fmt.Fprintf(os.Stderr, "To export health data:\n")
fmt.Fprintf(os.Stderr, " 1. Launch Health App on iPhone.\n")
fmt.Fprintf(os.Stderr, " 2. Tap on the profile photo or icon at the top right corner.\n")
fmt.Fprintf(os.Stderr, " 3. Tap \"Export All Health Data\" at the bottom of the screen.\n\n")
fmt.Fprintf(os.Stderr, " Health data will be saved to export.zip file. Use appropriate technique\n")
fmt.Fprintf(os.Stderr, " to transfer the file to your machine. If export.zip is unzipped,\n")
fmt.Fprintf(os.Stderr, " there will be export.xml among other files. This program can take\n")
fmt.Fprintf(os.Stderr, " the zip file or the xml file as input.\n\n")
flag.PrintDefaults()
showExamples()
}
func showExamples() {
fmt.Fprintf(os.Stderr, "\nExample:\n %s -file export.zip -dir ./csv\n", appName)
fmt.Fprintf(os.Stderr, " %s -file export.xml -dir ./csv -debug=false\n", appName)
fmt.Fprintf(os.Stderr, " %s -json -file export.zip -dir ./json_h\n", appName)
fmt.Fprintf(os.Stderr, " %s -json -header=false -file export.zip -dir ./json_nh\n", appName)
}
// return true if file exists, false otherwise
func fileExists(path string) bool {
if _, err := os.Stat(path); err == nil {
return true
}
return false
}
func mkDir(path string) {
if _, err := os.Stat(path); os.IsNotExist(err) {
logDebug("Make directory: %s\n", dir)
os.Mkdir(path, 0755)
}
}
func exitError(format string, a ...interface{}) {
fmt.Printf(format, a...)
os.Exit(1)
}
func logDebug(format string, a ...interface{}) {
if debug {
log.Printf(format, a...)
}
}
func logInfo(format string, a ...interface{}) {
log.Printf(format, a...)
}
func printJSONHeaders(f *os.File) {
fmt.Fprintf(f, "%s[\n%s\n%s],\n",
fourSpace,
jsonHeaders,
fourSpace)
}
func printJSON(f *os.File, data *healthkit.Record) {
// logInfo("header: %t", header)
cs := "{"
ce := "}"
if header {
cs = "["
ce = "]"
}
if header {
fmt.Fprintf(f, "%s%s\n%s\"%s\",\n%s\"%s\",\n%s\"%s\",\n%s\"%s\",\n%s\"%s\",\n%s\"%s\",\n%s\"%s\",\n%s\"%s\",\n%s\"%s\"\n%s%s,\n",
fourSpace,
cs,
sevenSpace,
data.SourceName,
sevenSpace,
data.SourceVersion,
sevenSpace,
data.Device,
sevenSpace,
data.Type,
sevenSpace,
data.Unit,
sevenSpace,
data.CreationDate,
sevenSpace,
data.StartDate,
sevenSpace,
data.EndDate,
sevenSpace,
data.Value,
fourSpace,
ce)
} else {
fmt.Fprintf(f, "%s%s\n%s\"sourceName\": \"%s\",\n%s\"sourceVersion\": \"%s\",\n%s\"device\": \"%s\",\n%s\"type\":\"%s\",\n%s\"unit\": \"%s\",\n%s\"creationDate\": \"%s\",\n%s\"startDate\": \"%s\",\n%s\"endDate\": \"%s\",\n%s\"value\": \"%s\"\n%s%s,\n",
fourSpace,
cs,
sevenSpace,
data.SourceName,
sevenSpace,
data.SourceVersion,
sevenSpace,
data.Device,
sevenSpace,
data.Type,
sevenSpace,
data.Unit,
sevenSpace,
data.CreationDate,
sevenSpace,
data.StartDate,
sevenSpace,
data.EndDate,
sevenSpace,
data.Value,
fourSpace,
ce)
}
}
func main() {
// defer profile.Start().Stop()
// -file
flag.StringVar(&dataFile, "file", "", "Path of export.zip or export.xml file (required)")
// -dir
pwd, err := os.Getwd()
if err != nil {
exitError("Could not determine current working directory")
}
flag.StringVar(&dir, "dir", pwd, "Directory for creating CSV/JSON files")
// -json
flag.BoolVar(&json, "json", false, "Print Output in JSON, default is CSV")
// -header
flag.BoolVar(&header, "header", true, "Print JSON headers at first array")
// -debug
flag.BoolVar(&debug, "debug", true, "Print debug messages")
flag.Usage = func() {
usage()
}
flag.Parse()
if len(dataFile) == 0 {
usage()
os.Exit(1)
}
if !fileExists(dataFile) {
exitError("File '%s' does not exist\n", dataFile)
}
// create directory if it does not exist
if dir != pwd {
mkDir(dir)
}
u, err := applehealth.NewUnmarshaler(dataFile)
if err != nil {
log.Panic(err)
}
defer u.Close()
defer timeTrack(time.Now(), appName)
if json {
t = "JSON"
}
logInfo("%s files will be written to directory: %s\n", t, dir)
ncsv := 0
writeHeader := false
logInfo("%s v%s Creating %s files ....\n", appName, version, t)
for {
var data healthkit.Data
if data, err = u.Next(); err != nil {
break
}
switch data := data.(type) {
case *healthkit.Record:
ext := ".csv"
if json {
ext = ".json"
}
filename := data.Type + ext
ofilename := data.Type + ext
if len(filenameReplacedMap[filename]) == 0 {
filename = strings.Replace(filename, "HKCategoryTypeIdentifier", "", -1)
filename = strings.Replace(filename, "HKQuantityTypeIdentifier", "", -1)
filename = filepath.FromSlash(dir + "/" + filename)
filenameReplacedMap[data.Type+ext] = filename
writeHeader = true
} else {
writeHeader = false
}
if len(filenameMap[ofilename]) == 0 {
logDebug("Creating: %s\n", filename)
filenameMap[ofilename] = filename
}
f, xerr := openFile(filenameMap[ofilename])
if writeHeader && xerr == nil {
defer f.Close()
ncsv = ncsv + 1
if json {
fmt.Fprintf(f, "[\n")
} else {
fmt.Fprintf(f, "sourceName,sourceVersion,device,Type,unit,creationDate,startDate,endDate,value\n")
}
writeHeader = false
}
if xerr == nil {
nrecs++
if json {
if header {
if !headerPrinted {
printJSONHeaders(f)
headerPrinted = true
}
}
printJSON(f, data)
} else {
fmt.Fprintf(f, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n",
data.SourceName,
data.SourceVersion,
data.Device,
data.Type,
data.Unit,
data.CreationDate,
data.StartDate,
data.EndDate,
data.Value)
}
} else {
fmt.Printf("ERRRR: %v\n", xerr)
}
}
}
if ncsv > 0 {
if json {
_, err := gf.Seek(-3, 1)
if err == nil {
if header {
fmt.Fprintf(gf, "]\n")
} else {
fmt.Fprintf(gf, "}\n")
}
fmt.Fprint(gf, "]\n")
}
}
logInfo("Created %d CSV files in %s\n", ncsv, dir)
}
}
|
[
0,
1,
7
] |
package headingholder
import (
"context"
"fmt"
"math"
"sync"
"time"
"github.com/tigerbot-team/tigerbot/go-controller/pkg/imu"
"github.com/tigerbot-team/tigerbot/go-controller/pkg/propeller"
)
func New(i2cLock *sync.Mutex, prop propeller.Interface) *RCHeadingHolder {
return &RCHeadingHolder{
i2cLock: i2cLock,
Propeller: prop,
}
}
// RCHeadingHolder is a more aggressive variant.
type RCHeadingHolder struct {
i2cLock *sync.Mutex // Guards access to the propeller
Propeller propeller.Interface
controlLock sync.Mutex
yaw, throttle, translation float64
currentHeading float64
}
func (y *RCHeadingHolder) SetControlInputs(yaw, throttle, translation float64) {
y.controlLock.Lock()
defer y.controlLock.Unlock()
y.yaw = yaw
y.throttle = throttle
y.translation = translation
}
func (y *RCHeadingHolder) CurrentHeading() float64 {
y.controlLock.Lock()
defer y.controlLock.Unlock()
return y.currentHeading
}
func (y *RCHeadingHolder) Loop(cxt context.Context, wg *sync.WaitGroup) {
defer wg.Done()
defer fmt.Println("Heading holder loop exited")
y.i2cLock.Lock()
m, err := imu.New("/dev/i2c-1")
if err != nil {
fmt.Println("Failed to open IMU", err)
y.i2cLock.Unlock()
panic("Failed to open IMU")
}
m.Configure()
m.Calibrate()
m.ResetFIFO()
y.i2cLock.Unlock()
const imuDT = 10 * time.Millisecond
const targetLoopDT = 20 * time.Millisecond
ticker := time.NewTicker(targetLoopDT)
defer ticker.Stop()
var headingEstimate float64
var targetHeading float64
var filteredTranslation, filteredThrottle float64
var motorRotationSpeed float64
var lastHeadingError float64
var iHeadingError float64
const (
kp = 0.022
ki = 0.0
kd = -0.00008
maxIntegral = 1
maxMotorSpeed = 2.0
maxTranslationDeltaPerSec = 1
maxThrottleDeltaPerSec = 2
)
maxTranslationDelta := maxTranslationDeltaPerSec * targetLoopDT.Seconds()
maxThrottleDelta := maxThrottleDeltaPerSec * targetLoopDT.Seconds()
var lastLoopStart = time.Now()
for cxt.Err() == nil {
<-ticker.C
now := time.Now()
loopTime := now.Sub(lastLoopStart)
lastLoopStart = now
// Integrate the output from the IMU to get our heading estimate.
y.i2cLock.Lock()
yawReadings := m.ReadFIFO()
y.i2cLock.Unlock()
for _, yaw := range yawReadings {
yawDegreesPerSec := float64(yaw) * m.DegreesPerLSB()
headingEstimate -= imuDT.Seconds() * yawDegreesPerSec
}
// Grab the current control values.
y.controlLock.Lock()
targetYaw := y.yaw
targetThrottle := y.throttle
targetTranslation := y.translation
y.currentHeading = headingEstimate
y.controlLock.Unlock()
// Update our target heading accordingly.
loopTimeSecs := loopTime.Seconds()
newTargetHeading := targetHeading + loopTimeSecs*targetYaw*600
const maxLeadDegrees = 40
// If new heading is good, use it. If new heading is out of range but old heading is good, clamp it.
// Otherwise, keep old heading. This helps us recover from shocks or if someone picks up the bot.
if newTargetHeading < headingEstimate+maxLeadDegrees && newTargetHeading > headingEstimate+maxLeadDegrees ||
targetHeading < headingEstimate+maxLeadDegrees && targetHeading > headingEstimate-maxLeadDegrees {
targetHeading = newTargetHeading
if targetHeading > headingEstimate+maxLeadDegrees {
targetHeading = headingEstimate + maxLeadDegrees
} else if targetHeading < headingEstimate-maxLeadDegrees {
targetHeading = headingEstimate - maxLeadDegrees
}
}
// Calculate the error/derivative/integral.
headingError := targetHeading - headingEstimate
dHeadingError := (headingError - lastHeadingError) / loopTimeSecs
iHeadingError += headingError * loopTimeSecs
if iHeadingError > maxIntegral {
iHeadingError = maxIntegral
} else if iHeadingError < -maxIntegral {
iHeadingError = -maxIntegral
}
// Calculate the correction to apply.
rotationCorrection := kp*headingError + ki*iHeadingError + kd*dHeadingError
// Add the correction to the current speed. We want 0 correction to mean "hold the same motor speed".
motorRotationSpeed = rotationCorrection
if motorRotationSpeed > maxMotorSpeed {
motorRotationSpeed = maxMotorSpeed
} else if motorRotationSpeed < -maxMotorSpeed {
motorRotationSpeed = -maxMotorSpeed
}
fmt.Printf("HH: %v Heading: %.1f Target: %.1f Error: %.1f Int: %.1f D: %.1f -> %.1f\n",
loopTime, headingEstimate, targetHeading, headingError, iHeadingError, dHeadingError, motorRotationSpeed)
if math.Abs(targetTranslation) < 0.2 {
filteredTranslation = targetTranslation
} else if targetTranslation > filteredTranslation+maxTranslationDelta {
filteredTranslation += maxTranslationDelta
} else if targetTranslation < filteredTranslation-maxTranslationDelta {
filteredTranslation -= maxTranslationDelta
} else {
filteredTranslation = targetTranslation
}
if math.Abs(targetThrottle) < 0.4 {
filteredThrottle = targetThrottle
} else if targetThrottle > filteredThrottle+maxThrottleDelta {
filteredThrottle += maxThrottleDelta
} else if targetThrottle < filteredThrottle-maxThrottleDelta {
filteredThrottle -= maxThrottleDelta
} else {
filteredThrottle = targetThrottle
}
// Map the values to speeds for each motor.
frontLeft := filteredThrottle + motorRotationSpeed + filteredTranslation
frontRight := filteredThrottle - motorRotationSpeed - filteredTranslation
backLeft := filteredThrottle + motorRotationSpeed - filteredTranslation
backRight := filteredThrottle - motorRotationSpeed + filteredTranslation
m1 := math.Max(frontLeft, frontRight)
m2 := math.Max(backLeft, backRight)
m := math.Max(m1, m2)
scale := 1.0
if m > 1 {
scale = 1.0 / m
}
fl := scaleAndClamp(frontLeft*scale, 127)
fr := scaleAndClamp(frontRight*scale, 127)
bl := scaleAndClamp(backLeft*scale, 127)
br := scaleAndClamp(backRight*scale, 127)
y.i2cLock.Lock()
y.Propeller.SetMotorSpeeds(fl, fr, bl, br)
y.i2cLock.Unlock()
lastHeadingError = headingError
}
y.i2cLock.Lock()
y.Propeller.SetMotorSpeeds(0, 0, 0, 0)
y.i2cLock.Unlock()
}
func scaleAndClamp(value, multiplier float64) int8 {
multiplied := value * multiplier
if multiplied <= math.MinInt8 {
return math.MinInt8
}
if multiplied >= math.MaxInt8 {
return math.MaxInt8
}
return int8(multiplied)
}
|
[
5
] |
package types
import (
"errors"
"net"
"sleepy/types"
"time"
)
const (
ExpiredPeerType = byte(0x04)
NewPeerType = byte(0x03)
OneHourPeerType = byte(0x02)
TwoHourPeerType = byte(0x01)
LongTimePeerType = byte(0x00)
)
type Peer interface {
Equal(other Peer) bool
GetID() types.UInt128
// SetIP set the current [ip] for the peer, and will set it as [verified] or not
SetIP(ip net.IP, verified bool)
// GetIP get the current IP of the peer
GetIP() net.IP
// VerifyIp set a peer as verified if the provided IP is equal than saved
VerifyIp(ip net.IP) bool
IsIPVerified() bool
IsAlive() bool
// InUse Check if the peer is in use
InUse() bool
GetUDPPort() uint16
SetUDPPort(port uint16)
GetTCPPort() uint16
SetTCPPort(port uint16)
GetProtocolVersion() uint8
SetProtocolVersion(version uint8)
GetCreatedAt() time.Time
GetExpiresAt() time.Time
// SetExpiration set the expiration time
SetExpiration(ea time.Time)
// GetDistance calculates the peer distance between this and the other
GetDistance(id types.UInt128) types.UInt128
GetTypeCode() byte
GetTypeUpdatedAt() time.Time
// DegradeType degrade the type of node
DegradeType()
UpdateType()
// UpdateFrom update peer instance from other
UpdateFrom(otherPeer Peer) error
}
type peerImp struct {
id types.UInt128
ip net.IP
udpPort uint16
tcpPort uint16
protocolVersion uint8
ipVerified bool
created time.Time
expires time.Time
typeCode byte
typeUpdated time.Time
useCounter uint
}
func newEmptyPeer() *peerImp {
return &peerImp{
id: types.NewUInt128FromInt(0),
ip: net.IPv4zero,
udpPort: 0,
tcpPort: 0,
protocolVersion: 0,
ipVerified: false,
created: time.Now(),
expires: time.Time{},
typeCode: NewPeerType,
typeUpdated: time.Now(),
useCounter: 0,
}
}
// NewPeer create a new user from his id
func NewPeer(id types.UInt128) Peer {
newPeer := newEmptyPeer()
newPeer.id = id.Clone()
return newPeer
}
// Id gets the current peer id
func (peer *peerImp) GetID() types.UInt128 {
return peer.id.Clone()
}
func (peer *peerImp) SetIP(ip net.IP, verified bool) {
peer.ip = make(net.IP, len(ip))
copy(peer.ip, ip)
peer.ipVerified = verified
}
func (peer *peerImp) GetIP() net.IP {
cpy := make(net.IP, len(peer.ip))
copy(cpy, peer.ip)
return cpy
}
func (peer *peerImp) VerifyIp(ip net.IP) bool {
if !ip.Equal(peer.GetIP()) {
peer.ipVerified = false
return false
} else {
peer.ipVerified = true
return true
}
}
// Check if the current IP is verified
func (peer *peerImp) IsIPVerified() bool {
return peer.ipVerified
}
// Set the UDP port of the peer
func (peer *peerImp) SetUDPPort(port uint16) {
peer.udpPort = port
}
// Get the UDP port of the peer
func (peer *peerImp) GetUDPPort() uint16 {
return peer.udpPort
}
// Set the TCP port of the peer
func (peer *peerImp) SetTCPPort(port uint16) {
peer.tcpPort = port
}
// Get the TCP port of the peer
func (peer *peerImp) GetTCPPort() uint16 {
return peer.tcpPort
}
func (peer *peerImp) GetDistance(id types.UInt128) types.UInt128 {
return types.Xor(peer.id, id)
}
// Check if the peer is alive
func (peer *peerImp) IsAlive() bool {
if peer.typeCode < ExpiredPeerType {
// If expiration time is past
if peer.expires.Before(time.Now()) && peer.GetExpiresAt().After(time.Time{}) {
peer.typeCode = ExpiredPeerType
return false
} else {
return true
}
} else {
// If expiration time is not setted, set an instant of the past
if peer.expires.Equal(time.Time{}) {
peer.expires = time.Now().Add(-time.Microsecond)
}
return false
}
}
func (peer *peerImp) GetCreatedAt() time.Time {
return peer.created
}
func (peer *peerImp) GetExpiresAt() time.Time {
return peer.expires
}
func (peer *peerImp) SetExpiration(expires time.Time) {
peer.expires = expires
}
func (peer *peerImp) GetTypeCode() byte {
return peer.typeCode
}
func (peer *peerImp) GetTypeUpdatedAt() time.Time {
return peer.typeUpdated
}
// Get the protocol version
func (peer *peerImp) GetProtocolVersion() uint8 {
return peer.protocolVersion
}
// Set the protocol version
func (peer *peerImp) SetProtocolVersion(version uint8) {
peer.protocolVersion = version
}
func (peer *peerImp) InUse() bool {
return peer.useCounter > 0
}
// Add a use flag
func (peer *peerImp) AddUse() {
peer.useCounter++
}
// Remove a use flag
func (peer *peerImp) RemoveUse() {
if peer.useCounter > 0 {
peer.useCounter--
} else {
// TODO: Warning?
peer.useCounter = 0
}
}
// Check if two peers are equals (If they have the same Id)
func (peer *peerImp) Equal(otherPeer Peer) bool {
return peer.id.Equal(otherPeer.GetID())
}
func (peer *peerImp) DegradeType() {
// If type rechecked less than 10 seconds ago or is expired, ignore
if time.Now().Sub(peer.typeUpdated) < time.Second*10 || peer.typeCode == ExpiredPeerType {
return
}
peer.typeUpdated = time.Now()
if peer.typeCode < ExpiredPeerType {
peer.typeCode++
}
}
// Update peer type based on internal times
func (peer *peerImp) UpdateType() {
hoursOnline := time.Now().Sub(peer.created)
if hoursOnline > 2*time.Hour {
peer.typeCode = LongTimePeerType
peer.expires = time.Now().Add(time.Hour * 2)
} else if hoursOnline > time.Hour {
peer.typeCode = TwoHourPeerType
peer.expires = time.Now().Add(time.Hour + (time.Minute * 30))
} else {
peer.typeCode = OneHourPeerType
peer.expires = time.Now().Add(time.Hour)
}
}
// Get the time on which peer has been viewed last time
func (peer *peerImp) LastSeen() time.Time {
if !peer.expires.Equal(time.Time{}) {
if peer.typeCode == OneHourPeerType {
return peer.expires.Add(-time.Hour)
} else if peer.typeCode == TwoHourPeerType {
return peer.expires.Add(-time.Hour - (time.Minute * 30))
} else if peer.typeCode == LongTimePeerType {
return peer.expires.Add(-time.Hour * 2)
}
}
return time.Time{}
}
func (peer *peerImp) UpdateFrom(otherPeer Peer) error {
if peer.Equal(otherPeer) {
peer.ip = otherPeer.GetIP()
peer.udpPort = otherPeer.GetUDPPort()
peer.tcpPort = otherPeer.GetTCPPort()
peer.protocolVersion = otherPeer.GetProtocolVersion()
peer.ipVerified = otherPeer.IsIPVerified()
peer.created = otherPeer.GetCreatedAt()
peer.expires = otherPeer.GetExpiresAt()
peer.typeCode = otherPeer.GetTypeCode()
peer.typeUpdated = otherPeer.GetTypeUpdatedAt()
return nil
} else {
return errors.New("the peer information only can be updated with the information of other peer with the same id")
}
}
// Filter a peer slice with an evaluation function
func Filter(peers []Peer, f func(Peer) bool) []Peer {
filtered := make([]Peer, 0)
for _, peer := range peers {
if f(peer) {
filtered = append(filtered, peer)
}
}
return filtered
}
|
[
5
] |
package meekstv
import (
"math/rand"
"sort"
"github.com/shawntoffel/meekstv/events"
)
func (m *meekStv) electEligibleCandidates() int {
eligibleCount := m.findEligibleCandidates()
m.handleMultiwayTie(eligibleCount)
m.newlyElectAllAlmostCandidates()
m.processNewlyElectedCandidates()
return eligibleCount
}
func (m *meekStv) findEligibleCandidates() int {
count := 0
candidates := m.Pool.Hopeful()
for _, candidate := range candidates {
if candidate.Votes >= m.Quota {
count = count + 1
m.Pool.SetAlmost(candidate.Id)
}
}
return count
}
func (m *meekStv) processNewlyElectedCandidates() {
snapshotCandidates := m.Pool.NewlyElected().Snapshot()
sort.Sort(BySnapshotVotes(snapshotCandidates))
for _, snapShotCandidate := range snapshotCandidates {
candidate := m.Pool.Elect(snapShotCandidate.Id)
m.AddEvent(&events.Elected{Name: candidate.Name, Rank: candidate.Rank})
}
}
func (m *meekStv) newlyElectAllAlmostCandidates() {
candidates := m.Pool.Almost()
for _, candidate := range candidates {
m.Pool.NewlyElect(candidate.Id)
m.round().AnyElected = true
}
}
func (m *meekStv) electAllHopefulCandidates() {
m.Pool.ElectHopeful()
m.AddEvent(&events.AllHopefulCandidatesElected{})
}
func (m *meekStv) handleMultiwayTie(eligibleCount int) {
count := eligibleCount
for {
tooMany := m.Pool.ElectedCount()+count > m.NumSeats
if !tooMany {
break
}
m.Pool.ExcludeHopeful()
m.AddEvent(&events.AllHopefulCandidatesExcluded{})
m.excludeLowestCandidate()
count = count - 1
}
}
func (m *meekStv) excludeLowestCandidate() {
lowestCandidates := m.Pool.Lowest()
toExclude := lowestCandidates[0]
randomUsed := false
if len(lowestCandidates) > 1 {
seed := rand.NewSource(m.Seed)
r := rand.New(seed)
i := r.Intn(len(lowestCandidates))
toExclude = lowestCandidates[i]
randomUsed = true
}
m.Pool.Exclude(toExclude.Id)
m.AddEvent(&events.LowestCandidateExcluded{Name: toExclude.Name, RandomUsed: randomUsed})
}
func (m *meekStv) excludeAllNoChanceCandidates() int {
toExclude := MeekCandidates{}
hopefuls := m.Pool.Hopeful()
sort.Sort(ByVotes(hopefuls))
surplus := m.round().Surplus
numElected := len(m.Pool.Elected())
for i := 0; i < len(hopefuls); i++ {
tryExclude := hopefuls[0 : len(hopefuls)-i]
if numElected+len(hopefuls)-len(tryExclude) < m.NumSeats {
continue
}
totalVotes := tryExclude.TotalVotes()
if i != 0 && totalVotes+surplus >= hopefuls[len(hopefuls)-i].Votes {
continue
}
toExclude = tryExclude
break
}
count := len(toExclude)
if count > 0 {
m.Pool.ExcludeMany(toExclude)
m.AddEvent(&events.NoChanceCandidatesExcluded{Names: toExclude.SortedNames()})
}
return count
}
|
[
0
] |
// +--------------------------+
// | |
// | Copyright (c) 2016 |
// | Keith Cullen |
// | |
// +--------------------------+
// Package circbuf provides primitives for implementing circular buffers.
package circbuf
import "fmt"
// A queue implemented using a contiguous buffer with separate indices for reading and writing.
//
// Bytes are copied in to and out from the buffer.
//
// The head index is the next location to be written. It is incremented when items
// are added and wraps to zero when it reaches the end of the linear buffer.
//
// The tail index is the next location to be read. It is incremented when items
// are removed and wraps to zero when it reaches the end of the linear buffer.
//
// When the head index is equal to the tail index, the circular buffer is empty.
// When the head index is one less than the tail index, the circular buffer is full.
type CircBuf struct {
head int // head is the index of the next location in buf to be written.
tail int // tail is the index of the next location in buf to be read.
buf []byte // buf is the linear buffer underlying the circular buffer.
}
// powerOf2 determines if its argument is an integer power of 2.
func powerOf2(x int) bool {
var i int = 1
for i > 0 {
if i == x {
return true
}
i <<= 1
}
return false
}
// New allocates and initialises a circular buffer and returns a pointer to it.
func New(len int) (*CircBuf, error) {
if len <= 0 {
return nil, fmt.Errorf("len argument, %v, is not positive", len)
}
if !powerOf2(len) {
return nil, fmt.Errorf("len argument, %v, is not an integer power of 2", len)
}
c := new(CircBuf)
c.buf = make([]byte, len)
return c, nil
}
// spaceToEnd counts the number of unused bytes in a circular buffer
// to the end of the linear buffer or the end of the circular buffer
// whichever is smaller.
func (c *CircBuf) spaceToEnd() int {
spaceEndLinearBuf := len(c.buf) - c.head
spaceEndCircBuf := (c.tail + spaceEndLinearBuf - 1) & (len(c.buf) - 1)
if spaceEndLinearBuf < spaceEndCircBuf {
return spaceEndLinearBuf
}
return spaceEndCircBuf
}
// countToEndArg counts the number of used bytes in a circular buffer
// to the end of the liner buffer or the end of the circular buffer
// whichever is smaller. The tail parameter allows the Peek function
// to count used bytes without having to update the tail index in the
// circular buffer.
func (c *CircBuf) countToEndArg(tail int) int {
countEndLinearBuf := len(c.buf) - tail
countEndCircBuf := (c.head + countEndLinearBuf) & (len(c.buf) - 1)
if countEndCircBuf < countEndLinearBuf {
return countEndCircBuf
}
return countEndLinearBuf
}
// countToEnd counts the number of used bytes in a circular buffer
// to the end of the liner buffer or the end of the circular buffer
// whichever is smaller.
func (c *CircBuf) countToEnd() int {
return c.countToEndArg(c.tail)
}
// Space returns the number of unused bytes in a circular buffer.
func (c *CircBuf) Space() int {
return (c.tail - c.head - 1) & (len(c.buf) - 1)
}
// Count returns the number of used bytes in a circular buffer.
func (c *CircBuf) Count() int {
return (c.head - c.tail) & (len(c.buf) - 1)
}
// Read reads data from a circular buffer.
// The number of bytes read is returned.
func (c *CircBuf) Read(buf []byte) int {
var count int
var num int
for {
count = c.countToEnd()
if len(buf) - num < count {
count = len(buf) - num
}
if count <= 0 {
break
}
copy(buf[num : num + count], c.buf[c.tail : c.tail + count])
c.tail = (c.tail + count) & (len(c.buf) - 1)
num += count
}
return num
}
// Write writes data to a circular buffer.
// The number of bytes written is returned.
func (c *CircBuf) Write(buf []byte) int {
var space int
var num int
for {
space = c.spaceToEnd()
if len(buf) - num < space {
space = len(buf) - num
}
if space <= 0 {
break
}
copy(c.buf[c.head : c.head + space], buf[num : num + space])
c.head = (c.head + space) & (len(c.buf) - 1)
num += space
}
return num
}
// Peek reads data from a circular buffer but does not update the tail index.
// Subsequent calls to Peek will produce the same results.
// The number of bytes read is returned.
func (c *CircBuf) Peek(buf []byte) int {
var count int
var tail int = c.tail // Use a local tail variable
var num int
for {
count = c.countToEndArg(tail)
if len(buf) - num < count {
count = len(buf) - num
}
if count <= 0 {
break
}
copy(buf[num : num + count], c.buf[tail : tail + count])
tail = (tail + count) & (len(c.buf) - 1)
num += count
}
return num
}
// Consume advances the tail index to remove data from a circular buffer.
// A call to Consume usually follows a call to Peek.
// The number of bytes consumed is returned.
func (c *CircBuf) Consume(nbytes int) int {
var count int
var num int
for {
count = c.countToEnd()
if nbytes - num < count {
count = nbytes - num
}
if count <= 0 {
break
}
c.tail = (c.tail + count) & (len(c.buf) - 1)
num += count
}
return num
}
// String converts a circular buffer to a string representation.
func (c *CircBuf) String() string {
return fmt.Sprintf("CircBuf{len: %v, head: %v, tail: %v, space: %v, count: %v, buf: %v}", len(c.buf), c.head, c.tail, c.Space(), c.Count(), c.buf)
}
|
[
1
] |
// Copyright 2019 TiKV Project 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 analysis
import (
"bufio"
"errors"
"io"
"log"
"os"
"regexp"
"strconv"
"time"
)
var regionOperators = []string{"balance-region", "move-hot-read-region", "move-hot-write-region"}
var leaderOperators = []string{"balance-leader", "transfer-hot-read-leader", "transfer-hot-write-leader"}
// DefaultLayout is the default layout to parse log.
const DefaultLayout = "2006/01/02 15:04:05"
var supportLayouts = map[string]string{
DefaultLayout: ".*?([0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}).*",
}
// Interpreter is the interface for all analysis to parse log
type Interpreter interface {
CompileRegex(operator string) (*regexp.Regexp, error)
ParseLog(filename string, r *regexp.Regexp) error
}
// CompileRegex is to provide regexp for transfer counter.
func (c *TransferCounter) CompileRegex(operator string) (*regexp.Regexp, error) {
var r *regexp.Regexp
var err error
for _, regionOperator := range regionOperators {
if operator == regionOperator {
r, err = regexp.Compile(".*?operator finish.*?region-id=([0-9]*).*?" + operator + ".*?store \\[([0-9]*)\\] to \\[([0-9]*)\\].*?")
}
}
for _, leaderOperator := range leaderOperators {
if operator == leaderOperator {
r, err = regexp.Compile(".*?operator finish.*?region-id=([0-9]*).*?" + operator + ".*?store ([0-9]*) to ([0-9]*).*?")
}
}
if r == nil {
err = errors.New("unsupported operator. ")
}
return r, err
}
func (c *TransferCounter) parseLine(content string, r *regexp.Regexp) ([]uint64, error) {
results := make([]uint64, 0, 4)
subStrings := r.FindStringSubmatch(content)
if len(subStrings) == 0 {
return results, nil
} else if len(subStrings) == 4 {
for i := 1; i < 4; i++ {
num, err := strconv.ParseInt(subStrings[i], 10, 64)
if err != nil {
return results, err
}
results = append(results, uint64(num))
}
return results, nil
} else {
return results, errors.New("Can't parse Log, with " + content)
}
}
func forEachLine(filename string, solve func(string) error) error {
// Open file
fi, err := os.Open(filename)
if err != nil {
return err
}
defer func() {
if err := fi.Close(); err != nil {
log.Printf("error closing file: %s\n", err)
}
}()
br := bufio.NewReader(fi)
// For each
for {
content, _, err := br.ReadLine()
if err != nil {
if err == io.EOF {
break
}
return err
}
err = solve(string(content))
if err != nil {
return err
}
}
return nil
}
func isExpectTime(expect, layout string, isBeforeThanExpect bool) func(time.Time) bool {
expectTime, err := time.Parse(layout, expect)
if err != nil {
return func(current time.Time) bool {
return true
}
}
return func(current time.Time) bool {
return current.Before(expectTime) == isBeforeThanExpect
}
}
func currentTime(layout string) func(content string) (time.Time, error) {
var r *regexp.Regexp
var err error
if pattern, ok := supportLayouts[layout]; ok {
r, err = regexp.Compile(pattern)
if err != nil {
log.Fatal(err)
}
} else {
log.Fatal("unsupported time layout")
}
return func(content string) (time.Time, error) {
result := r.FindStringSubmatch(content)
if len(result) == 2 {
return time.Parse(layout, result[1])
} else if len(result) == 0 {
return time.Time{}, nil
} else {
return time.Time{}, errors.New("There is no valid time in log with " + content)
}
}
}
// ParseLog is to parse log for transfer counter.
func (c *TransferCounter) ParseLog(filename, start, end, layout string, r *regexp.Regexp) error {
afterStart := isExpectTime(start, layout, false)
beforeEnd := isExpectTime(end, layout, true)
getCurrent := currentTime(layout)
err := forEachLine(filename, func(content string) error {
// Get current line time
current, err := getCurrent(content)
if err != nil || current.IsZero() {
return err
}
// if current line time between start and end
if afterStart(current) && beforeEnd(current) {
results, err := c.parseLine(content, r)
if err != nil {
return err
}
if len(results) == 3 {
regionID, sourceID, targetID := results[0], results[1], results[2]
GetTransferCounter().AddTarget(regionID, targetID)
GetTransferCounter().AddSource(regionID, sourceID)
}
}
return nil
})
return err
}
|
[
5
] |
package checkout
import (
"fmt"
"github.com/gato/lana/merchandise"
"testing"
)
func TestNewBasket(t *testing.T) {
basketMap = make(map[string]basket)
basket := NewBasket()
if basket.GetID() == "" {
t.Errorf("Basket ID should not be empty")
return
}
items, err := basket.GetItems()
if err != nil {
t.Errorf("GetCount returned an error %s", err.Error())
return
}
if len(items) != 0 {
t.Errorf("Initial Get Items should have no items")
return
}
if len(basketMap) != 1 {
t.Errorf("Basket was not added to map")
return
}
basket2 := NewBasket()
if len(basketMap) != 2 {
t.Errorf("Basket2 was not added to map")
return
}
if basket2.GetID() == basket.GetID() {
t.Errorf("Basket2 should not be equal to Basket")
}
}
func TestGetBasket(t *testing.T) {
basketMap = make(map[string]basket)
basket := NewBasket()
basket2, err := GetBasket(basket.GetID())
if err != nil {
t.Errorf("GetBasket returned an error %s", err.Error())
return
}
if basket2.GetID() != basket.GetID() {
t.Errorf("Basket2 should be equal to Basket")
}
}
func TestGetBasketNotFound(t *testing.T) {
basketMap = make(map[string]basket)
b := NewBasket()
basketMap = make(map[string]basket)
_, err := GetBasket(b.GetID())
if err == nil {
t.Errorf("GetBasket should have returned an error")
return
}
expected := "Basket not found"
if err.Error() != expected {
t.Errorf("Wrong error expected %s but got %s", expected, err.Error())
}
}
func TestAddItem(t *testing.T) {
basketMap = make(map[string]basket)
b := NewBasket()
count, err := b.AddItem(ProductItem{Product: merchandise.PEN, Count: 2})
if err != nil {
t.Errorf("AddItem returned an error %s", err.Error())
return
}
if count != 2 {
t.Errorf("wrong number of items expected 2 got %d", count)
return
}
count, err = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 3})
if err != nil {
t.Errorf("AddItem returned an error %s", err.Error())
return
}
if count != 5 {
t.Errorf("wrong number of items expected 5 got %d", count)
return
}
}
func TestMixedAddItem(t *testing.T) {
basketMap = make(map[string]basket)
b := NewBasket()
count, err := b.AddItem(ProductItem{Product: merchandise.PEN, Count: 2})
if err != nil {
t.Errorf("AddItem returned an error %s", err.Error())
return
}
if count != 2 {
t.Errorf("wrong number of items expected 2 got %d", count)
return
}
count, err = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 3})
if err != nil {
t.Errorf("AddItem returned an error %s", err.Error())
return
}
if count != 3 {
t.Errorf("wrong number of items expected 3 got %d", count)
return
}
}
func TestAddItemError(t *testing.T) {
basketMap = make(map[string]basket)
b := NewBasket()
count, err := b.AddItem(ProductItem{Product: merchandise.PEN, Count: 2})
if err != nil {
t.Errorf("AddItem returned an error %s", err.Error())
return
}
if count != 2 {
t.Errorf("wrong number of items expected 2 got %d", count)
return
}
// Clear merchandise map to force an error
basketMap = make(map[string]basket)
_, err = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 3})
if err == nil {
t.Errorf("An error was expected")
return
}
}
func findItem(items []ProductItem, code string) (item ProductItem, err error) {
for _, i := range items {
if i.Product == code {
item = i
return
}
}
return
}
func TestGetItems(t *testing.T) {
basketMap = make(map[string]basket)
b := NewBasket()
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 2})
items, err := b.GetItems()
if err != nil {
t.Errorf("GetItems returned an error %s", err.Error())
return
}
if len(items) != 1 {
t.Errorf("wrong number of items expected 1 got %d", len(items))
return
}
_item, err := findItem(items, merchandise.PEN)
if err != nil {
t.Errorf("findItem returned an error %s", err.Error())
return
}
if _item.Count != 2 {
t.Errorf("wrong number of items expected 2 got %d", _item.Count)
return
}
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 3})
items, err = b.GetItems()
if len(items) != 1 {
t.Errorf("wrong number of items expected 1 got %d", len(items))
return
}
_item, err = findItem(items, merchandise.PEN)
if err != nil {
t.Errorf("findItem returned an error %s", err.Error())
return
}
if _item.Count != 5 {
t.Errorf("wrong number of items expected 5 got %d", _item.Count)
return
}
}
func TestGetItemsError(t *testing.T) {
basketMap = make(map[string]basket)
b := NewBasket()
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 2})
items, err := b.GetItems()
if err != nil {
t.Errorf("GetCount returned an error %s", err.Error())
return
}
if len(items) != 1 {
t.Errorf("wrong number of items expected 1 got %d", len(items))
return
}
// Clear merchandise map to force an error
basketMap = make(map[string]basket)
_, err = b.GetItems()
if err == nil {
t.Errorf("An error was expected")
return
}
}
func findBasket(baskets []Basket, id string) (Basket, error) {
for _, b := range baskets {
if b.GetID() == id {
return b, nil
}
}
return nil, fmt.Errorf("Basket not found")
}
func TestListBaskets(t *testing.T) {
basketMap = make(map[string]basket)
baskets := ListBaskets()
if len(baskets) != 0 {
t.Errorf("wrong number of baskets expected 0 got %d", len(baskets))
return
}
b1 := NewBasket()
_, _ = b1.AddItem(ProductItem{Product: merchandise.PEN, Count: 2})
b2 := NewBasket()
_, _ = b2.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 3})
baskets = ListBaskets()
if len(baskets) != 2 {
t.Errorf("wrong number of baskets expected 2 got %d", len(baskets))
return
}
// Validate items returned are the ones that were added
_, err := findBasket(baskets, b1.GetID())
if err != nil {
t.Errorf("first basket not found")
return
}
_, err = findBasket(baskets, b2.GetID())
if err != nil {
t.Errorf("second basket not found")
return
}
}
func TestGetTotal(t *testing.T) {
// Items: PEN, TSHIRT, MUG
// Total: 32.50€
b := NewBasket()
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.MUG, Count: 1})
total, err := b.GetTotal()
if err != nil {
t.Errorf("GetTotal returned an error %s", err.Error())
return
}
expected := 32.5
if total != expected {
t.Errorf("invalid total expected %.2f got %.2f", expected, total)
return
}
// Items: PEN, TSHIRT, PEN
// Total: 25.00€
b = NewBasket()
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
total, _ = b.GetTotal()
expected = 25
if total != expected {
t.Errorf("invalid total expected %.2f got %.2f", expected, total)
return
}
// Items: TSHIRT, TSHIRT, TSHIRT, PEN, TSHIRT
// Total: 65.00€
b = NewBasket()
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
total, _ = b.GetTotal()
expected = 65
if total != expected {
t.Errorf("invalid total expected %.2f got %.2f", expected, total)
return
}
// Items: PEN, TSHIRT, PEN, PEN, MUG, TSHIRT, TSHIRT
// Total: 62.50€
b = NewBasket()
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.MUG, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
_, _ = b.AddItem(ProductItem{Product: merchandise.TSHIRT, Count: 1})
total, _ = b.GetTotal()
expected = 62.50
if total != expected {
t.Errorf("invalid total expected %.2f got %.2f", expected, total)
return
}
}
func TestGetTotalBasketNotFoundError(t *testing.T) {
b := NewBasket()
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
// force error
basketMap = make(map[string]basket)
_, err := b.GetTotal()
if err == nil {
t.Errorf("GetBasket should have returned an error")
return
}
expected := "Basket not found"
if err.Error() != expected {
t.Errorf("Wrong error expected %s but got %s", expected, err.Error())
}
}
type FailingPromo struct{}
func (promotion FailingPromo) Apply(Items map[string]item) (discounts []Discount, err error) {
err = fmt.Errorf("some random error")
return
}
func TestGetTotalPromotionError(t *testing.T) {
basketMap = make(map[string]basket)
b := NewBasket()
// Here I'm adding a failing promotion into basket internals
// This can't be done from the outside as users will only see
// the public interfase
// Only for the sake of test coverage. no real value here
// get the internal basket representation (in a not thread safe way)
internalBasket, _ := basketMap[b.GetID()]
// add new failing promotion
internalBasket.promotions = append(basketMap[b.GetID()].promotions, FailingPromo{})
// replace basket
basketMap[b.GetID()] = internalBasket
_, _ = b.AddItem(ProductItem{Product: merchandise.PEN, Count: 1})
_, err := b.GetTotal()
if err == nil {
t.Errorf("GetBasket should have returned an error")
return
}
expected := "some random error"
if err.Error() != expected {
t.Errorf("Wrong error expected %s but got %s", expected, err.Error())
}
}
func TestDeleteBasket(t *testing.T) {
basketMap = make(map[string]basket)
basket := NewBasket()
baskets := ListBaskets()
if len(baskets) != 1 {
t.Errorf("wrong number of baskets expected 1 got %d", len(baskets))
return
}
err := DeleteBasket(basket.GetID())
if err != nil {
t.Errorf("DeleteBasket returned an error %s", err.Error())
return
}
baskets = ListBaskets()
if len(baskets) != 0 {
t.Errorf("wrong number of baskets expected 0 got %d", len(baskets))
return
}
_, err = GetBasket(basket.GetID())
if err == nil {
t.Errorf("GetBasket should have returned an error")
return
}
expected := "Basket not found"
if err.Error() != expected {
t.Errorf("Wrong error expected %s but got %s", expected, err.Error())
}
}
func TestDeleteBasketNotFoundError(t *testing.T) {
basketMap = make(map[string]basket)
err := DeleteBasket("1234")
if err == nil {
t.Errorf("DeleteBasket should have returned an error")
return
}
expected := "Basket not found"
if err.Error() != expected {
t.Errorf("Wrong error expected %s but got %s", expected, err.Error())
}
}
|
[
2
] |
package solutions
import (
"reflect"
)
func sortColors(nums []int) {
size := len(nums)
if size <= 1 {
return
}
left := 0
right := size - 1
for i := left; i <= right; {
val := nums[i]
if val == 0 {
nums[left], nums[i] = nums[i], nums[left]
left++
i++
} else if val == 2 {
nums[right], nums[i] = nums[i], nums[right]
right--
} else {
i++
}
}
}
func init() {
desc := `
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
`
sol := Solution{
Title: "颜色分类",
Desc: desc,
Method: reflect.ValueOf(sortColors),
Tests: make([]TestCase, 0),
}
SolutionMap["0075"] = sol
}
|
[
5
] |
package internals
import (
"strconv"
)
type Parser struct {
lexer *Lexer
}
func NewParser(input string) *Parser {
p := &Parser{}
p.lexer = NewLexer(input)
return p
}
func (p *Parser) Input() string {
return p.lexer.input
}
func (p *Parser) peek() *Token {
return p.lexer.Peek()
}
func (p *Parser) advance() *Token {
return p.lexer.Advance()
}
func (p *Parser) expect(tokType TokenType) *Token {
if !p.isNext(tokType) {
panic(p.wrongToken(tokType))
}
return p.advance()
}
func (p *Parser) isNext(tokType TokenType) bool {
return p.peek().Type == tokType
}
func (p *Parser) wrongToken(expectedTokenTypes ...TokenType) error {
next := p.peek()
msg := `Unexpected token type ` + next.Type.Name() + ` at index ` + strconv.Itoa(next.Index) + `. Was expecting `
if len(expectedTokenTypes) == 1 {
msg += expectedTokenTypes[0].Name()
} else {
msg += `one of: `
for i, tokenType := range expectedTokenTypes {
if i > 0 {
msg += `, `
}
msg += tokenType.Name()
}
}
return newParseError(msg, p.Input(), next.Index)
}
func (p *Parser) Parse() *ProgramNode {
return p.parseProgram()
}
func (p *Parser) parseProgram() *ProgramNode {
program := &ProgramNode{}
for !p.isNext(TokenTypeEndOfInput) {
if p.isNext(TokenTypeOpenCurly) {
program.AddGroup(p.parseGroup())
} else if p.isNext(TokenTypeExpressionName) {
program.AddExpression(p.parseExpression())
} else {
panic(p.wrongToken(TokenTypeOpenCurly, TokenTypeExpressionName, TokenTypeComma))
}
if p.isNext(TokenTypeComma) { // optional comma
program.AddToken(p.advance())
}
}
program.AddToken(p.expect(TokenTypeEndOfInput))
return program
}
func (p *Parser) parseGroup() *GroupNode {
group := &GroupNode{}
group.AddToken(p.expect(TokenTypeOpenCurly))
for !p.isNext(TokenTypeCloseCurly) {
group.AddExpression(p.parseExpression())
if p.isNext(TokenTypeComma) {
group.AddToken(p.advance())
}
}
group.AddToken(p.expect(TokenTypeCloseCurly))
return group
}
func (p *Parser) parseExpression() *ExpressionNode {
nameTok := p.expect(TokenTypeExpressionName)
expType := nameTok.ExpressionType
exp := &ExpressionNode{}
exp.ExpressionType = expType
exp.AddToken(p.expect(TokenTypeOpenParen))
for {
exp.AddArgument(p.parseArgument(expType))
if p.isNext(TokenTypeComma) {
exp.AddToken(p.advance())
}
if p.isNext(TokenTypeCloseParen) {
break
}
}
exp.AddToken(p.expect(TokenTypeCloseParen))
return exp
}
func (p *Parser) parseArgument(expressionType ExpressionType) *ArgumentNode {
arg := &ArgumentNode{}
if p.isNext(TokenTypeNot) {
arg.IsExclusion = true
arg.AddToken(p.advance())
}
if p.isNext(TokenTypeWildcard) {
arg.IsWildcard = true
arg.AddToken(p.advance())
} else {
arg.Range = p.parseRange(expressionType)
}
if p.isNext(TokenTypeInterval) {
arg.AddToken(p.advance())
arg.Interval = p.parseIntegerValue(ExpressionTypeIntervalValue)
}
return arg
}
func (p *Parser) parseRange(expressionType ExpressionType) *RangeNode {
rangeNode := &RangeNode{}
if expressionType == ExpressionTypeDates {
rangeNode.Start = p.parseDate()
} else {
rangeNode.Start = p.parseIntegerValue(expressionType)
}
isRange := false
if p.isNext(TokenTypeRangeInclusive) {
isRange = true
} else if p.isNext(TokenTypeRangeHalfOpen) {
isRange = true
rangeNode.IsHalfOpen = true
}
if isRange {
rangeNode.AddToken(p.advance())
if expressionType == ExpressionTypeDates {
rangeNode.End = p.parseDate()
} else {
rangeNode.End = p.parseIntegerValue(expressionType)
}
}
return rangeNode
}
func (p *Parser) parseIntegerValue(expressionType ExpressionType) *IntegerValueNode {
val := &IntegerValueNode{}
if p.isNext(TokenTypePositiveInteger) {
// positive integer is valid for anything
tok := p.advance()
val.AddToken(tok)
val.Value = p.parseInt(tok)
} else if p.isNext(TokenTypeNegativeInteger) {
if expressionType != ExpressionTypeDaysOfMonth && expressionType != ExpressionTypeDaysOfYear {
panic(newParseError("Negative values are only allowed in dayofmonth and dayofyear expressions.", p.Input(), p.peek().Index))
}
tok := p.advance()
val.AddToken(tok)
val.Value = p.parseInt(tok)
} else if p.isNext(TokenTypeDayLiteral) {
if expressionType != ExpressionTypeDaysOfWeek {
panic(newParseError("Unexpected day literal. Day literals are only allowed in daysOfWeek expressions.", p.Input(), p.peek().Index))
}
tok := p.advance()
val.AddToken(tok)
val.Value = dayToInteger(tok.Value)
} else {
switch expressionType {
case ExpressionTypeDaysOfMonth, ExpressionTypeDaysOfYear:
panic(p.wrongToken(TokenTypePositiveInteger, TokenTypeNegativeInteger))
case ExpressionTypeDaysOfWeek:
panic(p.wrongToken(TokenTypePositiveInteger, TokenTypeDayLiteral))
default:
panic(p.wrongToken(TokenTypePositiveInteger))
}
}
return val
}
func (p *Parser) parseDate() *DateValueNode {
date := &DateValueNode{}
tok := p.expect(TokenTypePositiveInteger)
date.AddToken(tok)
one := p.parseInt(tok)
date.AddToken(p.expect(TokenTypeForwardSlash))
tok = p.expect(TokenTypePositiveInteger)
date.AddToken(tok)
two := p.parseInt(tok)
three := -1
if p.isNext(TokenTypeForwardSlash) {
date.AddToken(p.advance())
tok = p.expect(TokenTypePositiveInteger)
date.AddToken(tok)
three = p.parseInt(tok)
}
if three != -1 {
// date has a year
date.HasYear = true
date.Year = one
date.Month = two
date.Day = three
} else {
// no year
date.Month = one
date.Day = two
}
return date
}
func dayToInteger(day string) int {
switch day {
case "SUNDAY":
return 1
case "MONDAY":
return 2
case "TUESDAY":
return 3
case "WEDNESDAY":
return 4
case "THURSDAY":
return 5
case "FRIDAY":
return 6
case "SATURDAY":
return 7
default:
panic(day + " is not a day.")
}
}
func (p *Parser) parseInt(tok *Token) int {
i, err := strconv.Atoi(tok.Value)
if err != nil {
msg := "Integer value is too "
if i < 0 {
msg += "small."
} else {
msg += "large."
}
panic(newParseError(msg, p.Input(), tok.Index))
}
return i
}
|
[
5
] |
package main
import (
"flag"
"fmt"
"os"
"github.com/zuiurs/godic/local"
"github.com/zuiurs/godic/thesaurus"
"github.com/zuiurs/godic/weblio"
)
func main() {
var syn, ant, local bool
flag.BoolVar(&syn, "s", false, "search synonym words (short)")
flag.BoolVar(&syn, "syn", false, "search synonym words")
flag.BoolVar(&ant, "a", false, "search antonym words (short)")
flag.BoolVar(&ant, "ant", false, "search antonym words")
flag.BoolVar(&local, "l", false, "search from local dictionary (short)")
flag.BoolVar(&local, "local", false, "search from local dictionary")
flag.Parse()
if (syn && ant) || (ant && local) || (local && syn) {
fmt.Fprintln(os.Stderr, "Error: These option is exclusive")
os.Exit(1)
}
args := flag.Args()
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "Error: Required at least an arguments")
os.Exit(1)
}
if syn || ant {
useThesaurus(args, syn)
} else if local {
useLocal(args)
} else {
useWeblio(args)
}
}
func useThesaurus(args []string, syn bool) {
for _, v := range args {
fmt.Printf("--<%s>--\n", v)
words, err := thesaurus.Search(v)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
continue
}
if syn {
words = thesaurus.SynSort(words)
} else {
words = thesaurus.AntSort(words)
}
for i, w := range words {
// show 5 words
if i > 4 {
break
}
if syn {
if w.Class == thesaurus.ANTONYM {
break
}
} else {
if w.Class == thesaurus.SYNONYM {
break
}
}
fmt.Println(w)
}
}
}
func useWeblio(args []string) {
for _, v := range args {
fmt.Printf("--<%s>--\n", v)
words, err := weblio.Search(v)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
continue
}
for _, w := range words {
fmt.Println(w)
}
}
}
func useLocal(args []string) {
for _, v := range args {
fmt.Printf("--<%s>--\n", v)
state, err := local.Search(v)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
continue
}
fmt.Println(state)
}
}
|
[
5
] |
package main
import (
"fmt"
)
type xx interface {}
func print_empty( X xx ) {
ss := X.(type)
fmt.Printf( " %#v \n", X )
fmt.Printf( " %#T \n", X )
s:= X.(string)
fmt.Println(s)
}
func main() {
fmt.Println("hi")
print_empty( "1111111111" )
}
|
[
2
] |
package main
import (
"encoding/hex"
"fmt"
log "github.com/sirupsen/logrus"
)
type debugTextFormatter struct {
next log.Formatter
}
func (f *debugTextFormatter) Format(entry *log.Entry) ([]byte, error) {
delay := make(map[string][]byte)
for name, value := range entry.Data {
switch data := value.(type) {
case []byte:
delay[name] = data
delete(entry.Data, name)
}
}
var res []byte
res, err := f.next.Format(entry)
if err != nil {
return res, err
}
for name, value := range delay {
res = append(res, []byte(fmt.Sprintf(" %s (%d bytes):\n", name, len(value)))...)
lineStart := true
for _, c := range []byte(hex.Dump(value)) {
if lineStart && c != '\n' {
res = append(res, ' ', ' ', ' ', ' ')
}
res = append(res, c)
lineStart = (c == '\n')
}
}
return res, err
}
|
[
7
] |
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
// {{/*
// +build execgen_template
//
// This file is the execgen template for mergejoinbase.eg.go. It's formatted
// in a special way, so it's both valid Go and a valid text/template input.
// This permits editing this file with editor support.
//
// */}}
package colexecjoin
import (
"github.com/cockroachdb/cockroach/pkg/col/coldata"
"github.com/cockroachdb/cockroach/pkg/col/coldataext"
"github.com/cockroachdb/cockroach/pkg/col/typeconv"
"github.com/cockroachdb/cockroach/pkg/sql/colexecerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/errors"
)
// Workaround for bazel auto-generated code. goimports does not automatically
// pick up the right packages when run within the bazel sandbox.
var (
_ = typeconv.DatumVecCanonicalTypeFamily
_ coldataext.Datum
_ tree.AggType
)
// {{/*
// Declarations to make the template compile properly.
// _CANONICAL_TYPE_FAMILY is the template variable.
const _CANONICAL_TYPE_FAMILY = types.UnknownFamily
// _TYPE_WIDTH is the template variable.
const _TYPE_WIDTH = 0
// _ASSIGN_EQ is the template equality function for assigning the first input
// to the result of the second input == the third input.
func _ASSIGN_EQ(_, _, _, _, _, _ interface{}) int {
colexecerror.InternalError(errors.AssertionFailedf(""))
}
// */}}
// isBufferedGroupFinished checks to see whether or not the buffered group
// corresponding to input continues in batch.
func (o *mergeJoinBase) isBufferedGroupFinished(
input *mergeJoinInput, batch coldata.Batch, rowIdx int,
) bool {
if batch.Length() == 0 {
return true
}
bufferedGroup := o.bufferedGroup.left
if input == &o.right {
bufferedGroup = o.bufferedGroup.right
}
tupleToLookAtIdx := rowIdx
sel := batch.Selection()
if sel != nil {
tupleToLookAtIdx = sel[rowIdx]
}
// Check all equality columns in the first row of batch to make sure we're in
// the same group.
for _, colIdx := range input.eqCols[:len(input.eqCols)] {
switch input.canonicalTypeFamilies[colIdx] {
// {{range .}}
case _CANONICAL_TYPE_FAMILY:
switch input.sourceTypes[colIdx].Width() {
// {{range .WidthOverloads}}
case _TYPE_WIDTH:
// We perform this null check on every equality column of the first
// buffered tuple regardless of the join type since it is done only once
// per batch. In some cases (like INNER join, or LEFT OUTER join with the
// right side being an input) this check will always return false since
// nulls couldn't be buffered up though.
// TODO(yuzefovich): consider templating this.
bufferedNull := bufferedGroup.firstTuple[colIdx].MaybeHasNulls() && bufferedGroup.firstTuple[colIdx].Nulls().NullAt(0)
incomingNull := batch.ColVec(int(colIdx)).MaybeHasNulls() && batch.ColVec(int(colIdx)).Nulls().NullAt(tupleToLookAtIdx)
if o.joinType.IsSetOpJoin() {
if bufferedNull && incomingNull {
// We have a NULL match, so move onto the next column.
continue
}
}
if bufferedNull || incomingNull {
return true
}
bufferedCol := bufferedGroup.firstTuple[colIdx].TemplateType()
prevVal := bufferedCol.Get(0)
col := batch.ColVec(int(colIdx)).TemplateType()
curVal := col.Get(tupleToLookAtIdx)
var match bool
_ASSIGN_EQ(match, prevVal, curVal, _, bufferedCol, col)
if !match {
return true
}
// {{end}}
}
// {{end}}
default:
colexecerror.InternalError(errors.AssertionFailedf("unhandled type %s", input.sourceTypes[colIdx]))
}
}
return false
}
|
[
7
] |
// Created to test using different packages.
package lib
import (
"math"
)
////////////////////////////////////////////////////////////////////////
// Returns the n-th Fibonacci number by recursion.
func Fibonacci( n int ) float64 {
if n == 0 {
return 0.0
} else if n == 1 {
return 1.0
} else {
return Fibonacci(n-1) + Fibonacci(n-2)
}
}
// Function to calculate the Fibonacci number directly.
func Fibonacci_approx( n float64 ) float64 {
return ( math.Pow( 1 + math.Sqrt(5), n ) - math.Pow( 1 - math.Sqrt(5), n ) ) / ( math.Pow(2,n) * math.Sqrt(5) )
}
////////////////////////////////////////////////////////////////////////
|
[
5
] |
package adder
import (
"Taskmanager/pkg/utils"
"fmt"
"strconv"
"sync"
"time"
)
// Adder is responsible for adding a task to the task queue
func Adder(waitGroup sync.WaitGroup) {
taskCounter := 1
for {
newTaskID := strconv.Itoa(taskCounter)
task := utils.Task{newTaskID, false, utils.UnTouched, time.Now(), "taskdata"}
utils.TaskQueue = append(utils.TaskQueue, task)
fmt.Println("", task.Id)
taskCounter = taskCounter + 1
time.Sleep(5 * time.Second)
}
waitGroup.Done()
}
/*
func generateTaskID() string {
rand.Seed(time.Now().UnixNano())
chars := []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789")
length := 8
var id strings.Builder
for i := 0; i < length; i++ {
id.WriteRune(chars[rand.Intn(len(chars))])
}
randomId := id.String()
return randomId
}
*/
|
[
0
] |
// Code generated by mockery v1.0.1. DO NOT EDIT.
package mocks
import (
flyteidlcore "github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/core"
core "github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/core"
mock "github.com/stretchr/testify/mock"
types "k8s.io/apimachinery/pkg/types"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// TaskExecutionMetadata is an autogenerated mock type for the TaskExecutionMetadata type
type TaskExecutionMetadata struct {
mock.Mock
}
type TaskExecutionMetadata_GetAnnotations struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetAnnotations) Return(_a0 map[string]string) *TaskExecutionMetadata_GetAnnotations {
return &TaskExecutionMetadata_GetAnnotations{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetAnnotations() *TaskExecutionMetadata_GetAnnotations {
c := _m.On("GetAnnotations")
return &TaskExecutionMetadata_GetAnnotations{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetAnnotationsMatch(matchers ...interface{}) *TaskExecutionMetadata_GetAnnotations {
c := _m.On("GetAnnotations", matchers...)
return &TaskExecutionMetadata_GetAnnotations{Call: c}
}
// GetAnnotations provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetAnnotations() map[string]string {
ret := _m.Called()
var r0 map[string]string
if rf, ok := ret.Get(0).(func() map[string]string); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(map[string]string)
}
}
return r0
}
type TaskExecutionMetadata_GetK8sServiceAccount struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetK8sServiceAccount) Return(_a0 string) *TaskExecutionMetadata_GetK8sServiceAccount {
return &TaskExecutionMetadata_GetK8sServiceAccount{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetK8sServiceAccount() *TaskExecutionMetadata_GetK8sServiceAccount {
c := _m.On("GetK8sServiceAccount")
return &TaskExecutionMetadata_GetK8sServiceAccount{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetK8sServiceAccountMatch(matchers ...interface{}) *TaskExecutionMetadata_GetK8sServiceAccount {
c := _m.On("GetK8sServiceAccount", matchers...)
return &TaskExecutionMetadata_GetK8sServiceAccount{Call: c}
}
// GetK8sServiceAccount provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetK8sServiceAccount() string {
ret := _m.Called()
var r0 string
if rf, ok := ret.Get(0).(func() string); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(string)
}
return r0
}
type TaskExecutionMetadata_GetLabels struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetLabels) Return(_a0 map[string]string) *TaskExecutionMetadata_GetLabels {
return &TaskExecutionMetadata_GetLabels{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetLabels() *TaskExecutionMetadata_GetLabels {
c := _m.On("GetLabels")
return &TaskExecutionMetadata_GetLabels{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetLabelsMatch(matchers ...interface{}) *TaskExecutionMetadata_GetLabels {
c := _m.On("GetLabels", matchers...)
return &TaskExecutionMetadata_GetLabels{Call: c}
}
// GetLabels provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetLabels() map[string]string {
ret := _m.Called()
var r0 map[string]string
if rf, ok := ret.Get(0).(func() map[string]string); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(map[string]string)
}
}
return r0
}
type TaskExecutionMetadata_GetMaxAttempts struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetMaxAttempts) Return(_a0 uint32) *TaskExecutionMetadata_GetMaxAttempts {
return &TaskExecutionMetadata_GetMaxAttempts{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetMaxAttempts() *TaskExecutionMetadata_GetMaxAttempts {
c := _m.On("GetMaxAttempts")
return &TaskExecutionMetadata_GetMaxAttempts{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetMaxAttemptsMatch(matchers ...interface{}) *TaskExecutionMetadata_GetMaxAttempts {
c := _m.On("GetMaxAttempts", matchers...)
return &TaskExecutionMetadata_GetMaxAttempts{Call: c}
}
// GetMaxAttempts provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetMaxAttempts() uint32 {
ret := _m.Called()
var r0 uint32
if rf, ok := ret.Get(0).(func() uint32); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(uint32)
}
return r0
}
type TaskExecutionMetadata_GetNamespace struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetNamespace) Return(_a0 string) *TaskExecutionMetadata_GetNamespace {
return &TaskExecutionMetadata_GetNamespace{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetNamespace() *TaskExecutionMetadata_GetNamespace {
c := _m.On("GetNamespace")
return &TaskExecutionMetadata_GetNamespace{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetNamespaceMatch(matchers ...interface{}) *TaskExecutionMetadata_GetNamespace {
c := _m.On("GetNamespace", matchers...)
return &TaskExecutionMetadata_GetNamespace{Call: c}
}
// GetNamespace provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetNamespace() string {
ret := _m.Called()
var r0 string
if rf, ok := ret.Get(0).(func() string); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(string)
}
return r0
}
type TaskExecutionMetadata_GetOverrides struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetOverrides) Return(_a0 core.TaskOverrides) *TaskExecutionMetadata_GetOverrides {
return &TaskExecutionMetadata_GetOverrides{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetOverrides() *TaskExecutionMetadata_GetOverrides {
c := _m.On("GetOverrides")
return &TaskExecutionMetadata_GetOverrides{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetOverridesMatch(matchers ...interface{}) *TaskExecutionMetadata_GetOverrides {
c := _m.On("GetOverrides", matchers...)
return &TaskExecutionMetadata_GetOverrides{Call: c}
}
// GetOverrides provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetOverrides() core.TaskOverrides {
ret := _m.Called()
var r0 core.TaskOverrides
if rf, ok := ret.Get(0).(func() core.TaskOverrides); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(core.TaskOverrides)
}
}
return r0
}
type TaskExecutionMetadata_GetOwnerID struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetOwnerID) Return(_a0 types.NamespacedName) *TaskExecutionMetadata_GetOwnerID {
return &TaskExecutionMetadata_GetOwnerID{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetOwnerID() *TaskExecutionMetadata_GetOwnerID {
c := _m.On("GetOwnerID")
return &TaskExecutionMetadata_GetOwnerID{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetOwnerIDMatch(matchers ...interface{}) *TaskExecutionMetadata_GetOwnerID {
c := _m.On("GetOwnerID", matchers...)
return &TaskExecutionMetadata_GetOwnerID{Call: c}
}
// GetOwnerID provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetOwnerID() types.NamespacedName {
ret := _m.Called()
var r0 types.NamespacedName
if rf, ok := ret.Get(0).(func() types.NamespacedName); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(types.NamespacedName)
}
return r0
}
type TaskExecutionMetadata_GetOwnerReference struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetOwnerReference) Return(_a0 v1.OwnerReference) *TaskExecutionMetadata_GetOwnerReference {
return &TaskExecutionMetadata_GetOwnerReference{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetOwnerReference() *TaskExecutionMetadata_GetOwnerReference {
c := _m.On("GetOwnerReference")
return &TaskExecutionMetadata_GetOwnerReference{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetOwnerReferenceMatch(matchers ...interface{}) *TaskExecutionMetadata_GetOwnerReference {
c := _m.On("GetOwnerReference", matchers...)
return &TaskExecutionMetadata_GetOwnerReference{Call: c}
}
// GetOwnerReference provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetOwnerReference() v1.OwnerReference {
ret := _m.Called()
var r0 v1.OwnerReference
if rf, ok := ret.Get(0).(func() v1.OwnerReference); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(v1.OwnerReference)
}
return r0
}
type TaskExecutionMetadata_GetSecurityContext struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetSecurityContext) Return(_a0 flyteidlcore.SecurityContext) *TaskExecutionMetadata_GetSecurityContext {
return &TaskExecutionMetadata_GetSecurityContext{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetSecurityContext() *TaskExecutionMetadata_GetSecurityContext {
c := _m.On("GetSecurityContext")
return &TaskExecutionMetadata_GetSecurityContext{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetSecurityContextMatch(matchers ...interface{}) *TaskExecutionMetadata_GetSecurityContext {
c := _m.On("GetSecurityContext", matchers...)
return &TaskExecutionMetadata_GetSecurityContext{Call: c}
}
// GetSecurityContext provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetSecurityContext() flyteidlcore.SecurityContext {
ret := _m.Called()
var r0 flyteidlcore.SecurityContext
if rf, ok := ret.Get(0).(func() flyteidlcore.SecurityContext); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(flyteidlcore.SecurityContext)
}
return r0
}
type TaskExecutionMetadata_GetTaskExecutionID struct {
*mock.Call
}
func (_m TaskExecutionMetadata_GetTaskExecutionID) Return(_a0 core.TaskExecutionID) *TaskExecutionMetadata_GetTaskExecutionID {
return &TaskExecutionMetadata_GetTaskExecutionID{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnGetTaskExecutionID() *TaskExecutionMetadata_GetTaskExecutionID {
c := _m.On("GetTaskExecutionID")
return &TaskExecutionMetadata_GetTaskExecutionID{Call: c}
}
func (_m *TaskExecutionMetadata) OnGetTaskExecutionIDMatch(matchers ...interface{}) *TaskExecutionMetadata_GetTaskExecutionID {
c := _m.On("GetTaskExecutionID", matchers...)
return &TaskExecutionMetadata_GetTaskExecutionID{Call: c}
}
// GetTaskExecutionID provides a mock function with given fields:
func (_m *TaskExecutionMetadata) GetTaskExecutionID() core.TaskExecutionID {
ret := _m.Called()
var r0 core.TaskExecutionID
if rf, ok := ret.Get(0).(func() core.TaskExecutionID); ok {
r0 = rf()
} else {
if ret.Get(0) != nil {
r0 = ret.Get(0).(core.TaskExecutionID)
}
}
return r0
}
type TaskExecutionMetadata_IsInterruptible struct {
*mock.Call
}
func (_m TaskExecutionMetadata_IsInterruptible) Return(_a0 bool) *TaskExecutionMetadata_IsInterruptible {
return &TaskExecutionMetadata_IsInterruptible{Call: _m.Call.Return(_a0)}
}
func (_m *TaskExecutionMetadata) OnIsInterruptible() *TaskExecutionMetadata_IsInterruptible {
c := _m.On("IsInterruptible")
return &TaskExecutionMetadata_IsInterruptible{Call: c}
}
func (_m *TaskExecutionMetadata) OnIsInterruptibleMatch(matchers ...interface{}) *TaskExecutionMetadata_IsInterruptible {
c := _m.On("IsInterruptible", matchers...)
return &TaskExecutionMetadata_IsInterruptible{Call: c}
}
// IsInterruptible provides a mock function with given fields:
func (_m *TaskExecutionMetadata) IsInterruptible() bool {
ret := _m.Called()
var r0 bool
if rf, ok := ret.Get(0).(func() bool); ok {
r0 = rf()
} else {
r0 = ret.Get(0).(bool)
}
return r0
}
|
[
4
] |
package controllers
import (
"encoding/json"
"github.com/democratic-coin/dcoin-go/packages/utils"
"math"
"strings"
)
func (c *Controller) GetMinerData() (string, error) {
c.r.ParseForm()
secs := float64(3600 * 24 * 365)
userId := utils.StrToInt64(c.r.FormValue("userId"))
if !utils.CheckInputData(userId, "int") {
return `{"result":"incorrect userId"}`, nil
}
minersData, err := c.OneRow("SELECT * FROM miners_data WHERE user_id = ?", userId).String()
if err != nil {
return "", err
}
// получим ID майнеров, у которых лежат фото нужного нам юзера
minersIds := utils.GetMinersKeepers(minersData["photo_block_id"], minersData["photo_max_miner_id"], minersData["miners_keepers"], false)
hosts, err := c.GetList("SELECT http_host as host FROM miners_data WHERE miner_id IN (" + utils.JoinIntsK(minersIds, ",") + ")").String()
if err != nil {
return "", err
}
currencyList, err := c.GetCurrencyList(false)
if err != nil {
return "", err
}
_, _, promisedAmountListGen, err := c.GetPromisedAmounts(userId, c.Variables.Int64["cash_request_time"])
log.Debug("promisedAmountListGen: %v", promisedAmountListGen)
var data utils.DCAmounts
if promisedAmountListGen[72].Amount > 0 {
data = promisedAmountListGen[72]
} else if promisedAmountListGen[23].Amount > 0 {
data = promisedAmountListGen[23]
} else {
data = utils.DCAmounts{}
}
log.Debug("data: %v", data)
promisedAmounts := ""
prognosis := make(map[int64]float64)
if data.Amount > 1 {
promisedAmounts += RoundStr(utils.Float64ToStr(utils.Round(data.Amount, 0)), 0) + " " + currencyList[(data.CurrencyId)] + "<br>"
prognosis[int64(data.CurrencyId)] += (math.Pow(1+data.PctSec, secs) - 1) * data.Amount
}
if len(promisedAmounts) > 0 {
promisedAmounts = "<strong>" + promisedAmounts[:len(promisedAmounts)-4] + "</strong><br>" + c.Lang["promised"] + "<hr>"
}
/*
* На кошельках
* */
balances, err := c.GetBalances(userId)
if err != nil {
return "", err
}
walletsByCurrency := make(map[int]utils.DCAmounts)
for _, data := range balances {
walletsByCurrency[int(data.CurrencyId)] = data
}
log.Debug("walletsByCurrency[72].Amount: %v", walletsByCurrency[72].Amount)
if walletsByCurrency[72].Amount > 0 {
data = walletsByCurrency[72]
} else if walletsByCurrency[23].Amount > 0 {
data = walletsByCurrency[23]
} else {
data = utils.DCAmounts{}
}
log.Debug("data: %v", data)
wallets := ""
var countersIds []string
var pctSec float64
if data.Amount > 0 {
counterId := "map-" + utils.Int64ToStr(userId) + "-" + utils.Int64ToStr(data.CurrencyId)
countersIds = append(countersIds, counterId)
wallets = "<span class='dc_amount' id='" + counterId + "'>" + RoundStr(utils.Float64ToStr(data.Amount), 8) + "</span> d" + currencyList[(data.CurrencyId)] + "<br>"
// прогноз
prognosis[int64(data.CurrencyId)] += (math.Pow(1+data.PctSec, secs) - 1) * data.Amount
pctSec = data.PctSec
}
if len(wallets) > 0 {
wallets = wallets[:len(wallets)-4] + "<br>" + c.Lang["on_the_account"] + "<hr>"
}
/*
* Годовой прогноз
* */
prognosisHtml := ""
for currencyId, amount := range prognosis {
if amount < 0.01 {
continue
} else if amount < 1 {
amount = utils.Round(amount, 2)
} else {
amount = amount
}
prognosisHtml += "<span class='amount_1year'>" + RoundStr(utils.Float64ToStr(amount), 2) + " d" + currencyList[(currencyId)] + "</span><br>"
}
if len(prognosisHtml) > 0 {
prognosisHtml = prognosisHtml[:len(prognosisHtml)-4] + "<br> " + c.Lang["profit_forecast"] + " " + c.Lang["after_1_year"]
}
prognosisHtml = ""
result_ := minersDataType{Hosts: hosts, Lnglat: map[string]string{"lng": minersData["longitude"], "lat": minersData["latitude"]}, Html: promisedAmounts + wallets + "<div style=\"clear:both\"></div>" + prognosisHtml + "</p>", Counters: countersIds, PctSec: pctSec}
log.Debug("result_", result_)
result, err := json.Marshal(result_)
if err != nil {
return "", err
}
log.Debug(string(result))
return string(result), nil
}
func RoundStr(str string, count int) string {
ind := strings.Index(str, ".")
new := ""
if ind != -1 {
end := count
if len(str[ind+1:]) > 1 {
end = count+1
}
point := "."
if count == 0 {
point = ""
}
new = str[:ind] + point + str[ind+1:ind+end]
} else {
new = str
}
return new
}
type minersDataType struct {
Hosts []string `json:"hosts"`
Lnglat map[string]string `json:"lnglat"`
Html string `json:"html"`
Counters []string `json:"counters"`
PctSec float64 `json:"pct_sec"`
}
|
[
5
] |
package interpreter
import "fmt"
const (
OP_PRINT = 6
OP_READ = 7
)
type MemoryCell uint8
type ProgramAddress int
type MemoryAddress int
type MemoryMap map[MemoryAddress]MemoryCell
type Executable interface {
toS(int) string
}
func getIndent(indent int) string {
ind := ""
for i := 0; i < indent; i++ {
ind += " "
}
return ind
}
// =====================
type Operation uint8
func (O Operation) toS(indent int) string {
s := getIndent(indent)
switch O {
case OP_PRINT:
s += "<OP_PRINT>"
case OP_READ:
s += "<OP_READ>"
default:
s += "<OP_NOP>"
}
return s
}
func (O Operation) String() string {
return O.toS(0)
}
// =====================
type Program []Executable
func (P *Program) push(e Executable) {
if _, isModifier := e.(Modifier); !isModifier || e.(Modifier).active {
*P = append(*P, e)
}
}
func (P Program) toS(indent int) string {
s := "<P \n"
for _, v := range P {
s += getIndent(indent) + v.toS(indent) + "\n"
}
return s + ">"
}
func (P Program) String() string {
return P.toS(0)
}
// ===============
type Modifier struct {
mem MemoryMap
dMP MemoryAddress
active bool
}
func NewModifier() Modifier {
return Modifier{mem: MemoryMap{}}
}
func (M *Modifier) add(val int) {
M.mem[M.dMP] += MemoryCell(val)
M.active = true
}
func (M *Modifier) move(val int) {
M.dMP += MemoryAddress(val)
M.active = true
}
func (M Modifier) String() string {
if M.active {
line := ""
if M.dMP > 0 {
line = "-->"
} else if M.dMP < 0 {
line = "<-"
}
return fmt.Sprintf("<M(%s%d) %v>", line, M.dMP, M.mem)
} else {
return fmt.Sprintf("<M Empty>")
}
}
func (M Modifier) toS(indent int) string {
return getIndent(indent) + M.String()
}
// ====================
type Cycle struct {
prg Program
}
func (C Cycle) String() string {
return C.toS(0)
}
func (C Cycle) toS(indent int) string {
return fmt.Sprintf(getIndent(indent) + "<C %s>", C.prg.toS(indent + 1))
}
|
[
2
] |
// Copyright 2016 The Serviced 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 master
import (
"github.com/control-center/serviced/health"
"github.com/control-center/serviced/isvcs"
"time"
)
// GetISvcsHealth returns health status for a list of isvcs
func (c *Client) GetISvcsHealth(IServiceNames []string) ([]isvcs.IServiceHealthResult, error) {
results := []isvcs.IServiceHealthResult{}
if err := c.call("GetISvcsHealth", IServiceNames, &results); err != nil {
return nil, err
}
return results, nil
}
// GetServicesHealth returns health checks for all services.
func (c *Client) GetServicesHealth() (map[string]map[int]map[string]health.HealthStatus, error) {
results := make(map[string]map[int]map[string]health.HealthStatus)
err := c.call("GetServicesHealth", empty, &results)
return results, err
}
// ReportHealthStatus sends an update to the health check status cache.
func (c *Client) ReportHealthStatus(key health.HealthStatusKey, value health.HealthStatus, expires time.Duration) error {
request := HealthStatusRequest{
Key: key,
Value: value,
Expires: expires,
}
return c.call("ReportHealthStatus", request, nil)
}
// ReportInstanceDead removes stopped instances from the health check status cache.
func (c *Client) ReportInstanceDead(serviceID string, instanceID int) error {
request := ReportDeadInstanceRequest{
ServiceID: serviceID,
InstanceID: instanceID,
}
return c.call("ReportInstanceDead", request, nil)
}
|
[
2
] |
/*
* AUTOR: Rafael Tolosana Calasanz
* ASIGNATURA: 30221 Sistemas Distribuidos del Grado en Ingeniería Informática
* Escuela de Ingeniería y Arquitectura - Universidad de Zaragoza
* FECHA: octubre de 2021
* FICHERO: worker.go
* DESCRIPCIÓN: contiene la funcionalidad esencial para realizar los servidores
* correspondientes la practica 3
*/
package main
import (
"log"
"math/rand"
"net"
"net/http"
"net/rpc"
"os"
"sync"
"time"
"fmt"
"practica3/com"
)
const (
NORMAL = iota // NORMAL == 0
DELAY = iota // DELAY == 1
CRASH = iota // CRASH == 2
OMISSION = iota // IOTA == 3
)
type PrimesImpl struct {
delayMaxMilisegundos int
delayMinMiliSegundos int
behaviourPeriod int
behaviour int
i int
mutex sync.Mutex
}
func isPrime(n int) (foundDivisor bool) {
foundDivisor = false
for i := 2; (i < n) && !foundDivisor; i++ {
foundDivisor = (n%i == 0)
}
return !foundDivisor
}
func (p *PrimesImpl) Stop(n int, result *int) error {
os.Exit(n)
return nil
}
// PRE: verdad
// POST: IsPrime devuelve verdad si n es primo y falso en caso contrario
func findPrimes(interval com.TPInterval) (primes []int) {
for i := interval.A; i <= interval.B; i++ {
if isPrime(i) {
primes = append(primes, i)
}
}
return primes
}
// PRE: interval.A < interval.B
// POST: FindPrimes devuelve todos los números primos comprendidos en el
// intervalo [interval.A, interval.B]
func (p *PrimesImpl) FindPrimes(interval com.TPInterval, primeList *[]int) error {
p.mutex.Lock()
if p.i%p.behaviourPeriod == 0 {
p.behaviourPeriod = rand.Intn(20-2) + 2
options := rand.Intn(100)
if options > 90 {
p.behaviour = CRASH
} else if options > 60 {
p.behaviour = DELAY
} else if options > 40 {
p.behaviour = OMISSION
} else {
p.behaviour = NORMAL
}
p.i = 0
}
p.i++
p.mutex.Unlock()
switch p.behaviour {
case DELAY:
seconds := rand.Intn(p.delayMaxMilisegundos-p.delayMinMiliSegundos) + p.delayMinMiliSegundos
time.Sleep(time.Duration(seconds) * time.Millisecond)
*primeList = findPrimes(interval)
case CRASH:
os.Exit(1)
case OMISSION:
option := rand.Intn(100)
if option > 65 {
time.Sleep(time.Duration(10000) * time.Second)
*primeList = findPrimes(interval)
} else {
*primeList = findPrimes(interval)
}
case NORMAL:
*primeList = findPrimes(interval)
default:
*primeList = findPrimes(interval)
}
return nil
}
func main() {
if len(os.Args) == 2 {
time.Sleep(10 * time.Second)
rand.Seed(time.Now().UnixNano())
primesImpl := new(PrimesImpl)
primesImpl.delayMaxMilisegundos = 4000
primesImpl.delayMinMiliSegundos = 2000
primesImpl.behaviourPeriod = 4
primesImpl.i = 1
primesImpl.behaviour = NORMAL
rand.Seed(time.Now().UnixNano())
rpc.Register(primesImpl)
rpc.HandleHTTP()
l, e := net.Listen("tcp", os.Args[1])
if e != nil {
log.Fatal("listen error:", e)
}
http.Serve(l, nil)
} else {
fmt.Println("Usage: go run worker.go <ip:port>")
}
}
|
[
5
] |
/*
Copyright 2020 The Rook Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, 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 osd
import (
"encoding/json"
"fmt"
"path"
"strings"
"github.com/pkg/errors"
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
kms "github.com/rook/rook/pkg/daemon/ceph/osd/kms"
"github.com/rook/rook/pkg/operator/ceph/cluster/mon"
"github.com/rook/rook/pkg/operator/ceph/cluster/osd/config"
"github.com/rook/rook/pkg/operator/ceph/controller"
"github.com/rook/rook/pkg/operator/k8sutil"
batch "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func (c *Cluster) makeJob(osdProps osdProperties, provisionConfig *provisionConfig) (*batch.Job, error) {
podSpec, err := c.provisionPodTemplateSpec(osdProps, v1.RestartPolicyOnFailure, provisionConfig)
if err != nil {
return nil, err
}
if osdProps.onPVC() {
// This is not needed in raw mode and 14.2.8 brings it
// but we still want to do this not to lose backward compatibility with lvm based OSDs...
podSpec.Spec.InitContainers = append(podSpec.Spec.InitContainers, c.getPVCInitContainer(osdProps))
if osdProps.onPVCWithMetadata() {
podSpec.Spec.InitContainers = append(podSpec.Spec.InitContainers, c.getPVCMetadataInitContainer("/srv", osdProps))
}
if osdProps.onPVCWithWal() {
podSpec.Spec.InitContainers = append(podSpec.Spec.InitContainers, c.getPVCWalInitContainer("/wal", osdProps))
}
} else {
podSpec.Spec.NodeSelector = map[string]string{v1.LabelHostname: osdProps.crushHostname}
}
job := &batch.Job{
ObjectMeta: metav1.ObjectMeta{
Name: k8sutil.TruncateNodeNameForJob(prepareAppNameFmt, osdProps.crushHostname),
Namespace: c.clusterInfo.Namespace,
Labels: map[string]string{
k8sutil.AppAttr: prepareAppName,
k8sutil.ClusterAttr: c.clusterInfo.Namespace,
},
},
Spec: batch.JobSpec{
Template: *podSpec,
},
}
if osdProps.onPVC() {
k8sutil.AddLabelToJob(OSDOverPVCLabelKey, osdProps.pvc.ClaimName, job)
k8sutil.AddLabelToJob(CephDeviceSetLabelKey, osdProps.deviceSetName, job)
k8sutil.AddLabelToPod(OSDOverPVCLabelKey, osdProps.pvc.ClaimName, &job.Spec.Template)
k8sutil.AddLabelToPod(CephDeviceSetLabelKey, osdProps.deviceSetName, &job.Spec.Template)
}
k8sutil.AddRookVersionLabelToJob(job)
controller.AddCephVersionLabelToJob(c.clusterInfo.CephVersion, job)
err = c.clusterInfo.OwnerInfo.SetControllerReference(job)
if err != nil {
return nil, err
}
// override the resources of all the init containers and main container with the expected osd prepare resources
c.applyResourcesToAllContainers(&podSpec.Spec, cephv1.GetPrepareOSDResources(c.spec.Resources))
return job, nil
}
// applyResourcesToAllContainers applies consistent resource requests for all containers and all init containers in the pod
func (c *Cluster) applyResourcesToAllContainers(spec *v1.PodSpec, resources v1.ResourceRequirements) {
for i := range spec.InitContainers {
spec.InitContainers[i].Resources = resources
}
for i := range spec.Containers {
spec.Containers[i].Resources = resources
}
}
func (c *Cluster) provisionPodTemplateSpec(osdProps osdProperties, restart v1.RestartPolicy, provisionConfig *provisionConfig) (*v1.PodTemplateSpec, error) {
copyBinariesVolume, copyBinariesContainer := c.getCopyBinariesContainer()
// ceph-volume is currently set up to use /etc/ceph/ceph.conf; this means no user config
// overrides will apply to ceph-volume, but this is unnecessary anyway
volumes := append(controller.PodVolumes(provisionConfig.DataPathMap, c.spec.DataDirHostPath, c.spec.DataDirHostPath, true), copyBinariesVolume)
// create a volume on /dev so the pod can access devices on the host
devVolume := v1.Volume{Name: "devices", VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/dev"}}}
udevVolume := v1.Volume{Name: "udev", VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/run/udev"}}}
volumes = append(volumes, []v1.Volume{
udevVolume,
devVolume,
mon.CephSecretVolume(),
}...)
if osdProps.onPVC() {
// Create volume config for PVCs
volumes = append(volumes, getPVCOSDVolumes(&osdProps, c.spec.DataDirHostPath, c.clusterInfo.Namespace, true)...)
if osdProps.encrypted {
// If a KMS is configured we populate
if c.spec.Security.KeyManagementService.IsEnabled() {
if c.spec.Security.KeyManagementService.IsVaultKMS() {
volumeTLS, _ := kms.VaultVolumeAndMount(c.spec.Security.KeyManagementService.ConnectionDetails, "")
volumes = append(volumes, volumeTLS)
}
if c.spec.Security.KeyManagementService.IsKMIPKMS() {
volumeKMIP, _ := kms.KMIPVolumeAndMount(c.spec.Security.KeyManagementService.TokenSecretName)
volumes = append(volumes, volumeKMIP)
}
}
}
} else {
// If not running on PVC we mount the rootfs of the host to validate the presence of the LVM package
rootFSVolume := v1.Volume{Name: "rootfs", VolumeSource: v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: "/"}}}
volumes = append(volumes, rootFSVolume)
}
if len(volumes) == 0 {
return nil, errors.New("empty volumes")
}
provisionContainer, err := c.provisionOSDContainer(osdProps, copyBinariesContainer.VolumeMounts[0], provisionConfig)
if err != nil {
return nil, errors.Wrap(err, "failed to generate OSD provisioning container")
}
podSpec := v1.PodSpec{
ServiceAccountName: serviceAccountName,
InitContainers: []v1.Container{
*copyBinariesContainer,
},
Containers: []v1.Container{
provisionContainer,
},
RestartPolicy: restart,
Volumes: volumes,
HostNetwork: c.spec.Network.IsHost(),
PriorityClassName: cephv1.GetOSDPriorityClassName(c.spec.PriorityClassNames),
SchedulerName: osdProps.schedulerName,
}
if c.spec.Network.IsHost() {
podSpec.DNSPolicy = v1.DNSClusterFirstWithHostNet
}
if osdProps.onPVC() {
c.applyAllPlacementIfNeeded(&podSpec)
// apply storageClassDeviceSets.preparePlacement
osdProps.getPreparePlacement().ApplyToPodSpec(&podSpec)
} else {
c.applyAllPlacementIfNeeded(&podSpec)
// apply spec.placement.prepareosd
c.spec.Placement[cephv1.KeyOSDPrepare].ApplyToPodSpec(&podSpec)
}
k8sutil.RemoveDuplicateEnvVars(&podSpec)
podMeta := metav1.ObjectMeta{
Name: AppName,
Labels: map[string]string{
k8sutil.AppAttr: prepareAppName,
k8sutil.ClusterAttr: c.clusterInfo.Namespace,
OSDOverPVCLabelKey: osdProps.pvc.ClaimName,
},
Annotations: map[string]string{},
}
cephv1.GetOSDPrepareAnnotations(c.spec.Annotations).ApplyToObjectMeta(&podMeta)
cephv1.GetOSDPrepareLabels(c.spec.Labels).ApplyToObjectMeta(&podMeta)
// ceph-volume --dmcrypt uses cryptsetup that synchronizes with udev on
// host through semaphore
podSpec.HostIPC = osdProps.storeConfig.EncryptedDevice || osdProps.encrypted
return &v1.PodTemplateSpec{
ObjectMeta: podMeta,
Spec: podSpec,
}, nil
}
func (c *Cluster) provisionOSDContainer(osdProps osdProperties, copyBinariesMount v1.VolumeMount, provisionConfig *provisionConfig) (v1.Container, error) {
envVars := c.getConfigEnvVars(osdProps, k8sutil.DataDir, true)
// enable debug logging in the prepare job
envVars = append(envVars, setDebugLogLevelEnvVar(true))
// only 1 of device list, device filter, device path filter and use all devices can be specified. We prioritize in that order.
if len(osdProps.devices) > 0 {
configuredDevices := []config.ConfiguredDevice{}
for _, device := range osdProps.devices {
id := device.Name
if device.FullPath != "" {
id = device.FullPath
}
cd := config.ConfiguredDevice{
ID: id,
StoreConfig: config.ToStoreConfig(device.Config),
}
configuredDevices = append(configuredDevices, cd)
}
marshalledDevices, err := json.Marshal(configuredDevices)
if err != nil {
return v1.Container{}, errors.Wrapf(err, "failed to JSON marshal configured devices for node %q", osdProps.crushHostname)
}
envVars = append(envVars, dataDevicesEnvVar(string(marshalledDevices)))
} else if osdProps.selection.DeviceFilter != "" {
envVars = append(envVars, deviceFilterEnvVar(osdProps.selection.DeviceFilter))
} else if osdProps.selection.DevicePathFilter != "" {
envVars = append(envVars, devicePathFilterEnvVar(osdProps.selection.DevicePathFilter))
} else if osdProps.selection.GetUseAllDevices() {
envVars = append(envVars, deviceFilterEnvVar("all"))
}
envVars = append(envVars, v1.EnvVar{Name: "ROOK_CEPH_VERSION", Value: c.clusterInfo.CephVersion.CephVersionFormatted()})
envVars = append(envVars, crushDeviceClassEnvVar(osdProps.storeConfig.DeviceClass))
envVars = append(envVars, crushInitialWeightEnvVar(osdProps.storeConfig.InitialWeight))
if osdProps.metadataDevice != "" {
envVars = append(envVars, metadataDeviceEnvVar(osdProps.metadataDevice))
}
volumeMounts := append(controller.CephVolumeMounts(provisionConfig.DataPathMap, true), []v1.VolumeMount{
{Name: "devices", MountPath: "/dev"},
{Name: "udev", MountPath: "/run/udev"},
copyBinariesMount,
mon.CephSecretVolumeMount(),
}...)
if controller.LoopDevicesAllowed() {
envVars = append(envVars, v1.EnvVar{Name: "CEPH_VOLUME_ALLOW_LOOP_DEVICES", Value: "true"})
}
// If the OSD runs on PVC
if osdProps.onPVC() {
volumeMounts = append(volumeMounts, getPvcOSDBridgeMount(osdProps.pvc.ClaimName))
// The device list is read by the Rook CLI via environment variables so let's add them
configuredDevices := []config.ConfiguredDevice{
{
ID: fmt.Sprintf("/mnt/%s", osdProps.pvc.ClaimName),
StoreConfig: config.NewStoreConfig(),
},
}
if osdProps.onPVCWithMetadata() {
volumeMounts = append(volumeMounts, getPvcMetadataOSDBridgeMount(osdProps.metadataPVC.ClaimName))
configuredDevices = append(configuredDevices,
config.ConfiguredDevice{
ID: fmt.Sprintf("/srv/%s", osdProps.metadataPVC.ClaimName),
StoreConfig: config.NewStoreConfig(),
})
}
if osdProps.onPVCWithWal() {
volumeMounts = append(volumeMounts, getPvcWalOSDBridgeMount(osdProps.walPVC.ClaimName))
configuredDevices = append(configuredDevices,
config.ConfiguredDevice{
ID: fmt.Sprintf("/wal/%s", osdProps.walPVC.ClaimName),
StoreConfig: config.NewStoreConfig(),
})
}
marshalledDevices, err := json.Marshal(configuredDevices)
if err != nil {
return v1.Container{}, errors.Wrapf(err, "failed to JSON marshal configured devices for PVC %q", osdProps.crushHostname)
}
envVars = append(envVars, dataDevicesEnvVar(string(marshalledDevices)))
envVars = append(envVars, pvcBackedOSDEnvVar("true"))
envVars = append(envVars, encryptedDeviceEnvVar(osdProps.encrypted))
envVars = append(envVars, pvcNameEnvVar(osdProps.pvc.ClaimName))
if osdProps.encrypted {
// If a KMS is configured we populate volume mounts and env variables
if c.spec.Security.KeyManagementService.IsEnabled() {
if c.spec.Security.KeyManagementService.IsVaultKMS() {
_, volumeMountsTLS := kms.VaultVolumeAndMount(c.spec.Security.KeyManagementService.ConnectionDetails, "")
volumeMounts = append(volumeMounts, volumeMountsTLS)
}
envVars = append(envVars, kms.ConfigToEnvVar(c.spec)...)
if c.spec.Security.KeyManagementService.IsKMIPKMS() {
envVars = append(envVars, cephVolumeRawEncryptedEnvVarFromSecret(osdProps))
_, volmeMountsKMIP := kms.KMIPVolumeAndMount(c.spec.Security.KeyManagementService.TokenSecretName)
volumeMounts = append(volumeMounts, volmeMountsKMIP)
}
} else {
envVars = append(envVars, cephVolumeRawEncryptedEnvVarFromSecret(osdProps))
}
}
} else {
// If not running on PVC we mount the rootfs of the host to validate the presence of the LVM package
volumeMounts = append(volumeMounts, v1.VolumeMount{Name: "rootfs", MountPath: "/rootfs", ReadOnly: true})
}
// Add OSD ID as environment variables.
// When this env is set, prepare pod job will destroy this OSD.
if c.replaceOSD != nil {
// Compare pvc claim name in case of OSDs on PVC
if osdProps.onPVC() {
if strings.Contains(c.replaceOSD.Path, osdProps.pvc.ClaimName) {
envVars = append(envVars, replaceOSDIDEnvVar(fmt.Sprint(c.replaceOSD.ID)))
}
} else {
// Compare the node name in case of OSDs on disk
if c.replaceOSD.Node == osdProps.crushHostname {
envVars = append(envVars, replaceOSDIDEnvVar(fmt.Sprint(c.replaceOSD.ID)))
}
}
}
// run privileged always since we always mount /dev
privileged := true
runAsUser := int64(0)
runAsNonRoot := false
readOnlyRootFilesystem := false
osdProvisionContainer := v1.Container{
Command: []string{path.Join(rookBinariesMountPath, "rook")},
Args: []string{"ceph", "osd", "provision"},
Name: "provision",
Image: c.spec.CephVersion.Image,
ImagePullPolicy: controller.GetContainerImagePullPolicy(c.spec.CephVersion.ImagePullPolicy),
VolumeMounts: volumeMounts,
Env: envVars,
EnvFrom: getEnvFromSources(),
SecurityContext: &v1.SecurityContext{
Privileged: &privileged,
RunAsUser: &runAsUser,
RunAsNonRoot: &runAsNonRoot,
ReadOnlyRootFilesystem: &readOnlyRootFilesystem,
},
Resources: cephv1.GetPrepareOSDResources(c.spec.Resources),
}
return osdProvisionContainer, nil
}
|
[
5
] |
package profefe
import (
"fmt"
"net/http"
"path"
"strings"
"github.com/profefe/profefe/pkg/log"
"github.com/profefe/profefe/pkg/profile"
"github.com/profefe/profefe/pkg/storage"
"golang.org/x/xerrors"
)
type ProfilesHandler struct {
logger *log.Logger
collector *Collector
querier *Querier
}
func NewProfilesHandler(logger *log.Logger, collector *Collector, querier *Querier) *ProfilesHandler {
return &ProfilesHandler{
logger: logger,
collector: collector,
querier: querier,
}
}
func (h *ProfilesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var (
handler func(http.ResponseWriter, *http.Request) error
urlPath = path.Clean(r.URL.Path)
)
if urlPath == apiProfilesMergePath {
handler = h.HandleMergeProfile
} else if urlPath == apiProfilesPath {
switch r.Method {
case http.MethodPost:
handler = h.HandleCreateProfile
case http.MethodGet:
handler = h.HandleFindProfiles
}
} else if len(urlPath) > len(apiProfilesPath) {
handler = h.HandleGetProfile
}
var err error
if handler != nil {
err = handler(w, r)
} else {
err = ErrNotFound
}
HandleErrorHTTP(h.logger, err, w, r)
}
func (h *ProfilesHandler) HandleCreateProfile(w http.ResponseWriter, r *http.Request) error {
params := &storage.WriteProfileParams{}
if err := parseWriteProfileParams(params, r); err != nil {
return err
}
profModel, err := h.collector.WriteProfile(r.Context(), params, r.Body)
if err != nil {
return StatusError(http.StatusInternalServerError, "failed to collect profile", err)
}
ReplyJSON(w, profModel)
return nil
}
func (h *ProfilesHandler) HandleGetProfile(w http.ResponseWriter, r *http.Request) error {
pid := r.URL.Path[len(apiProfilesPath):] // id part of the path
pid = strings.Trim(pid, "/")
if pid == "" {
return StatusError(http.StatusBadRequest, "no profile id", nil)
}
w.Header().Set("Content-Type", "application/octet-stream")
err := h.querier.GetProfileTo(r.Context(), w, profile.ID(pid))
if err == storage.ErrNotFound {
return ErrNotFound
} else if err == storage.ErrEmpty {
return ErrEmpty
} else if err != nil {
err = xerrors.Errorf("could not get profile by id %q: %w", pid, err)
return StatusError(http.StatusInternalServerError, fmt.Sprintf("failed to get profile by id %q", pid), err)
}
return nil
}
func (h *ProfilesHandler) HandleFindProfiles(w http.ResponseWriter, r *http.Request) error {
params := &storage.FindProfilesParams{}
if err := parseFindProfileParams(params, r); err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
profModels, err := h.querier.FindProfiles(r.Context(), params)
if err == storage.ErrNotFound {
return ErrNotFound
} else if err == storage.ErrEmpty {
return ErrEmpty
} else if err != nil {
return err
}
ReplyJSON(w, profModels)
return nil
}
func (h *ProfilesHandler) HandleMergeProfile(w http.ResponseWriter, r *http.Request) error {
params := &storage.FindProfilesParams{}
if err := parseFindProfileParams(params, r); err != nil {
return err
}
if params.Type == profile.TypeTrace {
return StatusError(http.StatusMethodNotAllowed, "tracing profiles are not mergeable", nil)
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, params.Type))
err := h.querier.FindMergeProfileTo(r.Context(), w, params)
if err == storage.ErrNotFound {
return ErrNotFound
} else if err == storage.ErrEmpty {
return ErrEmpty
}
return err
}
|
[
5
] |
package main
import (
"fmt"
"strings"
"strconv"
"bufio"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
input1, _ := reader.ReadString('\n')
input1 = strings.TrimSpace(input1)
arrSize, _ := strconv.Atoi(input1)
str, _ := reader.ReadString('\n')
str = strings.TrimSpace(str)
strArr := strings.Split(str, " ")
if len(strArr) < arrSize {
fmt.Println("Given array length is smaller than given array size")
return
}
sum := 0
for ct :=0; ct < arrSize; ct++ {
cur, _ := strconv.Atoi(strArr[ct])
sum = sum + cur
}
fmt.Println(sum)
}
|
[
0
] |
//
// Copyright (c) 2021 Markku Rossi
//
// All rights reserved.
//
package main
import (
"fmt"
)
var fgColors = []string{
"", "30", "31", "32", "33", "34", "35", "36", "37",
"90", "91", "92", "93", "94", "95", "96", "97",
}
var bgColors = []string{
"", "40", "41", "42", "43", "44", "45", "46", "47",
"100", "101", "102", "103", "104", "105", "106", "107",
}
func main() {
fmt.Printf(" ")
for _, bg := range bgColors {
fmt.Printf("%4s", bg)
}
fmt.Println()
for _, fg := range fgColors {
fmt.Printf("%2s ", fg)
for _, bg := range bgColors {
if len(fg) > 0 {
if len(bg) > 0 {
fmt.Printf("\x1b[%s;%sm Aa \x1b[0m", fg, bg)
} else {
fmt.Printf("\x1b[%sm Aa \x1b[0m", fg)
}
} else if len(bg) > 0 {
fmt.Printf("\x1b[%sm Aa \x1b[0m", bg)
} else {
fmt.Printf(" ")
}
}
fmt.Println()
}
}
|
[
5
] |
// Package main is the example package.
package main
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/janek-bieser/gint"
)
type user struct {
FirstName string
LastName string
Email string
}
var users = []user{
{"Jack", "Sparrow", "[email protected]"},
{"Spider", "Man", "[email protected]"},
}
func main() {
r := gin.Default()
// Set our custom HTMLRender
r.HTMLRender = gint.NewHTMLRender()
r.GET("/", homePage)
r.GET("/users", usersPage)
r.GET("/users/:id", userDetailPage)
r.Run()
}
func homePage(c *gin.Context) {
c.HTML(http.StatusOK, "index", gin.H{
"title": "home",
})
}
func usersPage(c *gin.Context) {
c.HTML(http.StatusOK, "users/index", gin.H{
"title": "users",
"users": users,
})
}
func userDetailPage(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if id < 0 || err != nil {
c.Redirect(http.StatusMovedPermanently, "/users/0")
} else if id >= len(users) {
c.Redirect(http.StatusMovedPermanently, fmt.Sprintf("/users/%d", len(users)-1))
} else {
c.HTML(http.StatusOK, "users/detail", gin.H{
"title": "detail",
"user": users[id],
})
}
}
|
[
5
] |
package router
import (
"log"
"net/http"
"net/url"
"strconv"
)
type RoutServe interface {
ServeHTTP(w http.ResponseWriter, r *http.Request)
HEAD(pattern string, hf http.HandlerFunc)
GET(pattern string, hf http.HandlerFunc)
POST(pattern string, hf http.HandlerFunc)
PUT(pattern string, hf http.HandlerFunc)
DEL(pattern string, hf http.HandlerFunc)
OPTIONS(pattern string, hf http.HandlerFunc)
ServeStaticFiles(folderName string)
assign(method string, pattern string, hf http.HandlerFunc)
getMapKey(path string) (url.Values, bool)
}
type RoutHandler struct {
Pattern string
http.HandlerFunc
}
type RoutServeMux struct {
Handlers map[string][]*RoutHandler
}
func NewRoutServeMux() *RoutServeMux {
return &RoutServeMux{Handlers: make(map[string][]*RoutHandler)}
}
func (rout *RoutServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, handler := range rout.Handlers[r.Method] {
if params, ok := handler.getMapKey(r.URL.EscapedPath()); ok {
if len(params) > 0 {
r.URL.RawQuery = params.Encode()
}
handler.ServeHTTP(w, r)
return
}
}
}
func (rout *RoutServeMux) HEAD(pattern string, hf http.HandlerFunc) {
rout.assign("HEAD", pattern, hf)
}
func (rout RoutServeMux) GET(pattern string, hf http.HandlerFunc) {
rout.assign("GET", pattern, hf)
}
func (rout *RoutServeMux) POST(pattern string, hf http.HandlerFunc) {
rout.assign("POST", pattern, hf)
}
func (rout RoutServeMux) PUT(pattern string, hf http.HandlerFunc) {
rout.assign("PUT", pattern, hf)
}
func (rout *RoutServeMux) DEL(pattern string, hf http.HandlerFunc) {
rout.assign("DELETE", pattern, hf)
}
func (rout *RoutServeMux) OPTIONS(pattern string, hf http.HandlerFunc) {
rout.assign("Options", pattern, hf)
}
// CORS - sets in the Header necessary keys and values for CORS policy,
// usage in the same way as any middleware - handler need to be wrapped
func (rout *RoutServeMux) CORS(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setupResponseCORS(&w, r)
if (*r).Method == "OPTIONS" {
return
}
next.ServeHTTP(w, r)
}
}
func (rout *RoutServeMux) JSON(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
setupResponseJSON(w, r)
if (*r).Method == "OPTIONS" {
return
}
next.ServeHTTP(w, r)
}
}
func setupResponseCORS(w *http.ResponseWriter, r *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
func setupResponseJSON(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Credentials", `true`)
w.Header().Set("Content-Type", "application/json")
}
// ServeStaticFile - serve static files and strip pointed directory
// name of directory should writes with no slash, example: "folder"
func (rout *RoutServeMux) ServeStaticFiles(folderName string) {
rout.assign("GET", `/`+folderName+`/`,
rout.HFM(http.StripPrefix(`/`+folderName+`/`,
http.FileServer(http.Dir(`./`+folderName+`/`)))))
}
func (rout *RoutServeMux) assign(method, pattern string, hf http.HandlerFunc) {
handlers := rout.Handlers[method]
for _, handler := range handlers {
if handler.Pattern == pattern {
return
}
}
handler := &RoutHandler{
Pattern: pattern,
HandlerFunc: hf,
}
rout.Handlers[method] = append(handlers, handler)
}
func (rout *RoutServeMux) HFM(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
}
}
func GetKeyInt(r *http.Request, key string) (id int) {
str := r.URL.Query().Get(key)
id, err := strconv.Atoi(str)
if err != nil {
log.Println(err)
}
return
}
func GetKeyStr(r *http.Request, param string) string {
str := r.URL.Query().Get(param)
return str
}
func (rh *RoutHandler) getMapKey(path string) (url.Values, bool) {
mapValues := make(url.Values)
var j int
for i := j; i < len(path); i++ {
switch {
case j >= len(rh.Pattern):
if rh.Pattern != "/" && len(rh.Pattern) > 0 && rh.Pattern[len(rh.Pattern)-1] == '/' {
return mapValues, true
}
return nil, false
case rh.Pattern[j] == ':':
var name, val string
var nextSymbol byte
name, nextSymbol, j = match(rh.Pattern, isStrOrInt, j+1)
val, _, i = match(path, matchPart(nextSymbol), i)
escapedVal, err := url.QueryUnescape(val)
if err != nil {
return nil, false
}
mapValues.Add(":"+name, escapedVal)
case path[i] == rh.Pattern[j]:
j++
default:
return nil, false
}
}
if j != len(rh.Pattern) {
return nil, false
}
return mapValues, true
}
func matchPart(b byte) func(byte) bool {
return func(c byte) bool {
return c != b && c != '/'
}
}
func match(s string, f func(byte) bool, i int) (slice string, next byte, j int) {
for j = i; j < len(s) && f(s[j]); {
j++
}
if j < len(s) {
next = s[j]
}
return s[i:j], next, j
}
func isString(byte byte) bool {
return 'a' <= byte && byte <= 'z' || 'A' <= byte && byte <= 'Z' || byte == '_'
}
func isInt(byte byte) bool {
return '0' <= byte && byte <= '9'
}
func isStrOrInt(byte byte) bool {
return isString(byte) || isInt(byte)
}
|
[
1
] |
package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/alindeman/lint2hub"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type urlFlag struct {
URL *url.URL
}
func (f *urlFlag) Set(s string) error {
url, err := url.Parse(s)
if err != nil {
return err
}
*f.URL = *url
return nil
}
func (f *urlFlag) String() string {
if f.URL == nil {
return ""
}
return f.URL.String()
}
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
os.Exit(1)
}
}
func run() error {
var (
githubAccessToken string
githubBaseURL *url.URL
owner string
repo string
pullRequest int
sha string
pattern string
file string
lineNum int
body string
timeout time.Duration
)
flag.StringVar(&githubAccessToken, "github-access-token", "", "Access token for GitHub API")
flag.Var(&urlFlag{URL: githubBaseURL}, "github-base-url", "Base URL for the GitHub API (defaults to the public GitHub API)")
flag.StringVar(&owner, "owner", "", "Owner of the GitHub repository (i.e., the username or organization name)")
flag.StringVar(&repo, "repo", "", "Name of the GitHub repository")
flag.IntVar(&pullRequest, "pull-request", 0, "Pull request number")
flag.StringVar(&sha, "sha", "", "SHA of the commit of this checkout. If this SHA does not match the latest SHA of the pull request, no comments will be posted")
flag.StringVar(&pattern, "pattern", `^(?P<file>[^:]+):(?P<line>\d+):(?P<column>\d*):(\S+:)* (?P<body>.*)$`, "Regular expression matching standard input. Must contain `file`, `line`, and `body` named capture groups")
flag.StringVar(&file, "file", "", "Filename")
flag.IntVar(&lineNum, "line", 0, "Line number")
flag.StringVar(&body, "body", "", "Body of the comment")
flag.DurationVar(&timeout, "timeout", 30*time.Second, "Timeout")
flag.VisitAll(func(f *flag.Flag) {
if value := os.Getenv(fmt.Sprintf("LINT2HUB_%s", strings.ToUpper(f.Name))); value != "" {
_ = f.Value.Set(value)
}
})
flag.Parse()
if githubAccessToken == "" {
return errors.New("required flag missing: -github-access-token")
}
if owner == "" {
return errors.New("required flag missing: -owner")
}
if repo == "" {
return errors.New("required flag missing: -repo")
}
if pullRequest == 0 {
return errors.New("required flag missing: -pull-request")
}
if sha == "" {
return errors.New("required flag missing: -sha")
}
if pattern != "" {
if file != "" {
return errors.New("both -file and -pattern cannot be specified at the same time")
}
if lineNum != 0 {
return errors.New("both -line and -pattern cannot be specified at the same time")
}
if body != "" {
return errors.New("both -body and -pattern cannot be specified at the same time")
}
} else {
if file == "" {
return errors.New("required flag missing: -file")
}
if lineNum == 0 {
return errors.New("required flag missing: -line")
}
if body == "" {
return errors.New("required flag missing: -body")
}
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: githubAccessToken})
tc := oauth2.NewClient(ctx, ts)
gh := github.NewClient(tc)
if githubBaseURL != nil {
gh.BaseURL = githubBaseURL
}
commenter, err := lint2hub.NewCommenter(ctx, gh, owner, repo, pullRequest, sha)
if err != nil {
return err
}
if pattern != "" {
rePattern, err := regexp.Compile(pattern)
if err != nil {
return err
}
var fileSubmatch, lineSubmatch, bodySubmatch int
for i, name := range rePattern.SubexpNames() {
if name == "file" {
fileSubmatch = i
} else if name == "line" {
lineSubmatch = i
} else if name == "body" {
bodySubmatch = i
}
}
if fileSubmatch == 0 {
return errors.New("-pattern must contain (?P<file>) submatch")
} else if lineSubmatch == 0 {
return errors.New("-pattern must contain (?P<line>) submatch")
} else if bodySubmatch == 0 {
return errors.New("-pattern must contain (?P<body>) submatch")
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := strings.TrimRight(scanner.Text(), "\r\n")
if matches := rePattern.FindStringSubmatch(line); matches != nil {
file := matches[fileSubmatch]
body := matches[bodySubmatch]
lineNum, err := strconv.Atoi(matches[lineSubmatch])
if err != nil {
return fmt.Errorf("cannot convert line number '%v' to integer: %v", matches[lineSubmatch], err)
}
if position, ok := commenter.GetPosition(file, lineNum); ok {
if err := commenter.Post(ctx, file, position, body); err != nil {
return err
}
}
}
}
if err := scanner.Err(); err != nil {
return err
}
} else {
if position, ok := commenter.GetPosition(file, lineNum); ok {
if err := commenter.Post(ctx, file, position, body); err != nil {
return err
}
}
}
return nil
}
|
[
5
] |
package main
import (
"flag"
"github.com/mitchelldavis/hashicorp_verifier/pkg/hv"
"log"
"os"
"path/filepath"
)
func main() {
signatureCommand := flag.NewFlagSet("signature", flag.ExitOnError)
checksumCommand := flag.NewFlagSet("checksum", flag.ExitOnError)
extractCommand := flag.NewFlagSet("extract", flag.ExitOnError)
sig_keyPathPtr := signatureCommand.String("key", "", "The path to the public key")
sig_sigPathPtr := signatureCommand.String("sig", "", "The path to the signature file")
sig_targetPathPtr := signatureCommand.String("target", "", "The path to the file to check")
checksum_checksumPathPtr := checksumCommand.String("shasum", "", "The path to the shasum file")
checksum_targetPathPtr := checksumCommand.String("target", "", "The path to the file to check")
extract_checksumPathPtr := extractCommand.String("shasum", "", "The path to the shasum file")
extract_filenamePtr := extractCommand.String("filename", "", "The base of the file name to extract the checksum for")
// If the subcommand isn't provided, we exit
if len(os.Args) < 2 {
log.Fatal("signature, checksum, or extract subcommand is required")
}
switch os.Args[1] {
case "signature":
signatureCommand.Parse(os.Args[2:])
case "checksum":
checksumCommand.Parse(os.Args[2:])
case "extract":
extractCommand.Parse(os.Args[2:])
default:
flag.PrintDefaults()
os.Exit(1)
}
if signatureCommand.Parsed() {
// Required Flags
if *sig_keyPathPtr == "" || *sig_sigPathPtr == "" || *sig_targetPathPtr == "" {
signatureCommand.PrintDefaults()
os.Exit(1)
}
hv.Verify_Signature(sig_keyPathPtr, sig_sigPathPtr, sig_targetPathPtr)
} else if checksumCommand.Parsed() {
// Required Flags
if *checksum_checksumPathPtr == "" || *checksum_targetPathPtr == "" {
checksumCommand.PrintDefaults()
os.Exit(1)
}
filename := filepath.Base(*checksum_targetPathPtr)
hv.Verify_Checksum(checksum_checksumPathPtr, checksum_targetPathPtr, &filename)
} else if extractCommand.Parsed() {
// Required Flags
if *extract_checksumPathPtr == "" || *extract_filenamePtr == "" {
extractCommand.PrintDefaults()
os.Exit(1)
}
hv.Extract_Checksum(extract_checksumPathPtr, extract_filenamePtr)
}
}
|
[
5
] |
package models
import (
"time"
"github.com/toolkits/logger"
"github.com/coraldane/ops-meta/db"
"github.com/coraldane/ops-meta/utils"
)
type Endpoint struct {
Id int64
GmtCreate time.Time `orm:"type(datetime)"`
GmtModified time.Time `orm:"type(datetime)"`
Hostname string `form:"hostname"`
Ip string `form:"ip"`
UpdaterVersion string `form:"updaterVersion" orm:"null"`
RunUser string `form:"runUser" orm:"null"`
}
func (this *Endpoint) TableUnique() [][]string {
return [][]string{
[]string{"Hostname"},
}
}
func (this *Endpoint) Insert() (int64, error) {
num, err := db.NewOrm().QueryTable(Endpoint{}).Filter("Hostname", this.Hostname).Count()
if nil != err {
return 0, err
} else if 0 == num {
this.GmtCreate = time.Now()
this.GmtModified = time.Now()
return db.NewOrm().Insert(this)
} else {
strSql := `update t_endpoint set gmt_modified=?, ip = ?, updater_version = ?, run_user = ? where hostname=?`
result, err := db.NewOrm().Raw(strSql, utils.FormatUTCTime(time.Now()), this.Ip, this.UpdaterVersion, this.RunUser, this.Hostname).Exec()
if nil != err {
logger.Errorln("insert endpoint fail: ", err)
return 0, err
}
return result.RowsAffected()
}
}
func (this *Endpoint) DeleteByPK() (int64, error) {
result, err := this.DeleteByCond()
ea := EndpointAgent{Hostname: this.Hostname}
ea.Delete([]string{})
return result, err
}
func (this *Endpoint) DeleteByCond() (int64, error) {
query := db.NewOrm().QueryTable(Endpoint{})
if 0 < this.Id {
query = query.Filter("Id", this.Id)
}
if "" != this.Hostname {
query = query.Filter("Hostname", this.Hostname)
}
if "" != this.Ip {
query = query.Filter("Ip", this.Ip)
}
return query.Delete()
}
func QueryEndpointList(queryDto QueryEndpointDto, pageInfo *PageInfo) ([]Endpoint, *PageInfo) {
var rows []Endpoint
query := db.NewOrm().QueryTable(Endpoint{})
if "" != queryDto.Hostname {
query = query.Filter("hostname__icontains", queryDto.Hostname)
}
if "" != queryDto.Ip {
query = query.Filter("ip__contains", queryDto.Ip)
}
rowCount, err := query.Count()
if nil != err {
logger.Errorln("queryCount error", err)
pageInfo.SetRowCount(0)
return nil, pageInfo
}
pageInfo.SetRowCount(rowCount)
_, err = query.OrderBy("-GmtModified").Offset(pageInfo.GetStartIndex()).Limit(pageInfo.PageSize).All(&rows)
if nil != err {
logger.Errorln("QueryEndpointList error", err)
}
return rows, pageInfo
}
|
[
5
] |
package main
import (
"fmt"
"github.com/gobs/args"
"github.com/iikira/BaiduPCS-Go/command"
"github.com/iikira/BaiduPCS-Go/config"
"github.com/kardianos/osext"
"github.com/peterh/liner"
"github.com/urfave/cli"
"io"
"log"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
)
var (
historyFile = "pcs_command_history.txt"
reloadFn = func(c *cli.Context) error {
baidupcscmd.ReloadIfInConsole()
return nil
}
)
func init() {
// change work directory
folderPath, err := osext.ExecutableFolder()
if err != nil {
folderPath, err = filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
folderPath = filepath.Dir(os.Args[0])
}
}
os.Chdir(folderPath)
}
func main() {
app := cli.NewApp()
app.Name = "baidupcs_go"
app.Author = "iikira/BaiduPCS-Go: https://github.com/iikira/BaiduPCS-Go"
app.Usage = fmt.Sprintf("百度网盘工具箱 %s/%s GoVersion %s", runtime.GOOS, runtime.GOARCH, runtime.Version())
app.Description = `baidupcs_go 使用 Go语言编写, 为操作百度网盘, 提供实用功能.
具体功能, 参见 COMMANDS 列表
特色:
网盘内列出文件和目录, 支持通配符匹配路径;
下载网盘内文件, 支持高并发下载和断点续传.
程序目前处于测试版, 后续会添加更多的实用功能.`
app.Version = "beta-v1"
app.Action = func(c *cli.Context) {
if c.NArg() == 0 {
cli.ShowAppHelp(c)
line := newLiner()
defer closeLiner(line)
for {
if commandLine, err := line.Prompt("BaiduPCS-Go > "); err == nil {
line.AppendHistory(commandLine)
cmdArgs := args.GetArgs(commandLine)
if len(cmdArgs) == 0 {
continue
}
s := []string{os.Args[0]}
s = append(s, cmdArgs...)
closeLiner(line)
c.App.Run(s)
line = newLiner()
} else if err == liner.ErrPromptAborted || err == io.EOF {
break
} else {
log.Print("Error reading line: ", err)
continue
}
}
} else {
fmt.Printf("未找到命令: %s\n运行命令 %s help 获取帮助\n", c.Args().Get(0), app.Name)
}
}
app.Commands = []cli.Command{
{
Name: "login",
Usage: "使用百度BDUSS登录百度账号",
Description: fmt.Sprintf("\n 示例: \n\n %s\n\n %s\n\n %s\n\n %s\n\n %s\n",
app.Name+" login --bduss=123456789",
app.Name+" login",
"百度BDUSS获取方法: ",
"参考这篇 Wiki: https://github.com/iikira/BaiduPCS-Go/wiki/关于-获取百度-BDUSS",
"或者百度搜索: 获取百度BDUSS",
),
Category: "百度帐号操作",
Before: reloadFn,
After: reloadFn,
Action: func(c *cli.Context) error {
bduss := ""
if c.IsSet("bduss") {
bduss = c.String("bduss")
} else if c.NArg() == 0 {
cli.ShowCommandHelp(c, c.Command.Name)
line := liner.NewLiner()
line.SetCtrlCAborts(true)
defer line.Close()
bduss, _ = line.Prompt("请输入百度BDUSS值, 回车键提交 > ")
} else {
cli.ShowCommandHelp(c, c.Command.Name)
return nil
}
username, err := pcsconfig.Config.SetBDUSS(bduss)
if err != nil {
fmt.Println(err)
return nil
}
fmt.Println("百度帐号登录成功:", username)
return nil
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "bduss",
Usage: "百度BDUSS",
},
},
},
{
Name: "chuser",
Usage: "切换已登录的百度帐号",
Description: fmt.Sprintf("%s\n 示例:\n\n %s\n %s\n",
"如果运行该条命令没有提供参数, 程序将会列出所有的百度帐号, 供选择切换",
app.Name+" chuser --uid=123456789",
app.Name+" chuser",
),
Category: "百度帐号操作",
Before: reloadFn,
After: reloadFn,
Action: func(c *cli.Context) error {
if len(pcsconfig.Config.BaiduUserList) == 0 {
fmt.Println("未设置任何百度帐号, 不能切换")
return nil
}
var uid uint64
if c.IsSet("uid") {
if pcsconfig.Config.CheckUIDExist(c.Uint64("uid")) {
uid = c.Uint64("uid")
} else {
fmt.Println("切换用户失败, uid 不存在")
}
} else if c.NArg() == 0 {
cli.HandleAction(app.Command("loglist").Action, c)
line := liner.NewLiner()
line.SetCtrlCAborts(true)
defer line.Close()
nLine, _ := line.Prompt("请输入要切换帐号的 index 值 > ")
if n, err := strconv.Atoi(nLine); err == nil && n >= 0 && n < len(pcsconfig.Config.BaiduUserList) {
uid = pcsconfig.Config.BaiduUserList[n].UID
} else {
fmt.Println("切换用户失败, 请检查 index 值是否正确")
}
} else {
cli.ShowCommandHelp(c, c.Command.Name)
}
if uid == 0 {
return nil
}
pcsconfig.Config.BaiduActiveUID = uid
if err := pcsconfig.Config.Save(); err != nil {
fmt.Println(err)
return nil
}
fmt.Printf("切换用户成功, %v\n", pcsconfig.ActiveBaiduUser.Name)
return nil
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "uid",
Usage: "百度帐号 uid 值",
},
},
},
{
Name: "logout",
Usage: "退出已登录的百度帐号",
Description: fmt.Sprintf("%s\n 示例:\n\n %s\n %s\n",
"如果运行该条命令没有提供参数, 程序将会列出所有的百度帐号, 供选择退出",
app.Name+" logout --uid=123456789",
app.Name+" logout",
),
Category: "百度帐号操作",
Before: reloadFn,
After: reloadFn,
Action: func(c *cli.Context) error {
if len(pcsconfig.Config.BaiduUserList) == 0 {
fmt.Println("未设置任何百度帐号, 不能退出")
return nil
}
var uid uint64
if c.IsSet("uid") {
if pcsconfig.Config.CheckUIDExist(c.Uint64("uid")) {
uid = c.Uint64("uid")
} else {
fmt.Println("退出用户失败, uid 不存在")
}
} else if c.NArg() == 0 {
cli.HandleAction(app.Command("loglist").Action, c)
line := liner.NewLiner()
line.SetCtrlCAborts(true)
defer line.Close()
nLine, _ := line.Prompt("请输入要退出帐号的 index 值 > ")
if n, err := strconv.Atoi(nLine); err == nil && n >= 0 && n < len(pcsconfig.Config.BaiduUserList) {
uid = pcsconfig.Config.BaiduUserList[n].UID
} else {
fmt.Println("退出用户失败, 请检查 index 值是否正确")
}
} else {
cli.ShowCommandHelp(c, c.Command.Name)
}
if uid == 0 {
return nil
}
// 删除之前先获取被删除的数据, 用于下文输出日志
baidu, err := pcsconfig.Config.GetBaiduUserByUID(uid)
if err != nil {
fmt.Println(err)
return nil
}
if !pcsconfig.Config.DeleteBaiduUserByUID(uid) {
fmt.Printf("退出用户失败, %s\n", baidu.Name)
}
fmt.Printf("退出用户成功, %v\n", baidu.Name)
return nil
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "uid",
Usage: "百度帐号 uid 值",
},
},
},
{
Name: "loglist",
Usage: "获取当前帐号, 和所有已登录的百度帐号",
UsageText: fmt.Sprintf("%s loglist", app.Name),
Category: "百度帐号操作",
Before: reloadFn,
Action: func(c *cli.Context) error {
fmt.Printf("\n当前帐号 uid: %d, 用户名: %s\n", pcsconfig.ActiveBaiduUser.UID, pcsconfig.ActiveBaiduUser.Name)
fmt.Println(pcsconfig.Config.GetAllBaiduUser())
return nil
},
},
{
Name: "quota",
Usage: "获取配额, 即获取网盘总空间, 和已使用空间",
UsageText: fmt.Sprintf("%s quota", app.Name),
Category: "网盘操作",
Before: reloadFn,
Action: func(c *cli.Context) error {
baidupcscmd.RunGetQuota()
return nil
},
},
{
Name: "cd",
Usage: "切换工作目录",
UsageText: fmt.Sprintf("%s cd <目录>", app.Name),
Category: "网盘操作",
Before: reloadFn,
After: reloadFn,
Action: func(c *cli.Context) error {
if c.NArg() == 0 {
cli.ShowCommandHelp(c, c.Command.Name)
return nil
}
baidupcscmd.RunChangeDirectory(c.Args().Get(0))
return nil
},
},
{
Name: "ls",
Aliases: []string{"l", "ll"},
Usage: "列出当前工作目录的文件和目录或指定目录",
UsageText: fmt.Sprintf("%s ls <目录>", app.Name),
Category: "网盘操作",
Before: reloadFn,
Action: func(c *cli.Context) error {
baidupcscmd.RunLs(c.Args().Get(0))
return nil
},
},
{
Name: "pwd",
Usage: "输出当前所在目录",
UsageText: fmt.Sprintf("%s pwd", app.Name),
Category: "网盘操作",
Before: reloadFn,
Action: func(c *cli.Context) error {
fmt.Println(pcsconfig.ActiveBaiduUser.Workdir)
return nil
},
},
{
Name: "meta",
Usage: "获取单个文件/目录的元信息 (详细信息)",
UsageText: fmt.Sprintf("%s meta <文件/目录 路径>", app.Name),
Category: "网盘操作",
Before: reloadFn,
Action: func(c *cli.Context) error {
baidupcscmd.RunGetMeta(c.Args().Get(0))
return nil
},
},
{
Name: "download",
Aliases: []string{"d"},
Usage: "下载文件, 网盘文件绝对路径或相对路径",
UsageText: fmt.Sprintf("%s download <网盘文件的路径>", app.Name),
Description: "下载的文件将会保存到, 程序所在目录的 download/ 目录 (文件夹), 暂不支持指定目录, \n 重名的文件将会被覆盖! \n",
Category: "网盘操作",
Before: reloadFn,
Action: func(c *cli.Context) error {
if c.NArg() == 0 {
cli.ShowCommandHelp(c, c.Command.Name)
return nil
}
baidupcscmd.RunDownload(c.Args().Get(0))
return nil
},
},
{
Name: "set",
Usage: "设置配置",
UsageText: fmt.Sprintf("%s set OptionName Value", app.Name),
Description: `
可设置的值:
OptionName Value
------------------
max_parallel 下载最大线程 (并发量) - 建议值 ( 100 ~ 500 )
例子:
set max_parallel 250
`,
Category: "配置",
Before: reloadFn,
After: reloadFn,
Action: func(c *cli.Context) error {
if c.NArg() < 2 {
cli.ShowCommandHelp(c, c.Command.Name)
return nil
}
switch c.Args().Get(0) {
case "max_parallel":
parallel, err := strconv.Atoi(c.Args().Get(1))
if err != nil {
return cli.NewExitError(fmt.Errorf("max_parallel 设置值不合法, 错误: %s", err), 1)
}
pcsconfig.Config.MaxParallel = parallel
err = pcsconfig.Config.Save()
if err != nil {
fmt.Println("设置失败, 错误:", err)
return nil
}
fmt.Printf("设置成功, %s -> %v\n", c.Args().Get(0), c.Args().Get(1))
default:
fmt.Printf("未知设定值: %s\n\n", c.Args().Get(0))
cli.ShowCommandHelp(c, "set")
}
return nil
},
},
{
Name: "quit",
Aliases: []string{"exit"},
Usage: "退出程序",
Action: func(c *cli.Context) error {
return cli.NewExitError("", 0)
},
Hidden: true,
HideHelp: true,
},
}
sort.Sort(cli.FlagsByName(app.Flags))
sort.Sort(cli.CommandsByName(app.Commands))
app.Run(os.Args)
}
func newLiner() *liner.State {
line := liner.NewLiner()
line.SetCtrlCAborts(true)
if f, err := os.Open(historyFile); err == nil {
line.ReadHistory(f)
f.Close()
}
return line
}
func closeLiner(line *liner.State) {
if f, err := os.Create(historyFile); err != nil {
log.Print("Error writing history file: ", err)
} else {
line.WriteHistory(f)
f.Close()
}
line.Close()
}
|
[
5
] |
package ui
import "github.com/gdamore/tcell/v2"
type Popover struct {
x, y, width, height int
content Drawable
}
func (p *Popover) Draw(ctx *Context) {
var subcontext *Context
// trim desired width to fit
width := p.width
if p.x+p.width > ctx.Width() {
width = ctx.Width() - p.x
}
if p.y+p.height+1 < ctx.Height() {
// draw below
subcontext = ctx.Subcontext(p.x, p.y+1, width, p.height)
} else if p.y-p.height >= 0 {
// draw above
subcontext = ctx.Subcontext(p.x, p.y-p.height, width, p.height)
} else {
// can't fit entirely above or below, so find the largest available
// vertical space and shrink to fit
if p.y > ctx.Height()-p.y {
// there is more space above than below
height := p.y
subcontext = ctx.Subcontext(p.x, 0, width, height)
} else {
// there is more space below than above
height := ctx.Height() - p.y
subcontext = ctx.Subcontext(p.x, p.y+1, width, height-1)
}
}
p.content.Draw(subcontext)
}
func (p *Popover) Event(e tcell.Event) bool {
if di, ok := p.content.(DrawableInteractive); ok {
return di.Event(e)
}
return false
}
func (p *Popover) Focus(f bool) {
if di, ok := p.content.(DrawableInteractive); ok {
di.Focus(f)
}
}
func (p *Popover) Invalidate() {
p.content.Invalidate()
}
func (p *Popover) OnInvalidate(f func(Drawable)) {
p.content.OnInvalidate(func(_ Drawable) {
f(p)
})
}
|
[
5
] |
package types
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
host "github.com/cosmos/cosmos-sdk/x/ibc/24-host"
"github.com/golang/protobuf/proto"
"github.com/FreeFlixMedia/modules/nfts"
)
type NFTInput struct {
PrimaryNFTID string `json:"primary_nft_id"`
Recipient string `json:"recipient"`
AssetID string `json:"asset_id"`
LicensingFee sdk.Coin `json:"licensing_fee"`
RevenueShare sdk.Dec `json:"revenue_share"`
TwitterHandle string `json:"twitter_handle"`
}
type MsgXNFTTransfer struct {
SourcePort string `json:"source_port"`
SourceChannel string `json:"source_channel"`
DestHeight uint64 `json:"dest_height"`
Sender sdk.AccAddress `json:"sender"`
NFTInput
}
func NewMsgXNFTTransfer(sourcePort, sourceChannel string, height uint64, sender sdk.AccAddress,
nftInput NFTInput) MsgXNFTTransfer {
return MsgXNFTTransfer{
SourcePort: sourcePort,
SourceChannel: sourceChannel,
DestHeight: height,
Sender: sender,
NFTInput: nftInput,
}
}
var _ sdk.Msg = MsgXNFTTransfer{}
func (m *MsgXNFTTransfer) Reset() {
*m = MsgXNFTTransfer{}
}
func (m *MsgXNFTTransfer) String() string {
return proto.CompactTextString(m)
}
func (m MsgXNFTTransfer) ProtoMessage() {}
func (m MsgXNFTTransfer) Route() string {
return RouterKey
}
func (m MsgXNFTTransfer) Type() string {
return "msg_xnft_transfer"
}
func (m MsgXNFTTransfer) ValidateBasic() error {
if err := host.PortIdentifierValidator(m.SourcePort); err != nil {
return sdkerrors.Wrap(err, "invalid source port ID")
}
if err := host.ChannelIdentifierValidator(m.SourceChannel); err != nil {
return sdkerrors.Wrap(err, "invalid source channel ID")
}
if nfts.GetContextOfCurrentChain() == nfts.CoCoContext {
if m.NFTInput.AssetID == "" {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "asset id should not be empty")
} else if m.NFTInput.RevenueShare.IsZero() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "revenue share is not allowed to be empty")
} else if m.NFTInput.TwitterHandle == "" {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "handle name should not be empty")
} else if !m.NFTInput.LicensingFee.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "licensing fee is invalid")
}
}
if nfts.GetContextOfCurrentChain() == nfts.FreeFlixContext {
if len(m.PrimaryNFTID) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "primary nft id is empty")
}
}
if m.Sender.Empty() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "invalid sender address")
} else if m.NFTInput.Recipient == "" {
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "Recipient should not be nil")
}
return nil
}
func (m MsgXNFTTransfer) GetSignBytes() []byte {
return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(m))
}
func (m MsgXNFTTransfer) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{m.Sender}
}
|
[
5
] |
// Copyright 2021 gorse Project 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 base
import (
"bufio"
"fmt"
"strings"
)
// ValidateId validates user/item id. Id cannot be empty and contain [/,].
func ValidateId(text string) error {
text = strings.TrimSpace(text)
if text == "" {
return fmt.Errorf("id cannot be empty")
} else if strings.Contains(text, "/") {
return fmt.Errorf("id cannot contain `/`")
}
return nil
}
// ValidateLabel validates label. Label cannot be empty and contain [/,|].
func ValidateLabel(text string) error {
text = strings.TrimSpace(text)
if text == "" {
return fmt.Errorf("label cannot be empty")
} else if strings.Contains(text, "/") {
return fmt.Errorf("label cannot contain `/`")
} else if strings.Contains(text, "|") {
return fmt.Errorf("label cannot contain `|`")
}
return nil
}
// Escape text for csv.
func Escape(text string) string {
// check if need escape
if !strings.Contains(text, ",") &&
!strings.Contains(text, "\"") &&
!strings.Contains(text, "\n") &&
!strings.Contains(text, "\r") {
return text
}
// start to encode
builder := strings.Builder{}
builder.WriteRune('"')
for _, c := range text {
if c == '"' {
builder.WriteString("\"\"")
} else {
builder.WriteRune(c)
}
}
builder.WriteRune('"')
return builder.String()
}
// ReadLines parse fields of each line for csv file.
func ReadLines(sc *bufio.Scanner, sep string, handler func(int, []string) bool) error {
lineCount := 0 // line number of current position
fields := make([]string, 0) // fields for current line
builder := strings.Builder{} // string builder for current field
quoted := false // whether current position in quote
for sc.Scan() {
// read line
lineStr := sc.Text()
line := []rune(lineStr)
// start of line
if quoted {
builder.WriteString("\r\n")
}
// parse line
for i := 0; i < len(line); i++ {
if string(line[i]) == sep && !quoted {
// end of field
fields = append(fields, builder.String())
builder.Reset()
} else if line[i] == '"' {
if quoted {
if i+1 >= len(line) || line[i+1] != '"' {
// end of quoted
quoted = false
} else {
i++
builder.WriteRune('"')
}
} else {
// start of quoted
quoted = true
}
} else {
builder.WriteRune(line[i])
}
}
// end of line
if !quoted {
fields = append(fields, builder.String())
builder.Reset()
if !handler(lineCount, fields) {
return nil
}
fields = []string{}
}
// increase line count
lineCount++
}
return sc.Err()
}
|
[
5
] |
package main
import "fmt"
func main() {
// дано: граф G с вершинами V от 0 до 10
V := []int{0,1,2,3,4,5,6,7,8,9,10}
// дано: список рёбер E графа G:
E := [][2]int{
{0, 1},
{0, 3},
{0, 4},
{1, 2},
{1, 3},
{2, 3},
{2, 9},
{3, 4},
{3, 5},
{4, 6},
{5, 7},
{6, 10},
{7, 8},
{7, 4},
{8, 10},
{9, 5},
{9, 7},
{9, 8},
{10, 4},
}
// найти кратчайший путь между двумя произвольными вершинами графа G
for _,v := range V{
for i,x := range depthFirstSearch(V,E, v){
fmt.Printf("%d-%d: %v\n",v, i, x)
}
fmt.Println()
}
}
// depthFirstSearch - список истинных расстояний кратчайшего пути до вершины s
func depthFirstSearch(V []int, E [][2]int, s int) [][]int {
type vertex struct {
adjacency []int
passed bool
path []int
}
// пометить s как разведанную вершину, все остальные как неразведанные
// дистанция от s до v: О если s == v, иначе +бесконечность
vs := make(map[int]*vertex)
for _,v := range V{
var x vertex
for _, e := range E {
if e[0] == v {
x.adjacency = append(x.adjacency, e[1])
}
}
vs[v] = &x
}
vs[s].passed = true
// Q - стек, инициализированный вершиной s
Q := []int{s}
for len(Q) > 0 {
// удалить вершину из конца Q, назвать ее v
v := Q[len(Q)-1]
Q = Q[:len(Q)-1]
// для каждого ребра (v, w) в списке смежности вершины v
for _,w := range vs[v].adjacency {
wi := vs[w]
if wi.passed {
continue
}
wi.passed = true
wi.path = append(append(wi.path, vs[v].path...), w)
Q = append(Q, w)
}
}
xs := make([][]int, len(V))
for i,v := range V {
xs[i] = vs[v].path
}
return xs
}
|
[
2
] |
package main
import (
"flag"
"log"
"os"
"github.com/s1as3r/gospotdl/search"
)
const (
clientId = "b9640826ab8949e4b34a4eeee5b26ce6"
clientSecret = "c25b0399324d49a08d8210138cbf9e27"
)
func main() {
client, err := search.GetSpotifyClient(clientId, clientSecret)
if err != nil {
log.Fatalf("Error getting spotify client: %s", err)
}
var dir string
var max int
flag.StringVar(&dir, "output", ".", "output directory")
flag.StringVar(&dir, "o", ".", "output directory")
flag.IntVar(&max, "max", 4, "max concurrent downloads")
flag.IntVar(&max, "m", 4, "max concurrent downloads")
flag.Parse()
if err := os.Chdir(dir); err != nil {
log.Fatalf("Error changing directory: %s", err)
}
for _, arg := range flag.Args() {
handleArg(client, arg, max)
}
}
|
[
1
] |
package bot
import (
"strings"
"github.com/bwmarrin/discordgo"
"go.uber.org/zap"
)
// slashCommandHandlers handles and routes all incoming interaction based commands based on the interaction type
func (d *DiscordAPI) slashCommandHandlers(s *discordgo.Session, i *discordgo.InteractionCreate) {
Logger.With(zap.Any("interaction", i.Interaction)).Debug("slash command interaction")
switch i.Type {
case discordgo.InteractionApplicationCommand:
d.slashApplicationCommanInteractionHandler(s, i)
case discordgo.InteractionMessageComponent:
d.slashMessageComponentHandler(s, i)
}
}
// slashMessageComponentHandler handles and routes interactions with components, such as button clicks
func (d *DiscordAPI) slashMessageComponentHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
customID := i.Interaction.MessageComponentData().CustomID
switch customID[:strings.Index(customID, ":")] {
case "stream":
d.slashStreamComponentHandler(s, i)
}
}
// slashApplicationCommanInteractionHandler handles and routes initial slash command messages
func (d *DiscordAPI) slashApplicationCommanInteractionHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
switch i.Interaction.ApplicationCommandData().Name {
case "stream":
d.slashStreamHandler(s, i)
}
}
|
[
7
] |
package main
import (
"auth-guardian/config"
"auth-guardian/logging"
"auth-guardian/mocked"
"auth-guardian/server"
"context"
"log"
)
func main() {
// Load config
err := config.Load()
if err != nil {
log.Panic(&map[string]string{
"file": "file.go",
"Function": "getConfigFromFile",
"error": "Can't load existing config file",
"details": err.Error(),
})
}
// Run test service if test mode enabled
if config.MockTestService {
logging.Debug(&map[string]string{
"file": "main.go",
"Function": "main",
"event": "Run mocked test-service",
"url": "http://localhost:3001",
})
// Run test service
testServiceServer := mocked.RunMockTestService()
defer testServiceServer.Shutdown(context.TODO())
}
// Run mock IDP if enabled
if config.MockOAuth {
logging.Debug(&map[string]string{
"file": "main.go",
"Function": "main",
"event": "Run mocked OAuth IDP",
})
// Run OAuth IDP
oAuthServer := mocked.RunMockOAuthIDP()
defer oAuthServer.Shutdown(context.TODO())
} else if config.MockLDAP {
logging.Debug(&map[string]string{
"file": "main.go",
"Function": "main",
"event": "Run mocked LDAP IDP",
})
// Run LDAP IDP
ldapListener := mocked.RunMockLDAPIDP()
defer (*ldapListener).Close()
} else if config.MockSAML {
logging.Debug(&map[string]string{
"file": "main.go",
"Function": "main",
"event": "Run mocked SAML IDP",
})
// Run SAML IDP
samlServer := mocked.RunMockSAMLIDP()
defer samlServer.Shutdown(context.TODO())
}
server.Run(nil)
}
|
[
5
] |
package user
import (
"net/url"
"net/http"
)
type Jar struct {
cookies []*http.Cookie
}
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
jar.cookies = cookies
}
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
return jar.cookies
}
func SetJarCook(c *http.Client) {
urls,_ := url.Parse(`http://ttservice.toplogis.com/`)
cook := make([]*http.Cookie,0)
cook = append(cook, getCookies(OneConfig.SessionId))
c.Jar.SetCookies(urls,cook)
}
func getCookies(SessionId string) *http.Cookie {
return &http.Cookie{
Name: "JSESSIONID",
Value: SessionId,
Path: "/",
HttpOnly: false,
MaxAge:9999999999,
}
}
func getClient() *http.Client {
return &http.Client{
Jar:new(Jar),
Timeout:9999999999,
}
}
func setHeader(req *http.Request) {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36")
req.Header.Set("Upgrade-Insecure-Requests","1")
req.Header.Set("Cache-Control","0")
req.Header.Set("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
}
|
[
2
] |
/**
create by yy on 2019-08-31
*/
package models
import (
"errors"
"fmt"
"gin_template/app/enum"
"gorm.io/gorm"
"reflect"
)
type BaseModel interface {
TableName() string // 获取数据表名
getDB() *gorm.DB // 获取db实例
getDBWithNoDeleted() *gorm.DB // 获取未被软删除的db实例
CreateTable() error // 创建表
HasTable() bool // 表是否存在
}
type Model struct {
CreatedAt int64 `json:"created"`
UpdatedAt int64 `json:"updated"`
DeletedAt int64 `json:"deleted"`
}
// 统一是软删除
// 获取未删除db 实例
func getTableWithNoDeleted(gdb *gorm.DB, tableName string) *gorm.DB {
db := gdb.Table(tableName)
if db != nil {
db = db.Where("deleted = 0")
}
return db
}
// 获取所有数据(不论是否被删除) db实例
func getTable(gdb *gorm.DB, tableName string) *gorm.DB {
return gdb.Table(tableName)
}
func getOrderByStr(orderField, defaultOrder string, orderType int64) (orderBy string) {
if orderField != "" {
orderBy = orderField
} else {
orderBy = defaultOrder
}
if orderType > 0 {
orderBy = orderBy + " desc"
} else {
orderBy = orderBy + " asc"
}
return
}
func getOffset(page, pageSize int) int {
offset := (page - 1) * pageSize
if offset <= 0 {
offset = 0
}
return offset
}
type separateHandle func(*gorm.DB, interface{}) *gorm.DB
// auto struct gorm.DB
// 1 -> and
// 2 -> or
// 3 -> separate handle 单独处理
// 4 -> like 操作
// separateHandle 单独处理 的字符串数组
func queryAutoWhere(db *gorm.DB, search interface{}, separate ...map[string]separateHandle) (*gorm.DB, error) {
var (
err error
data interface{}
)
vt := reflect.TypeOf(search)
val := reflect.ValueOf(search)
if kd := vt.Kind(); kd != reflect.Struct {
if kd := vt.Elem().Kind(); kd != reflect.Struct {
return db, errors.New("the param is not a struct, please make sure")
} else {
vt = vt.Elem()
val = val.Elem()
}
}
fieldNum := val.NumField()
for i := 0; i < fieldNum; i++ {
handleType := vt.Field(i).Tag.Get(enum.FieldIsHandle)
if handleType == "" {
continue
}
switch val.Field(i).Type().String() {
case "string":
tmp := val.Field(i).String()
if tmp == "" {
continue
}
data = tmp
case "*int64", "*int32", "*int16", "*int8", "*int":
if val.Field(i).IsNil() {
continue
}
data = val.Field(i).Elem().Int()
case "*uint64", "*uint32", "*uint16", "*uint8", "*uint":
if val.Field(i).IsNil() {
continue
}
data = val.Field(i).Elem().Uint()
case "int64", "int32", "int16", "int8", "int":
data = val.Field(i).Int()
case "uint64", "uint32", "uint16", "uint8", "uint":
data = val.Field(i).Uint()
}
switch handleType {
case enum.AutoWhere:
db = db.Where(vt.Field(i).Tag.Get(enum.FieldHandle), data)
case enum.AutoOr:
db = db.Or(vt.Field(i).Tag.Get(enum.FieldHandle), data)
case enum.AutoCustomHandle:
// 根据条件 判断大于和小于
if len(separate) > 0 {
db = separate[0][vt.Field(i).Tag.Get("json")](db, data)
}
case enum.AutoLike:
db = db.Where(vt.Field(i).Tag.Get(enum.FieldHandle), "%"+fmt.Sprintf("%v", data)+"%")
}
}
return db, err
}
// 获取可以赋空值的字段 map,用于完善 struct2Map
func NewExcept(list ...string) map[string]int64 {
m := make(map[string]int64)
for _, v := range list {
m[v] = 1
}
return m
}
type Struct2MapValue struct {
Value reflect.Value
Type reflect.Type
}
// 字段tag 加上 s2s:"-" 则会被忽略
// 成员属性必须带有 json tag标签才能获取
// 例:
// type structToMap struct {
// Data int64 `json:"data" struct2map:"-"`
// }
// except: 可以赋空值的字段, 通过 NewExcept 获取(参数是定义的成员名,不是tag名,需要注意)
// 样例:result, err := struct2Map(data, NewExcept("DataString"), nil)
// 从结构体转为 map (适用于 数据库更新数据)
func struct2Map(v interface{}, except map[string]int64, maps map[string]interface{}, originValue ...Struct2MapValue) (data map[string]interface{}, err error) {
var (
vt reflect.Type
val reflect.Value
)
if except == nil {
except = make(map[string]int64)
}
if maps != nil {
data = maps
} else {
data = make(map[string]interface{})
}
if len(originValue) > 0 {
vt = originValue[0].Type
val = originValue[0].Value
} else {
vt = reflect.TypeOf(v)
val = reflect.ValueOf(v)
}
if kd := vt.Kind(); kd != reflect.Struct {
if kd := vt.Elem().Kind(); kd != reflect.Struct {
return nil, errors.New("the param is not a struct, please make sure")
} else {
vt = vt.Elem()
val = val.Elem()
if vt.Kind() != reflect.Struct {
return nil, errors.New("the param is not a struct, please make sure")
}
}
}
fieldNum := val.NumField()
for i := 0; i < fieldNum; i++ {
fieldIgnore := vt.Field(i).Tag.Get("s2s")
if fieldIgnore == "-" {
continue
}
fieldName := vt.Field(i).Tag.Get("json")
if fieldName == "" {
data, _ = struct2Map(val.Field(i), except, data, Struct2MapValue{
Value: val.Field(i),
Type: vt.Field(i).Type,
})
continue
}
_, ok := except[vt.Field(i).Name]
switch val.Field(i).Type().String() {
case "string":
if val.Field(i).String() != "" || ok {
data[fieldName] = val.Field(i).String()
}
case "*string":
if val.Field(i).IsNil() {
continue
}
data[fieldName] = val.Field(i).Elem().String()
case "*int64", "*int32", "*int16", "*int8", "*int":
if val.Field(i).IsNil() {
continue
}
data[fieldName] = val.Field(i).Elem().Int()
case "*uint64", "*uint32", "*uint16", "*uint8", "*uint":
if val.Field(i).IsNil() {
continue
}
data[fieldName] = val.Field(i).Elem().Uint()
case "uint64", "uint32", "uint16", "uint8", "uint":
if val.Field(i).Uint() != 0 || ok {
data[fieldName] = val.Field(i).Uint()
}
case "int64", "int32", "int16", "int8", "int":
if val.Field(i).Int() != 0 || ok {
data[fieldName] = val.Field(i).Int()
}
case "float64", "float32":
if val.Field(i).Float() != 0 || ok {
data[fieldName] = val.Field(i).Float()
}
case "*float64", "*float32":
if val.Field(i).IsNil() {
continue
}
data[fieldName] = val.Field(i).Elem().Float()
default:
data, _ = struct2Map(val.Field(i), except, data, Struct2MapValue{
Value: val.Field(i),
Type: vt.Field(i).Type,
})
}
}
return
}
|
[
0
] |
package kiwi
import (
"errors"
"fmt"
"io/ioutil"
"os"
_ "path/filepath"
"reflect"
"strconv"
"strings"
"unsafe"
)
// Platform specific fields to be embedded into
// the Process struct.
type ProcPlatAttribs struct {
}
// GetProcessByPID returns the process with the given PID.
func GetProcessByPID(PID int) (Process, error) {
// Try to open the folder to see if it exists and if we have access to it.
f, err := os.Open(fmt.Sprintf("/proc/%d", PID))
defer f.Close()
if err != nil {
return Process{}, errors.New(fmt.Sprintf("Error opening /proc/%d", PID))
}
return Process{PID: uint64(PID)}, nil
}
// GetProcessByFileName returns the process with the given file name.
// If multiple processes have the same filename, the first process
// enumerated by this function is returned.
func GetProcessByFileName(fileName string) (Process, error) {
// Open the /proc *nix directory.
procDir, err := os.Open("/proc")
defer procDir.Close()
if err != nil {
fmt.Println(err)
return Process{}, errors.New("Error on opening /proc")
}
// Read in the directory names. Processes are listed
// as folders within this directory, named by their PID.
dirNames, err := procDir.Readdirnames(0)
if err != nil {
fmt.Println(err)
return Process{}, errors.New("Error on reading dirs from /proc")
}
// Enumerate all directories here.
for _, dirString := range dirNames {
// Parse the directory name as a uint.
pid, err := strconv.ParseUint(dirString, 0, 64)
// If it is not a numeric directory name, skip it.
if v, ok := err.(*strconv.NumError); ok && v.Err == strconv.ErrSyntax {
continue
} else if err != nil {
fmt.Println(err)
return Process{}, errors.New("Error on enumerating dirs from /proc")
}
// TODO: Change this to something better, it is very hacky right now.
// Read the target program's stats file.
tmpFileBytes, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
if err != nil {
fmt.Println(err)
return Process{}, errors.New("Error on enumerating dirs from " + fmt.Sprintf("/proc/%d/stat", pid))
}
// HACK!
// Stat file [1] has the file name surrounded by ()
curProcFileName := strings.Trim(strings.Split(string(tmpFileBytes), " ")[1], "()")
// Check if this is the process we are looking for.
if curProcFileName == fileName {
return Process{PID: pid}, nil
}
}
return Process{}, errors.New("Couldn't find a process with the given file name.")
}
// The platform specific read function.
func (p *Process) read(addr uintptr, ptr interface{}) error {
// Reflection magic!
v := reflect.ValueOf(ptr)
dataAddr := getDataAddr(v)
dataSize := getDataSize(v)
// Open the file mapped process memory.
mem, err := os.Open(fmt.Sprintf("/proc/%d/mem", p.PID))
defer mem.Close()
if err != nil {
return errors.New(fmt.Sprintf("Error opening /proc/%d/mem. Are you root?", p.PID))
}
// Create a buffer and read data into it.
dataBuf := make([]byte, dataSize)
n, err := mem.ReadAt(dataBuf, int64(addr))
if n != int(dataSize) {
return errors.New(fmt.Sprintf("Tried to read %d bytes, actually read %d bytes\n", dataSize, n))
} else if err != nil {
return err
}
// Unsafely cast to []byte to copy data into.
buf := (*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: dataAddr,
Len: int(dataSize),
Cap: int(dataSize),
}))
copy(*buf, dataBuf)
return nil
}
// The platform specific write function.
func (p *Process) write(addr uintptr, ptr interface{}) error {
// Reflection magic!
v := reflect.ValueOf(ptr)
dataAddr := getDataAddr(v)
dataSize := getDataSize(v)
// Open the file mapped process memory.
mem, err := os.OpenFile(fmt.Sprintf("/proc/%d/mem", p.PID), os.O_WRONLY, 0666)
defer mem.Close()
if err != nil {
return errors.New(fmt.Sprintf("Error opening /proc/%d/mem. Are you root?", p.PID))
}
// Unsafe cast to []byte to copy data from.
buf := (*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: dataAddr,
Len: int(dataSize),
Cap: int(dataSize),
}))
// Write the data from buf into memory.
n, err := mem.WriteAt(*buf, int64(addr))
if n != int(dataSize) {
return errors.New((fmt.Sprintf("Tried to write %d bytes, actually wrote %d bytes\n", dataSize, n)))
} else if err != nil {
return err
}
return nil
}
|
[
2
] |
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"sort"
"strings"
)
type Data struct {
File string
Hash string
StorePath string
Prebuilt bool
}
type DataSlice []Data
var gdata DataSlice = make([]Data, 0)
func (d DataSlice) Len() int {
return len(d)
}
func (d DataSlice) Less(i, j int) bool {
return d[i].StorePath < d[j].StorePath
}
func (d DataSlice) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
func (d DataSlice) Sort() {
sort.Sort(d)
}
func load(name string) {
f, e := os.Open(name)
if e != nil {
log.Fatal("Couldn't open ", name, ": ", e)
}
defer f.Close()
fmt.Println("Loading ", name)
bf := bufio.NewReader(f)
for {
var d Data
d.File = name
var der string
line, e := bf.ReadString('\n')
if e == io.EOF {
break
}
line = line[:len(line)-1]
if len(line) > 1 && line[len(line)-1] == '\r' {
line = line[:len(line)-2]
}
line = strings.Replace(line, "|", " ", -1)
n, e := fmt.Sscanf(line, "%s %s %s", &d.StorePath, &d.Hash, &der)
if e == nil {
d.Prebuilt = true
} else if e == io.EOF && n == 2 {
d.Prebuilt = false
} else {
log.Fatal("Failed scanf. n=", n, ", err = ", e)
}
gdata = append(gdata, d)
}
}
func CheckHashes() {
i := 0
for i < len(gdata) {
path := gdata[i].StorePath
hash := gdata[i].Hash
j := i + 1
for ; j < len(gdata) && gdata[j].StorePath == path; j += 1 {
if gdata[j].Hash != hash {
fmt.Println(path, "between", gdata[i].File, "and", gdata[j].File)
}
}
i = j
}
}
func main() {
if len(os.Args) <= 1 {
fmt.Fprintln(os.Stderr, "Usage: diffhash [file1] [file2] ...")
}
for _, a := range os.Args[1:] {
load(a)
}
fmt.Println("Loaded: ", len(gdata))
gdata.Sort()
CheckHashes()
}
|
[
5
] |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
func homeLink(W http.ResponseWriter, r *http.Request) {
fmt.Fprintf(W, "Welcome Bank!")
}
type account struct {
ID string `json:"ID"`
Saldo float32 `json:"Saldo"`
Data time.Time `json:"Data"`
Status bool `json:"Status"`
}
type allaccounts []account
var accounts = allaccounts{
{
ID: "1",
Saldo: 123.45,
Data: time.Now(),
Status: true,
},
}
func createaccount(response http.ResponseWriter, request *http.Request) {
response.Header().Set("content-type", "application/json")
var newaccount account
reqBody, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Fprintf(response, "Informe dados da conta para cadastro.")
}
json.Unmarshal(reqBody, &newaccount)
newaccount.Data = time.Now()
accounts = append(accounts, newaccount)
response.WriteHeader(http.StatusCreated)
json.NewEncoder(response).Encode(newaccount)
}
func getaccount(response http.ResponseWriter, request *http.Request) {
accountID := mux.Vars(request)["id"]
for _, singleaccount := range accounts {
if singleaccount.ID == accountID {
json.NewEncoder(response).Encode(singleaccount)
}
}
}
func getAllaccounts(response http.ResponseWriter, request *http.Request) {
response.Header().Set("content-type", "application/json")
json.NewEncoder(response).Encode(accounts)
}
func creditaccount(response http.ResponseWriter, request *http.Request) {
accountID := mux.Vars(request)["id"]
var credit account
reqBody, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Fprintf(response, "Informe os dados da conta.")
}
json.Unmarshal(reqBody, &credit)
for i, singleaccount := range accounts {
if singleaccount.ID == accountID {
if singleaccount.Status == true {
singleaccount.Saldo += credit.Saldo
accounts = append(accounts[:i], singleaccount)
json.NewEncoder(response).Encode(singleaccount)
response.WriteHeader(http.StatusNoContent)
}
}
}
}
func debitaccount(response http.ResponseWriter, request *http.Request) {
accountID := mux.Vars(request)["id"]
var credit account
reqBody, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Fprintf(response, "Informe os dados da conta.")
}
json.Unmarshal(reqBody, &credit)
for i, singleaccount := range accounts {
if singleaccount.ID == accountID {
singleaccount.Saldo -= credit.Saldo
accounts = append(accounts[:i], singleaccount)
response.WriteHeader(http.StatusNoContent)
json.NewEncoder(response).Encode(singleaccount)
}
}
}
func blockaccount(response http.ResponseWriter, request *http.Request) {
accountID := mux.Vars(request)["id"]
var block account
reqBody, err := ioutil.ReadAll(request.Body)
if err != nil {
fmt.Fprintf(response, "Informe os dados da conta.")
}
json.Unmarshal(reqBody, &block)
for i, singleaccount := range accounts {
if singleaccount.ID == accountID {
singleaccount.Status = block.Status
accounts = append(accounts[:i], singleaccount)
response.WriteHeader(http.StatusNoContent)
json.NewEncoder(response).Encode(singleaccount)
}
}
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", homeLink)
router.HandleFunc("/api/v1/account", createaccount).Methods("POST")
router.HandleFunc("/api/v1/account/{id}", getaccount).Methods("GET")
router.HandleFunc("/api/v1/account/all", getAllaccounts).Methods("GET")
router.HandleFunc("/api/v1/account/{id}/block", blockaccount).Methods("PATCH")
router.HandleFunc("/api/v1/account/{id}/credit", creditaccount).Methods("PATCH")
router.HandleFunc("/api/v1/account/{id}/debit", debitaccount).Methods("PATCH")
fmt.Printf("Servidor disponivel!")
log.Fatal(http.ListenAndServe(":8080", router))
}
|
[
2
] |
package server
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
)
func downloadFileToPath(downloadURL, path string) error {
path, err := filepath.Abs(path)
if err != nil {
return err
}
out, err := os.Create(path)
if err != nil {
return err
}
defer out.Close()
src, err := httpGet(downloadURL)
if err != nil {
return err
}
defer src.Close()
_, err = io.Copy(out, src)
return err
}
func httpGet(addr string) (io.ReadCloser, error) {
parsed, err := url.Parse(addr)
if err != nil {
return nil, err
}
resp, err := http.Get(parsed.String())
if err != nil {
return nil, err
}
return resp.Body, nil
}
func httpGetAndRead(addr string) ([]byte, error) {
bodySrc, err := httpGet(addr)
if err != nil {
return nil, err
}
defer bodySrc.Close()
return ioutil.ReadAll(bodySrc)
}
func httpGetAndParseJSON(addr string, target interface{}) error {
body, err := httpGetAndRead(addr)
if err != nil {
return err
}
return json.Unmarshal(body, target)
}
type javaVersion struct {
major int
minor int
patch int
}
func (v javaVersion) String() string {
return fmt.Sprintf("%d.%d.%d", v.major, v.minor, v.patch)
}
func getSystemJavaVersion() javaVersion {
version := javaVersion{}
// if java isn't installed, w.e, something else'll surely break anyway
path, err := exec.LookPath("java")
if err != nil {
return version
}
cmd := exec.Command(path, "-version")
out, err := cmd.CombinedOutput()
if err != nil {
return version
}
// this part split off for sake of unit testing
return parseJavaVersion(out)
}
func parseJavaVersion(in []byte) javaVersion {
major, minor, patch := 0, 0, 0
// this is tailor written expecting openjdk -- I ain't about to license
// Oracle stuff to find a version string format :\
re := regexp.MustCompile(`(openjdk|java) version "(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(_\d+)?"`)
if re.Match(in) {
matches := re.FindStringSubmatch(string(in))
if len(matches) != re.NumSubexp()+1 {
return javaVersion{}
}
major, _ = strconv.Atoi(matches[re.SubexpIndex("major")])
minor, _ = strconv.Atoi(matches[re.SubexpIndex("minor")])
patch, _ = strconv.Atoi(matches[re.SubexpIndex("patch")])
} else {
// alternative output format I've seen in 1.12+ opendjdk alpine builds
re = regexp.MustCompile(`(openjdk|java) version "(?P<minor>\d+)-ea"`)
if !re.Match(in) {
return javaVersion{}
}
matches := re.FindStringSubmatch(string(in))
if len(matches) != re.NumSubexp()+1 {
return javaVersion{}
}
major = 1
minor, _ = strconv.Atoi(matches[re.SubexpIndex("minor")])
patch = 0
}
return javaVersion{major, minor, patch}
}
func javaArgs(jarPath string, ro RuntimeOpts, v javaVersion) []string {
args := make([]string, 0)
args = append(args, fmt.Sprintf("-Xms%s", ro.InitialMemory))
args = append(args, fmt.Sprintf("-Xmx%s", ro.MaxMemory))
// aikar's flags
// https://aikar.co/2018/07/02/tuning-the-jvm-g1gc-garbage-collector-flags-for-minecraft/
args = append(args, "-XX:+UseG1GC")
args = append(args, "-XX:+ParallelRefProcEnabled")
args = append(args, "-XX:MaxGCPauseMillis=200")
args = append(args, "-XX:+UnlockExperimentalVMOptions")
args = append(args, "-XX:+DisableExplicitGC")
args = append(args, "-XX:+AlwaysPreTouch")
if ro.MaxMemory > 12*Gigabyte {
args = append(args, "-XX:G1NewSizePercent=40")
args = append(args, "-XX:G1MaxNewSizePercent=50")
args = append(args, "-XX:G1HeapRegionSize=16M")
args = append(args, "-XX:G1ReservePercent=15")
args = append(args, "-XX:InitiatingHeapOccupancyPercent=20")
} else {
args = append(args, "-XX:G1NewSizePercent=30")
args = append(args, "-XX:G1MaxNewSizePercent=40")
args = append(args, "-XX:G1HeapRegionSize=8M")
args = append(args, "-XX:G1ReservePercent=20")
args = append(args, "-XX:InitiatingHeapOccupancyPercent=15")
}
args = append(args, "-XX:G1HeapWastePercent=5")
args = append(args, "-XX:G1MixedGCCountTarget=4")
args = append(args, "-XX:G1MixedGCLiveThresholdPercent=90")
args = append(args, "-XX:G1RSetUpdatingPauseTimePercent=5")
args = append(args, "-XX:SurvivorRatio=32")
args = append(args, "-XX:+PerfDisableSharedMem")
args = append(args, "-XX:MaxTenuringThreshold=1")
args = append(args, "-Dusing.aikars.flags=https://mcflags.emc.gs")
args = append(args, "-Daikars.new.flags=true")
if ro.DebugGC {
if v.major == 1 && v.minor >= 8 && v.minor <= 10 { // java 1.8-1.10
args = append(args, "-Xloggc:gc.log")
args = append(args, "-verbose:gc")
args = append(args, "-XX:+PrintGCDetails")
args = append(args, "-XX:+PrintGCDateStamps")
args = append(args, "-XX:+PrintGCTimeStamps")
args = append(args, "-XX:+UseGCLogFileRotation")
args = append(args, "-XX:NumberOfGCLogFiles=5")
args = append(args, "-XX:GCLogFileSize=1M")
} else if v.major == 1 && v.minor >= 11 || v.major > 1 { // java 1.11+
args = append(args, "-Xlog:gc*:logs/gc.log:time,uptime:filecount=5,filesize=1M")
} else {
// I ain't got no clue, check aikar's blog
}
}
args = append(args, "-jar", jarPath)
args = append(args, "nogui")
return args
}
func runJavaServer(binaryPath string, runOpts RuntimeOpts) error {
if _, err := os.Stat(binaryPath); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("server not installed, refusing to run")
}
return err
}
path, err := exec.LookPath("java")
if err != nil {
return err
}
version := getSystemJavaVersion()
args := javaArgs(binaryPath, runOpts, version)
cmd := exec.Command(path, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Pgid: 0,
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
in, err := cmd.StdinPipe()
if err != nil {
return err
}
Log.Printf("Starting '%s %s'\n", path, strings.Join(args, " "))
if err := cmd.Start(); err != nil {
return err
}
go func() {
io.Copy(in, os.Stdin)
}()
cmdErrChan := make(chan error, 1)
go func() {
cmdErrChan <- cmd.Wait()
}()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT)
timeoutChan := make(chan int, 1)
for {
select {
case err := <-cmdErrChan:
return err
case <-sigChan:
if _, err := in.Write([]byte("stop\n")); err != nil {
// ru-roh
}
go time.AfterFunc(6*time.Second, func() { timeoutChan <- 1 })
case <-timeoutChan:
if err := cmd.Process.Kill(); err != nil {
// woah, what a hardy process
}
return nil
}
}
}
|
[
5
] |
package main
import (
"archive/tar"
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/blakesmith/ar"
"github.com/julien-sobczak/deb822"
)
func main() {
// This program expects one or more package files to install.
if len(os.Args) < 2 {
log.Fatalf("Missing package archive(s)")
}
// Read the DPKG database
db, _ := loadDatabase()
// Unpack and configure the archive(s)
for _, archivePath := range os.Args[1:] {
processArchive(db, archivePath)
}
// For simplicity reasons, we don't manage a queue to defer
// the configuration of packages like in the official code.
}
//
// Dpkg Database
//
type Database struct {
// File /var/lib/dpkg/status
Status deb822.Document
// Packages under /var/lib/dpkg/info/
Packages []*PackageInfo
}
type PackageInfo struct {
Paragraph deb822.Paragraph // Extracted section in /var/lib/dpkg/status
// info
Files []string // File <name>.list
Conffiles []string // File <name>.conffiles
MaintainerScripts map[string]string // File <name>.{preinst,prerm,...}
Status string // Current status (as present in `Paragraph`)
StatusDirty bool // True to ask for sync
}
func (p *PackageInfo) Name() string {
// Extract the package name from its section in /var/lib/dpkg/status
return p.Paragraph.Value("Package")
}
func (p *PackageInfo) Version() string {
// Extract the package version from its section in /var/lib/dpkg/status
return p.Paragraph.Value("Version")
}
// isConffile determines if a file must be processed as a conffile.
func (p *PackageInfo) isConffile(path string) bool {
for _, conffile := range p.Conffiles {
if path == conffile {
return true
}
}
return false
}
// InfoPath returns the path of a file under /var/lib/dpkg/info/.
// Ex: "list" => /var/lib/dpkg/info/hello.list
func (p *PackageInfo) InfoPath(filename string) string {
return filepath.Join("/var/lib/dpkg", p.Name()+"."+filename)
}
// We now add a method to change the package status
// and make sure the section in the status file is updated too.
// This method will be used several times at the different steps
// of the installation process.
func (p *PackageInfo) SetStatus(new string) {
p.Status = new
p.StatusDirty = true
// Override in DEB 822 document used to write the status file
old := p.Paragraph.Values["Status"]
parts := strings.Split(old, " ")
newStatus := fmt.Sprintf("%s %s %s", parts[0], parts[1], new)
p.Paragraph.Values["Status"] = newStatus
}
// Now, we are ready to read the database directory to initialize the structs.
func loadDatabase() (*Database, error) {
// Load the status file
f, _ := os.Open("/var/lib/dpkg/status")
parser, _ := deb822.NewParser(f)
status, _ := parser.Parse()
// Read the info directory
var packages []*PackageInfo
for _, statusParagraph := range status.Paragraphs {
statusField := statusParagraph.Value("Status") // install ok installed
statusValues := strings.Split(statusField, " ")
pkg := PackageInfo{
Paragraph: statusParagraph,
MaintainerScripts: make(map[string]string),
Status: statusValues[2],
StatusDirty: false,
}
// Read the configuration files
pkg.Files, _ = ReadLines(pkg.InfoPath("list"))
pkg.Conffiles, _ = ReadLines(pkg.InfoPath("conffiles"))
// Read the maintainer scripts
maintainerScripts := []string{"preinst", "postinst", "prerm", "postrm"}
for _, script := range maintainerScripts {
scriptPath := pkg.InfoPath(script)
if _, err := os.Stat(scriptPath); !os.IsNotExist(err) {
content, err := os.ReadFile(scriptPath)
if err != nil {
return nil, err
}
pkg.MaintainerScripts[script] = string(content)
}
}
packages = append(packages, &pkg)
}
// We have read everything that interest us and are ready
// to populate the Database struct.
return &Database{
Status: status,
Packages: packages,
}, nil
}
// Now we are ready to process an archive to install.
func processArchive(db *Database, archivePath string) error {
// Read the Debian archive file
f, err := os.Open(archivePath)
if err != nil {
return err
}
defer f.Close()
reader := ar.NewReader(f)
// Skip debian-binary
reader.Next()
// control.tar
reader.Next()
var bufControl bytes.Buffer
io.Copy(&bufControl, reader)
pkg, err := parseControl(db, bufControl)
if err != nil {
return err
}
// Add the new package in the database
db.Packages = append(db.Packages, pkg)
db.Sync()
// data.tar
reader.Next()
var bufData bytes.Buffer
io.Copy(&bufData, reader)
fmt.Printf("Preparing to unpack %s ...\n", filepath.Base(archivePath))
if err := pkg.Unpack(bufData); err != nil {
return err
}
if err := pkg.Configure(); err != nil {
return err
}
db.Sync()
return nil
}
// parseControl processes the control.tar archive.
func parseControl(db *Database, buf bytes.Buffer) (*PackageInfo, error) {
// The control.tar archive contains the most important files
// we need to install the package.
// We need to extract metadata from the control file, determine
// if the package contains conffiles and maintainer scripts.
pkg := PackageInfo{
MaintainerScripts: make(map[string]string),
Status: "not-installed",
StatusDirty: true,
}
tr := tar.NewReader(&buf)
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
return nil, err
}
// Read the file content
var buf bytes.Buffer
if _, err := io.Copy(&buf, tr); err != nil {
return nil, err
}
switch filepath.Base(hdr.Name) {
case "control":
parser, _ := deb822.NewParser(strings.NewReader(buf.String()))
document, _ := parser.Parse()
controlParagraph := document.Paragraphs[0]
// Copy control fields and add the Status field in second position
pkg.Paragraph = deb822.Paragraph{
Values: make(map[string]string),
}
// Make sure the field "Package' comes first, then "Status",
// then remaining fields.
pkg.Paragraph.Order = append(
pkg.Paragraph.Order, "Package", "Status")
pkg.Paragraph.Values["Package"] = controlParagraph.Value("Package")
pkg.Paragraph.Values["Status"] = "install ok non-installed"
for _, field := range controlParagraph.Order {
if field == "Package" {
continue
}
pkg.Paragraph.Order = append(pkg.Paragraph.Order, field)
pkg.Paragraph.Values[field] = controlParagraph.Value(field)
}
case "conffiles":
pkg.Conffiles = SplitLines(buf.String())
case "prerm":
fallthrough
case "preinst":
fallthrough
case "postinst":
fallthrough
case "postrm":
pkg.MaintainerScripts[filepath.Base(hdr.Name)] = buf.String()
}
}
return &pkg, nil
}
// Unpack processes the data.tar archive.
func (p *PackageInfo) Unpack(buf bytes.Buffer) error {
// The unpacking process consists in extracting all files
// in data.tar to their final destination, except for conffiles,
// which are copied with a special extension that will be removed
// in the configure step.
if err := p.runMaintainerScript("preinst"); err != nil {
return err
}
fmt.Printf("Unpacking %s (%s) ...\n", p.Name(), p.Version())
tr := tar.NewReader(&buf)
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
return err
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, tr); err != nil {
return err
}
switch hdr.Typeflag {
case tar.TypeReg:
dest := hdr.Name
if strings.HasPrefix(dest, "./") {
// ./usr/bin/hello => /usr/bin/hello
dest = dest[1:]
}
if !strings.HasPrefix(dest, "/") {
// usr/bin/hello => /usr/bin/hello
dest = "/" + dest
}
tmpdest := dest
if p.isConffile(tmpdest) {
// Extract using the extension .dpkg-new
tmpdest += ".dpkg-new"
}
if err := os.MkdirAll(filepath.Dir(tmpdest), 0755); err != nil {
log.Fatalf("Failed to unpack directory %s: %v", tmpdest, err)
}
content := buf.Bytes()
if err := os.WriteFile(tmpdest, content, 0755); err != nil {
log.Fatalf("Failed to unpack file %s: %v", tmpdest, err)
}
p.Files = append(p.Files, dest)
}
}
p.SetStatus("unpacked")
p.Sync()
return nil
}
// Configure processes the conffiles.
func (p *PackageInfo) Configure() error {
// The configure process consists in renaming the conffiles
// unpacked at the previous step.
//
// We ignore some implementation concerns like checking if a conffile
// has been updated using the last known checksum.
fmt.Printf("Setting up %s (%s) ...\n", p.Name(), p.Version())
// Rename conffiles
for _, conffile := range p.Conffiles {
os.Rename(conffile+".dpkg-new", conffile)
}
p.SetStatus("half-configured")
p.Sync()
// Run maintainer script
if err := p.runMaintainerScript("postinst"); err != nil {
return err
}
p.SetStatus("installed")
p.Sync()
return nil
}
func (p *PackageInfo) runMaintainerScript(name string) error {
// The control.tar file can contains scripts to be run at
// specific moments. This function uses the standard Go library
// to run the `sh` command with a maintainer scrpit as an argument.
if _, ok := p.MaintainerScripts[name]; !ok {
// Nothing to run
return nil
}
out, err := exec.Command("/bin/sh", p.InfoPath(name)).Output()
if err != nil {
return err
}
fmt.Print(string(out))
return nil
}
// We have covered the different steps of the installation process.
// We still need to write the code to sync the database.
func (d *Database) Sync() error {
newStatus := deb822.Document{
Paragraphs: []deb822.Paragraph{},
}
// Sync the /var/lib/dpkg/info directory
for _, pkg := range d.Packages {
newStatus.Paragraphs = append(newStatus.Paragraphs, pkg.Paragraph)
if pkg.StatusDirty {
if err := pkg.Sync(); err != nil {
return err
}
}
}
// Make a new version of /var/lib/dpkg/status
os.Rename("/var/lib/dpkg/status", "/var/lib/dpkg/status-old")
formatter := deb822.NewFormatter()
formatter.SetFoldedFields("Description")
formatter.SetMultilineFields("Conffiles")
if err := os.WriteFile("/var/lib/dpkg/status",
[]byte(formatter.Format(newStatus)), 0644); err != nil {
return err
}
return nil
}
func (p *PackageInfo) Sync() error {
// This function synchronizes the files under /var/lib/dpkg/info
// for a single package.
// Write <package>.list
if err := os.WriteFile(p.InfoPath("list"),
[]byte(MergeLines(p.Files)), 0644); err != nil {
return err
}
// Write <package>.conffiles
if err := os.WriteFile(p.InfoPath("conffiles"),
[]byte(MergeLines(p.Conffiles)), 0644); err != nil {
return err
}
// Write <package>.{preinst,prerm,postinst,postrm}
for name, content := range p.MaintainerScripts {
err := os.WriteFile(p.InfoPath(name), []byte(content), 0755)
if err != nil {
return err
}
}
p.StatusDirty = false
return nil
}
/* Utility functions */
func ReadLines(path string) ([]string, error) {
if _, err := os.Stat(path); !os.IsNotExist(err) {
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return SplitLines(string(content)), nil
}
return nil, nil
}
func SplitLines(content string) []string {
var lines []string
for _, line := range strings.Split(string(content), "\n") {
if strings.TrimSpace(line) == "" {
continue
}
lines = append(lines, line)
}
return lines
}
func MergeLines(lines []string) string {
return strings.Join(lines, "\n") + "\n"
}
|
[
1,
7
] |
package main
type Node struct {
Val int
Left *Node
Right *Node
Next *Node
}
func connect(root *Node) *Node {
if root == nil {
return nil
}
list := make([]*Node, 0)
list = append(list, root)
list = append(list, nil)
var node *Node
for len(list) != 0 {
node = list[0]
list = list[1:]
if node != nil {
node.Next = list[0]
if node.Left != nil { // 注意这里不能加入空节点。
list = append(list, node.Left)
}
if node.Right != nil {
list = append(list, node.Right)
}
} else {
if len(list) > 0 {
list = append(list, nil)
}
}
}
return root
}
func connect1(root *Node) *Node {
if root == nil {
return nil
}
curr := root
var head *Node
for curr.Left != nil {
head = curr
for head != nil {
head.Left.Next = head.Right
if head.Next != nil {
head.Right.Next = head.Next.Left
}
head = head.Next
}
curr = curr.Left
}
return root
}
func main() {
}
|
[
4
] |
package sniff
import (
"bytes"
"net"
"sort"
"time"
)
type SortableIps []net.IP
func (s SortableIps) Len() int {
return len(s)
}
func (s SortableIps) Less(i, j int) bool {
return bytes.Compare(s[i], s[j]) < 0
}
func (s SortableIps) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
type SortableHosts []HostInfos
func (s SortableHosts) Len() int {
return len(s)
}
func (s SortableHosts) Less(i, j int) bool {
firstIps := s[i].IPAddresses
secondIps := s[j].IPAddresses
sort.Sort(SortableIps(firstIps))
sort.Sort(SortableIps(secondIps))
if len(firstIps) == 0 && len(secondIps) == 0 {
return bytes.Compare(s[i].HardwareAddresses[0], s[j].HardwareAddresses[0]) < 0
} else if len(firstIps) > 0 && len(secondIps) == 0 {
return true
} else if len(firstIps) == 0 && len(secondIps) > 0 {
return false
} else {
return bytes.Compare(firstIps[0], secondIps[0]) < 0
}
}
func (s SortableHosts) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
type SortableHwAddrs []net.HardwareAddr
func (s SortableHwAddrs) Len() int {
return len(s)
}
func (s SortableHwAddrs) Less(i, j int) bool {
return bytes.Compare(s[i], s[j]) < 0
}
func (s SortableHwAddrs) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
type HostInfos struct {
HardwareAddresses []net.HardwareAddr
IPAddresses []net.IP
Hostnames []string
PackagesCount int
LastPackage time.Time
}
func (hostInfo *HostInfos) AddIp(ip net.IP) {
for _, existingIp := range hostInfo.IPAddresses {
if bytes.Equal(existingIp, ip) {
return
}
}
hostInfo.IPAddresses = append(hostInfo.IPAddresses, ip)
sort.Sort(SortableIps(hostInfo.IPAddresses))
}
func (hostInfo *HostInfos) AddHostname(hostname string) {
for _, existing := range hostInfo.Hostnames {
if existing == hostname {
return
}
}
hostInfo.Hostnames = append(hostInfo.Hostnames, hostname)
sort.Strings(hostInfo.Hostnames)
}
func (hostInfo *HostInfos) AddHardwareAddress(addr net.HardwareAddr) {
for _, existing := range hostInfo.HardwareAddresses {
if bytes.Equal(addr, existing) {
return
}
}
hostInfo.HardwareAddresses = append(hostInfo.HardwareAddresses, addr)
sort.Sort(SortableHwAddrs(hostInfo.HardwareAddresses))
}
func (hostInfo *HostInfos) CopyFrom(other *HostInfos) {
if other == nil {
return
}
for _, ip := range other.IPAddresses {
hostInfo.AddIp(ip)
}
for _, hw := range other.HardwareAddresses {
hostInfo.AddHardwareAddress(hw)
}
for _, hostname := range other.Hostnames {
hostInfo.AddHostname(hostname)
}
}
func (hostInfo *HostInfos) CountPackage() {
hostInfo.PackagesCount++
hostInfo.LastPackage = time.Now()
}
|
[
5
] |
// Copyright (c) 2013-2016 by Michael Dvorkin. All Rights Reserved.
// Use of this source code is governed by a MIT-style license that can
// be found in the LICENSE file.
package main
import (
"flag"
"log"
"time"
termbox "github.com/michaeldv/termbox-go"
"github.com/mvberg/mop"
od "github.com/barchart/barchart-ondemand-client-golang"
)
const help = `Mop v0.2.0 -- Copyright (c) 2013-2016 by Michael Dvorkin. All Rights Reserved.
NO WARRANTIES OF ANY KIND WHATSOEVER. SEE THE LICENSE FILE FOR DETAILS.
<u>Command</u> <u>Description </u>
+ Add stocks to the list.
- Remove stocks from the list.
? Display this help screen.
g Group stocks by advancing/declining issues.
o Change column sort order.
p Pause market data and stock updates.
q Quit mop.
esc Ditto.
Enter comma-delimited list of stock tickers when prompted.
<r> Press any key to continue </r>
`
//-----------------------------------------------------------------------------
func mainLoop(screen *mop.Screen, profile *mop.Profile, apiKey string, sandbox bool) {
var lineEditor *mop.LineEditor
var columnEditor *mop.ColumnEditor
keyboardQueue := make(chan termbox.Event)
timestampQueue := time.NewTicker(1 * time.Second)
quotesQueue := time.NewTicker(5 * time.Second)
marketQueue := time.NewTicker(12 * time.Second)
showingHelp := false
paused := false
go func() {
for {
keyboardQueue <- termbox.PollEvent()
}
}()
onDemand := od.New(apiKey, false)
if sandbox == true {
onDemand.BaseURL = "https://marketdata.websol.barchart.com/"
}
market := mop.NewMarket(onDemand)
quotes := mop.NewQuotes(market, profile)
screen.Draw(market, quotes)
loop:
for {
select {
case event := <-keyboardQueue:
switch event.Type {
case termbox.EventKey:
if lineEditor == nil && columnEditor == nil && !showingHelp {
if event.Key == termbox.KeyEsc || event.Ch == 'q' || event.Ch == 'Q' {
break loop
} else if event.Ch == '+' || event.Ch == '-' {
lineEditor = mop.NewLineEditor(screen, quotes)
lineEditor.Prompt(event.Ch)
} else if event.Ch == 'o' || event.Ch == 'O' {
columnEditor = mop.NewColumnEditor(screen, quotes)
} else if event.Ch == 'g' || event.Ch == 'G' {
if profile.Regroup() == nil {
screen.Draw(quotes)
}
} else if event.Ch == 'p' || event.Ch == 'P' {
paused = !paused
screen.Pause(paused).Draw(time.Now())
} else if event.Ch == '?' || event.Ch == 'h' || event.Ch == 'H' {
showingHelp = true
screen.Clear().Draw(help)
}
} else if lineEditor != nil {
if done := lineEditor.Handle(event); done {
lineEditor = nil
}
} else if columnEditor != nil {
if done := columnEditor.Handle(event); done {
columnEditor = nil
}
} else if showingHelp {
showingHelp = false
screen.Clear().Draw(market, quotes)
}
case termbox.EventResize:
screen.Resize()
if !showingHelp {
screen.Draw(market, quotes)
} else {
screen.Draw(help)
}
}
case <-timestampQueue.C:
if !showingHelp && !paused {
screen.Draw(time.Now())
}
case <-quotesQueue.C:
if !showingHelp && !paused {
screen.Draw(quotes)
}
case <-marketQueue.C:
if !showingHelp && !paused {
screen.Draw(market)
}
}
}
}
//-----------------------------------------------------------------------------
func main() {
screen := mop.NewScreen()
defer screen.Close()
apiKey := flag.String("key", "", "OnDemand API Key")
sandbox := flag.Bool("sandbox", false, "Set to true if using Free API")
flag.Parse()
if len(*apiKey) == 0 {
log.Panic("You must set your API key: -key=YOUR_KEY")
}
profile := mop.NewProfile()
mainLoop(screen, profile, *apiKey, *sandbox)
}
|
[
5
] |
package alexa
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"github.com/domenipavec/jaslice-go/application"
"github.com/fromkeith/gossdp"
uuid "github.com/satori/go.uuid"
)
const SetupXML = `<?xml version="1.0"?>
<root>
<device>
<deviceType>urn:MakerMusings:device:controllee:1</deviceType>
<friendlyName>%s</friendlyName>
<manufacturer>Belkin International Inc.</manufacturer>
<modelName>Emulated Socket</modelName>
<modelNumber>3.1415</modelNumber>
<UDN>uuid:%s</UDN>
</device>
</root>
`
type Alexa struct {
invocation string
onUrl string
offUrl string
}
// Get preferred outbound ip of this machine
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
func New(app *application.App, config application.Config) application.Module {
alexa := &Alexa{
invocation: config.GetString("invocation"),
onUrl: config.GetString("onUrl"),
offUrl: config.GetString("offUrl"),
}
uid := uuid.NewV3(uuid.NamespaceDNS, alexa.invocation)
ip := GetOutboundIP()
port := 40000 + int(uid[0]) + int(uid[1])*10
serial := "Socket-1_0-" + uid.String()
log.Printf("Running %s on %s:%d", serial, ip, port)
serverDef := gossdp.AdvertisableServer{
ServiceType: "urn:Belkin:device:**",
DeviceUuid: serial,
Location: fmt.Sprintf("http://%s:%d/setup.xml", ip, port),
MaxAge: 86400,
}
mux := http.NewServeMux()
mux.HandleFunc("/setup.xml", func(w http.ResponseWriter, r *http.Request) {
log.Printf("setup.xml for %s:%d", ip, port)
fmt.Fprintf(w, SetupXML, alexa.invocation, serial)
})
mux.HandleFunc("/upnp/control/basicevent1", func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println("Error reading body:", err)
http.Error(w, "can't read body", http.StatusBadRequest)
}
if !bytes.Contains(body, []byte("SetBinaryState")) {
return
}
action := ""
if bytes.Contains(body, []byte("<BinaryState>1</BinaryState>")) {
action = "on"
} else if bytes.Contains(body, []byte("<BinaryState>0</BinaryState>")) {
action = "off"
} else {
log.Println("Invalid action")
return
}
log.Printf("got control event for %s: %s", alexa.invocation, action)
if action == "on" {
alexa.get(alexa.onUrl)
} else {
alexa.get(alexa.offUrl)
}
})
go func() {
s := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: mux,
}
s.SetKeepAlivesEnabled(false)
err := s.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}()
app.Ssdp.AdvertiseServer(serverDef)
return alexa
}
func (alexa *Alexa) get(url string) {
_, err := http.Get("http://localhost:80" + url)
if err != nil {
log.Printf("Error with get request to %s: %s", url, err)
}
}
func (alexa *Alexa) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
}
func (alexa *Alexa) Data() interface{} {
return nil
}
func (alexa *Alexa) On() {
}
func (alexa *Alexa) Off() {
}
|
[
5
] |
package main
import "fmt"
func searchRange(A []int, target int) []int {
// write your code here
res := make([]int, 2)
flag := true
if len(A) == 0 {
return []int{-1, -1}
}
for i := 0; i < len(A); i++ {
if A[i] == target {
if flag {
res[0] = i
flag = false
} else {
res[1] = i
}
}
}
return res
}
func main() {
A := []int{5, 7, 7, 8, 8, 10}
fmt.Println(searchRange(A, 8))
}
|
[
2
] |
package main
import (
"fmt"
)
func cycle(n,m int) int {
if n < 1 || m < 1 {
return -1
} else if n == 1{
return 0
} else {
// F[n] = (F[n - 1] + m) % n
return (cycle(n-1,m) + m) % n
}
}
func main() {
fmt.Println(3,2, " => ", cycle(3,2))
fmt.Println(4,2, " => ", cycle(4,2))
fmt.Println(5,2, " => ", cycle(5,2))
}
|
[
5
] |
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"time"
)
type World struct {
Cells []int
Width int
}
func NeweWorld(width int, density float64) *World {
cells := make([]int, width)
for i, _ := range cells {
if rand.Float64() < density {
cells[i] = rand.Intn(19) - 9
}
}
return &World{
Cells: cells,
Width: width,
}
}
func (w *World) Reproduce() {
newcells := make([]int, w.Width)
cc := make([]int, w.Width)
for i, old := range w.Cells {
if old != 0 {
// i = mod(i+old, w.Width)
i = i + old
if 0 <= i && i < w.Width {
cc[i] += 1
newcells[i] += old
}
}
}
for i, old := range w.Cells {
if cc[i] > 0 {
w.Cells[i] = newcells[i] - old*(cc[i]-1)
}
}
}
func mod(d, m int) int {
return ((d % m) + m) % m
}
func main() {
var sc = bufio.NewScanner(os.Stdin)
rand.Seed(time.Now().UnixNano())
world := NeweWorld(30, 0.2)
for i := 0; i < 30000; i++ {
sc.Scan()
for _, v := range world.Cells {
fmt.Printf("%3d", v)
}
world.Reproduce()
}
}
|
[
0
] |
package main
func main() {
mapOfHolidays := getAndParseData()
longWeekends := calculateLongWeekends(mapOfHolidays)
isLongWeekendNow, currentLongWeekend := isLongWeekendNow(longWeekends)
if isLongWeekendNow {
outputCurrLongWeekend(currentLongWeekend, mapOfHolidays)
} else if isHolidayToday(mapOfHolidays) {
outputCurrHoliday(mapOfHolidays)
} else {
nextHolidayDate := getNextHolidayDate(mapOfHolidays)
nextLongWeekend := getNextLongWeekend(longWeekends)
nextHolidayTime := stringToTime(nextHolidayDate)
nextLongWeekendStartTime := stringToTime(nextLongWeekend.Start)
if nextLongWeekend.Start == nextHolidayDate || nextLongWeekendStartTime.Before(nextHolidayTime) {
outputNextLongWeekend(mapOfHolidays, nextLongWeekend)
} else {
outputNextHoliday(mapOfHolidays, nextHolidayDate)
}
}
}
|
[
5
] |
package tx
import (
"encoding/binary"
"io"
"math"
)
// Varint .
type Varint uint64
func (varint *Varint) Write(writer io.Writer) error {
if uint64(*varint) < 0xFD {
_, err := writer.Write([]byte{byte(*varint)})
return err
} else if uint64(*varint) < math.MaxUint16 {
buff := make([]byte, 3)
buff[0] = 0xFD
binary.LittleEndian.PutUint16(buff[1:], uint16(*varint))
_, err := writer.Write(buff)
return err
} else if uint64(*varint) < math.MaxUint32 {
buff := make([]byte, 5)
buff[0] = 0xFE
binary.LittleEndian.PutUint32(buff[1:], uint32(*varint))
_, err := writer.Write(buff)
return err
}
buff := make([]byte, 9)
buff[0] = 0xFF
binary.LittleEndian.PutUint64(buff[1:], uint64(*varint))
_, err := writer.Write(buff)
return err
}
func (varint *Varint) Read(reader io.Reader) error {
flag := make([]byte, 1)
_, err := reader.Read(flag)
if err != nil {
return err
}
if flag[0] == 0xFD {
buff := make([]byte, 2)
_, err := reader.Read(buff)
(*varint) = Varint(binary.LittleEndian.Uint16(buff))
if err != nil {
return err
}
} else if flag[0] == 0xFE {
buff := make([]byte, 4)
_, err := reader.Read(buff)
(*varint) = Varint(binary.LittleEndian.Uint32(buff))
if err != nil {
return err
}
} else if flag[0] == 0xFF {
buff := make([]byte, 8)
_, err := reader.Read(buff)
(*varint) = Varint(binary.LittleEndian.Uint64(buff))
if err != nil {
return err
}
} else {
*varint = Varint(flag[0])
}
return nil
}
|
[
5
] |
package easy
import "strconv"
func fizzBuzz(n int) (strs []string) {
for i := 1; i <= n; i++ {
if i%3 == 0 && i%5 == 0 {
strs = append(strs, "FizzBuzz")
} else if i%3 == 0 {
strs = append(strs, "Fizz")
} else if i%5 == 0 {
strs = append(strs, "Buzz")
} else {
strs = append(strs, strconv.Itoa(i))
}
}
return
}
|
[
5
] |
package models
import (
"fmt"
"math"
"strings"
"time"
"github.com/oysterprotocol/brokernode/utils"
)
/*BatchUpsert updates a table and overwrite its current the values of column.*/
func BatchUpsert(tableName string, serializeValues []string, serializedColumnNames string, onConflictColumnsNames []string) error {
numOfBatchRequest := int(math.Ceil(float64(len(serializeValues)) / float64(oyster_utils.SQL_BATCH_SIZE)))
var updatedColumns []string
for _, v := range onConflictColumnsNames {
if v == oyster_utils.UpdatedAt {
continue
}
updatedColumns = append(updatedColumns, fmt.Sprintf("%s = VALUES(%s)", v, v))
}
updatedColumns = append(updatedColumns, fmt.Sprintf("%s = VALUES(%s)", oyster_utils.UpdatedAt, oyster_utils.UpdatedAt))
serializedUpdatedColumnName := strings.Join(updatedColumns, oyster_utils.COLUMNS_SEPARATOR)
// Batch Update data_maps table.
remainder := len(serializeValues)
for i := 0; i < numOfBatchRequest; i++ {
lower := i * oyster_utils.SQL_BATCH_SIZE
upper := i*oyster_utils.SQL_BATCH_SIZE + int(math.Min(float64(remainder), oyster_utils.SQL_BATCH_SIZE))
upsertedValues := serializeValues[lower:upper]
for k := 0; k < len(upsertedValues); k++ {
upsertedValues[k] = fmt.Sprintf("(%s)", upsertedValues[k])
}
// Do an insert operation and dup by primary key.
var rawQuery string
values := strings.Join(upsertedValues, oyster_utils.COLUMNS_SEPARATOR)
if len(serializedUpdatedColumnName) > 0 {
rawQuery = fmt.Sprintf(`INSERT INTO %s(%s) VALUES %s ON DUPLICATE KEY UPDATE %s`,
tableName, serializedColumnNames, values, serializedUpdatedColumnName)
} else {
rawQuery = fmt.Sprintf(`INSERT INTO %s(%s) VALUES %s`, tableName, serializedColumnNames, values)
}
err := DB.RawQuery(rawQuery).Exec()
retryCount := oyster_utils.MAX_NUMBER_OF_SQL_RETRY
for err != nil && retryCount > 0 {
time.Sleep(300 * time.Millisecond)
err = DB.RawQuery(rawQuery).Exec()
retryCount = retryCount - 1
}
if err != nil {
oyster_utils.LogIfError(err, nil)
return err
}
remainder = remainder - oyster_utils.SQL_BATCH_SIZE
}
return nil
}
|
[
0
] |
package result
import (
"fmt"
"gg/src/validator"
)
type ErrorResult struct {
data interface{}
err error
}
func (r *ErrorResult) Unwrap() interface{} {
if r.err != nil {
validator.CheckErrors(r.err)
panic(r.err.Error())
}
return r.data
}
func Result(any ...interface{}) *ErrorResult {
switch len(any) {
case 1:
if any[0] == nil {
return &ErrorResult{nil, nil}
} else if e, ok := any[0].(error); ok {
return &ErrorResult{nil, e}
}
case 2:
if any[1] == nil {
return &ErrorResult{any[0], nil}
} else if e, ok := any[1].(error); ok {
return &ErrorResult{any[0], e}
}
}
return &ErrorResult{nil, fmt.Errorf("error result")}
}
|
[
1
] |
package algo
import "math"
func RecursionSum(data []int) int {
if len(data) == 0 {
return 0
}
return data[0] + RecursionSum(data[1:])
}
func RecursionMax(data []int) int {
if len(data) == 0 {
return math.MinInt64
}
if len(data) == 1 {
return data[0]
}
i := data[0]
j := RecursionMax(data[1:])
if i > j {
return i
}
return j
}
// return index of target.
func RecursionBinSearch(data []int, target int) int {
if len(data) == 0 {
return math.MinInt64
}
if len(data) == 1 && data[0] == target {
return 0
} else if len(data) == 1 {
return math.MinInt64
}
left := 0
right := len(data)
mid := left + (right-left)/2
if data[mid] > target {
right = mid
} else if data[mid] == target {
return mid
} else {
left = mid + 1
}
return left + RecursionBinSearch(data[left:right], target)
}
|
[
5
] |
package gui
import (
"fmt"
"html"
"log"
"sort"
"time"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/gtk"
rosters "github.com/twstrike/coyim/roster"
"github.com/twstrike/coyim/ui"
)
type roster struct {
widget *gtk.ScrolledWindow
model *gtk.TreeStore
view *gtk.TreeView
checkEncrypted func(to string) bool
sendMessage func(to, message string)
isCollapsed map[string]bool
toCollapse []*gtk.TreePath
ui *gtkUI
}
const (
indexJid = 0
indexDisplayName = 1
indexAccountID = 2
indexColor = 3
indexBackgroundColor = 4
indexWeight = 5
indexParentJid = 0
indexParentDisplayName = 1
indexTooltip = 6
indexStatusIcon = 7
indexRowType = 8
)
func (u *gtkUI) newRoster() *roster {
builder := builderForDefinition("Roster")
r := &roster{
isCollapsed: make(map[string]bool),
ui: u,
}
builder.ConnectSignals(map[string]interface{}{
"on_activate_buddy": r.onActivateBuddy,
})
obj, _ := builder.GetObject("roster")
r.widget = obj.(*gtk.ScrolledWindow)
obj, _ = builder.GetObject("roster-view")
r.view = obj.(*gtk.TreeView)
obj, _ = builder.GetObject("roster-model")
r.model = obj.(*gtk.TreeStore)
u.displaySettings.update()
r.view.Connect("button-press-event", r.onButtonPress)
return r
}
func (r *roster) getAccount(id string) (*account, bool) {
return r.ui.accountManager.getAccountByID(id)
}
func getFromModelIter(m *gtk.TreeStore, iter *gtk.TreeIter, index int) string {
val, _ := m.GetValue(iter, index)
v, _ := val.GetString()
return v
}
func (r *roster) getAccountAndJidFromEvent(bt *gdk.EventButton) (jid string, account *account, rowType string, ok bool) {
x := bt.X()
y := bt.Y()
path := new(gtk.TreePath)
found := r.view.GetPathAtPos(int(x), int(y), path, nil, nil, nil)
if !found {
return "", nil, "", false
}
iter, err := r.model.GetIter(path)
if err != nil {
return "", nil, "", false
}
jid = getFromModelIter(r.model, iter, indexJid)
accountID := getFromModelIter(r.model, iter, indexAccountID)
rowType = getFromModelIter(r.model, iter, indexRowType)
account, ok = r.getAccount(accountID)
return jid, account, rowType, ok
}
func (r *roster) createAccountPeerPopup(jid string, account *account, bt *gdk.EventButton) {
builder := builderForDefinition("ContactPopupMenu")
obj, _ := builder.GetObject("contactMenu")
mn := obj.(*gtk.Menu)
builder.ConnectSignals(map[string]interface{}{
"on_remove_contact": func() {
account.session.RemoveContact(jid)
r.ui.removePeer(account, jid)
r.redraw()
},
"on_allow_contact_to_see_status": func() {
account.session.ApprovePresenceSubscription(jid, "" /* generate id */)
},
"on_forbid_contact_to_see_status": func() {
account.session.DenyPresenceSubscription(jid, "" /* generate id */)
},
"on_ask_contact_to_see_status": func() {
account.session.RequestPresenceSubscription(jid)
},
"on_dump_info": func() {
r.debugPrintRosterFor(account.session.GetConfig().Account)
},
})
mn.ShowAll()
mn.PopupAtMouseCursor(nil, nil, int(bt.Button()), bt.Time())
}
func (r *roster) createAccountPopup(jid string, account *account, bt *gdk.EventButton) {
builder := builderForDefinition("AccountPopupMenu")
obj, _ := builder.GetObject("accountMenu")
mn := obj.(*gtk.Menu)
builder.ConnectSignals(map[string]interface{}{
"on_connect": func() {
account.connect()
},
"on_disconnect": func() {
account.disconnect()
},
"on_dump_info": func() {
r.debugPrintRosterFor(account.session.GetConfig().Account)
},
})
connx, _ := builder.GetObject("connectMenuItem")
connect := connx.(*gtk.MenuItem)
dconnx, _ := builder.GetObject("disconnectMenuItem")
disconnect := dconnx.(*gtk.MenuItem)
connect.SetSensitive(account.session.IsDisconnected())
disconnect.SetSensitive(account.session.IsConnected())
mn.ShowAll()
mn.PopupAtMouseCursor(nil, nil, int(bt.Button()), bt.Time())
}
func (r *roster) onButtonPress(view *gtk.TreeView, ev *gdk.Event) bool {
bt := &gdk.EventButton{ev}
if bt.Button() == 0x03 {
jid, account, rowType, ok := r.getAccountAndJidFromEvent(bt)
if ok {
switch rowType {
case "peer":
r.createAccountPeerPopup(jid, account, bt)
case "account":
r.createAccountPopup(jid, account, bt)
}
}
}
return false
}
func (r *roster) onActivateBuddy(v *gtk.TreeView, path *gtk.TreePath) {
selection, _ := v.GetSelection()
defer selection.UnselectPath(path)
iter, err := r.model.GetIter(path)
if err != nil {
return
}
jid := getFromModelIter(r.model, iter, indexJid)
accountID := getFromModelIter(r.model, iter, indexAccountID)
rowType := getFromModelIter(r.model, iter, indexRowType)
if rowType != "peer" {
r.isCollapsed[jid] = !r.isCollapsed[jid]
r.redraw()
return
}
account, ok := r.getAccount(accountID)
if !ok {
return
}
r.openConversationWindow(account, jid)
}
func (r *roster) openConversationWindow(account *account, to string) (*conversationWindow, error) {
c, ok := account.getConversationWith(to)
if !ok {
textBuffer := r.ui.getTags().createTextBuffer()
c = account.createConversationWindow(to, r.ui.displaySettings, textBuffer)
r.ui.connectShortcutsChildWindow(c.win)
r.ui.connectShortcutsConversationWindow(c)
c.parentWin = r.ui.window
}
c.Show()
return c, nil
}
func (r *roster) displayNameFor(account *account, from string) string {
p, ok := r.ui.getPeer(account, from)
if !ok {
return from
}
return p.NameForPresentation()
}
func (r *roster) presenceUpdated(account *account, from, show, showStatus string, gone bool) {
c, ok := account.getConversationWith(from)
if !ok {
return
}
doInUIThread(func() {
c.appendStatus(r.displayNameFor(account, from), time.Now(), show, showStatus, gone)
})
}
func (r *roster) messageReceived(account *account, from string, timestamp time.Time, encrypted bool, message []byte) {
doInUIThread(func() {
conv, err := r.openConversationWindow(account, from)
if err != nil {
return
}
conv.appendMessage(r.displayNameFor(account, from), timestamp, encrypted, ui.StripHTML(message), false)
})
}
func (r *roster) update(account *account, entries *rosters.List) {
r.ui.accountManager.Lock()
defer r.ui.accountManager.Unlock()
r.ui.accountManager.setContacts(account, entries)
}
func (r *roster) debugPrintRosterFor(nm string) {
r.ui.accountManager.RLock()
defer r.ui.accountManager.RUnlock()
for account, rs := range r.ui.accountManager.getAllContacts() {
if account.session.GetConfig().Is(nm) {
rs.Iter(func(_ int, item *rosters.Peer) {
fmt.Printf("-> %s\n", item.Dump())
})
}
}
fmt.Printf(" ************************************** \n")
fmt.Println()
}
func isNominallyVisible(p *rosters.Peer) bool {
return (p.Subscription != "none" && p.Subscription != "") || p.PendingSubscribeID != ""
}
func shouldDisplay(p *rosters.Peer, showOffline bool) bool {
return isNominallyVisible(p) && (showOffline || p.Online)
}
func isAway(p *rosters.Peer) bool {
switch p.Status {
case "dnd", "xa", "away":
return true
}
return false
}
func isOnline(p *rosters.Peer) bool {
return p.PendingSubscribeID == "" && p.Online
}
func decideStatusFor(p *rosters.Peer) string {
if p.PendingSubscribeID != "" {
return "unknown"
}
if !p.Online {
return "offline"
}
switch p.Status {
case "dnd":
return "busy"
case "xa":
return "extended-away"
case "away":
return "away"
}
return "available"
}
func decideColorFor(p *rosters.Peer) string {
if !p.Online {
return "#aaaaaa"
}
return "#000000"
}
func createGroupDisplayName(parentName string, counter *counter, isExpanded bool) string {
name := parentName
if !isExpanded {
name = fmt.Sprintf("[%s]", name)
}
return fmt.Sprintf("%s (%d/%d)", name, counter.online, counter.total)
}
func createTooltipFor(item *rosters.Peer) string {
pname := html.EscapeString(item.NameForPresentation())
jid := html.EscapeString(item.Jid)
if pname != jid {
return fmt.Sprintf("%s (%s)", pname, jid)
}
return jid
}
func (r *roster) addItem(item *rosters.Peer, parentIter *gtk.TreeIter, indent string) {
iter := r.model.Append(parentIter)
setAll(r.model, iter,
item.Jid,
fmt.Sprintf("%s %s", indent, item.NameForPresentation()),
item.BelongsTo,
decideColorFor(item),
"#ffffff",
nil,
createTooltipFor(item),
)
r.model.SetValue(iter, indexRowType, "peer")
r.model.SetValue(iter, indexStatusIcon, statusIcons[decideStatusFor(item)].getPixbuf())
}
func (r *roster) redrawMerged() {
showOffline := !r.ui.config.Display.ShowOnlyOnline
r.ui.accountManager.RLock()
defer r.ui.accountManager.RUnlock()
r.toCollapse = nil
grp := rosters.TopLevelGroup()
for account, contacts := range r.ui.accountManager.getAllContacts() {
contacts.AddTo(grp, account.session.GroupDelimiter)
}
accountCounter := &counter{}
r.displayGroup(grp, nil, accountCounter, showOffline, "")
r.view.ExpandAll()
for _, path := range r.toCollapse {
r.view.CollapseRow(path)
}
}
type counter struct {
total int
online int
}
func (c *counter) inc(total, online bool) {
if total {
c.total++
}
if online {
c.online++
}
}
func (r *roster) displayGroup(g *rosters.Group, parentIter *gtk.TreeIter, accountCounter *counter, showOffline bool, accountName string) {
pi := parentIter
groupCounter := &counter{}
groupID := accountName + "//" + g.FullGroupName()
if g.GroupName != "" {
pi = r.model.Append(parentIter)
r.model.SetValue(pi, indexParentJid, groupID)
r.model.SetValue(pi, indexRowType, "group")
r.model.SetValue(pi, indexWeight, 500)
r.model.SetValue(pi, indexBackgroundColor, "#e9e7f3")
}
for _, item := range g.Peers() {
vs := isNominallyVisible(item)
o := isOnline(item)
accountCounter.inc(vs, vs && o)
groupCounter.inc(vs, vs && o)
if shouldDisplay(item, showOffline) {
r.addItem(item, pi, "")
}
}
for _, gr := range g.Groups() {
r.displayGroup(gr, pi, accountCounter, showOffline, accountName)
}
if g.GroupName != "" {
parentPath, _ := r.model.GetPath(pi)
shouldCollapse, ok := r.isCollapsed[groupID]
isExpanded := true
if ok && shouldCollapse {
isExpanded = false
r.toCollapse = append(r.toCollapse, parentPath)
}
r.model.SetValue(pi, indexParentDisplayName, createGroupDisplayName(g.FullGroupName(), groupCounter, isExpanded))
}
}
func (r *roster) redrawSeparateAccount(account *account, contacts *rosters.List, showOffline bool) {
parentIter := r.model.Append(nil)
accountCounter := &counter{}
grp := contacts.Grouped(account.session.GroupDelimiter)
parentName := account.session.GetConfig().Account
r.displayGroup(grp, parentIter, accountCounter, showOffline, parentName)
r.model.SetValue(parentIter, indexParentJid, parentName)
r.model.SetValue(parentIter, indexAccountID, account.session.GetConfig().ID())
r.model.SetValue(parentIter, indexRowType, "account")
r.model.SetValue(parentIter, indexWeight, 700)
bgcolor := "#918caa"
if account.session.IsDisconnected() {
bgcolor = "#d5d3de"
}
r.model.SetValue(parentIter, indexBackgroundColor, bgcolor)
parentPath, _ := r.model.GetPath(parentIter)
shouldCollapse, ok := r.isCollapsed[parentName]
isExpanded := true
if ok && shouldCollapse {
isExpanded = false
r.toCollapse = append(r.toCollapse, parentPath)
}
var stat string
if account.session.IsDisconnected() {
stat = "offline"
} else if account.session.IsConnected() {
stat = "available"
} else {
stat = "connecting"
}
r.model.SetValue(parentIter, indexStatusIcon, statusIcons[stat].getPixbuf())
r.model.SetValue(parentIter, indexParentDisplayName, createGroupDisplayName(parentName, accountCounter, isExpanded))
}
func (r *roster) sortedAccounts() []*account {
var as []*account
for account := range r.ui.accountManager.getAllContacts() {
if account == nil {
log.Printf("adding an account that is nil...\n")
}
as = append(as, account)
}
sort.Sort(byAccountNameAlphabetic(as))
return as
}
func (r *roster) redrawSeparate() {
showOffline := !r.ui.config.Display.ShowOnlyOnline
r.ui.accountManager.RLock()
defer r.ui.accountManager.RUnlock()
r.toCollapse = nil
for _, account := range r.sortedAccounts() {
r.redrawSeparateAccount(account, r.ui.accountManager.getContacts(account), showOffline)
}
r.view.ExpandAll()
for _, path := range r.toCollapse {
r.view.CollapseRow(path)
}
}
const disconnectedPageIndex = 0
const spinnerPageIndex = 1
const rosterPageIndex = 2
func (r *roster) redraw() {
//TODO: this should be behind a mutex
r.model.Clear()
if r.ui.shouldViewAccounts() {
r.redrawSeparate()
} else {
r.redrawMerged()
}
}
func setAll(v *gtk.TreeStore, iter *gtk.TreeIter, values ...interface{}) {
for i, val := range values {
if val != nil {
v.SetValue(iter, i, val)
}
}
}
|
[
5
] |
package controllers
import (
"bytes"
"encoding/xml"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
"github.com/eaciit/clit"
"github.com/eaciit/toolkit"
"git.eaciitapp.com/rezaharli/toracle/helpers"
"git.eaciitapp.com/rezaharli/toracle/models"
"git.eaciitapp.com/sebar/dbflex"
)
type MasterController struct {
*Base
}
func NewMasterController() *MasterController {
return new(MasterController)
}
func (c *MasterController) ReadAPI() error {
var err error
compcode := []string{"PTTL", "ZTOS"}
for _, cc := range compcode {
log.Println("\n--------------------------------------\nReading Master Vendor API", cc)
resultsVendor, err := c.FetchVendor(cc)
if err != nil {
log.Println(err.Error())
return err
}
for _, vendor := range resultsVendor {
vendor.Set("COMP_CODE", cc)
}
log.Println("\n--------------------------------------\nInserting", len(resultsVendor), "Rows Master Vendor API")
err = c.InsertData(resultsVendor, "vendor")
if err != nil {
log.Println(err.Error())
return err
}
log.Println("\n--------------------------------------\nReading Master Customer API", cc)
resultsCustomer, err := c.FetchCustomer(cc)
if err != nil {
log.Println(err.Error())
return err
}
for _, cust := range resultsCustomer {
cust.Set("COMP_CODE", cc)
}
log.Println("\n--------------------------------------\nInserting", len(resultsCustomer), " Master Customer API")
err = c.InsertData(resultsCustomer, "customer")
if err != nil {
log.Println(err.Error())
return err
}
}
return err
}
func (c *MasterController) FetchCustomer(compcode string) ([]toolkit.M, error) {
log.Println("Fetch Customers")
config := clit.Config("master", "customer", map[string]interface{}{}).(map[string]interface{})
username := clit.Config("master", "username", nil).(string)
password := clit.Config("master", "password", nil).(string)
// compcode := clit.Config("master", "compcode", nil).(string)
parambody := `<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<ZFMFI_CUSTOMER_GETLIST xmlns="urn:sap-com:document:sap:rfc:functions">
<!--Company Code-->
<COMP_CODE xmlns="">` + compcode + `</COMP_CODE>
<!--List of Customers-->
<!-- Optional -->
<CUSTOMER xmlns="">
<item></item>
</CUSTOMER>
</ZFMFI_CUSTOMER_GETLIST>
</Body>
</Envelope>`
payload := []byte(strings.TrimSpace(parambody))
request, err := http.NewRequest("POST", config["url"].(string), bytes.NewReader(payload))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/xml")
request.SetBasicAuth(username, password)
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
r := &models.MasterCustomer{}
err = xml.Unmarshal(body, &r)
if err != nil {
return nil, err
}
results := make([]toolkit.M, 0)
for _, value := range r.Body.Urn.CUSTOMER.Item {
result, _ := toolkit.ToM(value)
results = append(results, result)
}
return results, err
}
func (c *MasterController) FetchVendor(compcode string) ([]toolkit.M, error) {
log.Println("Fetch Vendor")
config := clit.Config("master", "vendor", map[string]interface{}{}).(map[string]interface{})
username := clit.Config("master", "username", nil).(string)
password := clit.Config("master", "password", nil).(string)
// compcode := clit.Config("master", "compcode", nil).(string)
parambody := `<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<ZFMFI_VENDOR_GETLIST xmlns="urn:sap-com:document:sap:rfc:functions">
<!--Company Code-->
<COMP_CODE xmlns="">` + compcode + `</COMP_CODE>
<!--List of Vendors-->
<!-- Optional -->
<VENDOR xmlns="">
<item></item>
</VENDOR>
</ZFMFI_VENDOR_GETLIST>
</Body>
</Envelope>`
payload := []byte(strings.TrimSpace(parambody))
request, err := http.NewRequest("POST", config["url"].(string), bytes.NewReader(payload))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/xml")
request.SetBasicAuth(username, password)
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
r := &models.MasterVendor{}
err = xml.Unmarshal(body, &r)
if err != nil {
return nil, err
}
results := make([]toolkit.M, 0)
for _, value := range r.Body.Urn.VENDOR.Item {
result, _ := toolkit.ToM(value)
results = append(results, result)
}
return results, err
}
func (c *MasterController) InsertData(results []toolkit.M, configname string) error {
var err error
config := clit.Config("master", configname, nil).(map[string]interface{})
columnsMapping := config["columnsMapping"].(map[string]interface{})
// compcode := clit.Config("master", "compcode", nil).(string)
tablename := ""
wherecol := ""
if configname == "vendor" {
tablename = "SAP_VENDOR"
wherecol = "VENDOR_NO"
} else if configname == "customer" {
tablename = "SAP_CUSTOMER"
wherecol = "CUST_NO"
}
var headers []Header
for dbFieldName, attributeName := range columnsMapping {
header := Header{
DBFieldName: dbFieldName,
Column: attributeName.(string),
}
headers = append(headers, header)
}
for _, result := range results {
rowData := toolkit.M{}
for _, header := range headers {
if header.DBFieldName == "VENDOR_NAME" || header.DBFieldName == "CUST_NAME" {
if strings.Contains(result[header.Column].(string), ",") {
rowData.Set(header.DBFieldName, strings.Replace(result[header.Column].(string), ",", "", -1))
} else if strings.Contains(result[header.Column].(string), "'") {
rowData.Set(header.DBFieldName, strings.Replace(result[header.Column].(string), "'", "", -1))
} else {
rowData.Set(header.DBFieldName, result[header.Column])
}
} else {
rowData.Set(header.DBFieldName, result[header.Column])
}
}
rowData.Set("UPDATE_DATE", time.Now())
// rowData.Set("COMP_CODE", compcode)
sql := "DELETE FROM " + tablename + " WHERE " + wherecol + " = '" + rowData.GetString(wherecol) + "'"
conn := helpers.Database()
query, err := conn.Prepare(dbflex.From(tablename).SQL(sql))
if err != nil {
log.Println(err)
}
_, err = query.Execute(toolkit.M{}.Set("data", toolkit.M{}))
if err != nil {
log.Println(err)
}
// log.Println(tablename, rowData)
param := helpers.InsertParam{
TableName: tablename,
Data: rowData,
}
// log.Println("Inserting Data:", configname)
err = helpers.Insert(param)
if err != nil {
helpers.HandleError(err)
}
}
return err
}
|
[
5
] |
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed 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 main
import (
"context"
"flag"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"github.com/google/gapid/core/app"
"github.com/google/gapid/core/text/parse/cst"
"github.com/google/gapid/gapil"
"github.com/google/gapid/gapil/semantic"
)
var (
apiPath = flag.String("api", "", "Filename of the api file to verify (required)")
cacheDir = flag.String("cache", "", "Directory for caching downloaded files (required)")
apiRoot *semantic.API
mappings *semantic.Mappings
numErrors = 0
)
func main() {
app.ShortHelp = "stringgen compiles string table files to string packages and a Go definition file."
app.Run(run)
}
func run(ctx context.Context) error {
if *apiPath == "" {
app.Usage(ctx, "Mustsupply api path")
}
if *cacheDir == "" {
app.Usage(ctx, "Must supply cache dir")
}
processor := gapil.NewProcessor()
mappings = processor.Mappings
api, errs := processor.Resolve(*apiPath)
if len(errs) > 0 {
for _, err := range errs {
PrintError("%v\n", err.Message)
}
os.Exit(2)
}
apiRoot = api
reg := DownloadRegistry()
VerifyApi(reg)
return nil
}
func PrintError(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
numErrors = numErrors + 1
}
func VerifyApi(reg *Registry) {
VerifyEnum(reg, false)
VerifyEnum(reg, true)
for _, cmd := range reg.Command {
VerifyCommand(reg, cmd)
}
}
func VerifyEnum(r *Registry, bitfields bool) {
name := "GLenum"
if bitfields {
name = "GLbitfield"
}
expected := make(map[string]struct{})
for _, enums := range r.Enums {
if (enums.Type == "bitmask") == bitfields && enums.Namespace == "GL" {
for _, enum := range enums.Enum {
// Boolean values are handles specially (as labels)
if enum.Name == "GL_TRUE" || enum.Name == "GL_FALSE" {
continue
}
// The following 64bit values are not proper GLenum values.
if enum.Name == "GL_TIMEOUT_IGNORED" || enum.Name == "GL_TIMEOUT_IGNORED_APPLE" {
continue
}
if enum.API == "" || enum.API == GLES1API || enum.API == GLES2API {
var value uint32
if v, err := strconv.ParseUint(enum.Value, 0, 32); err == nil {
value = uint32(v)
} else if v, err := strconv.ParseInt(enum.Value, 0, 32); err == nil {
value = uint32(v)
} else {
PrintError("Failed to parse enum value %v", enum.Value)
continue
}
expected[fmt.Sprintf("%s = 0x%08X", enum.Name, value)] = struct{}{}
}
}
}
}
seen := make(map[string]struct{})
for _, e := range apiRoot.Enums {
if e.Name() == name {
for _, m := range e.Entries {
seen[fmt.Sprintf("%s = 0x%08X", m.Name(), m.Value)] = struct{}{}
}
}
}
CompareSets(expected, seen, name+": ")
}
func CompareSets(expected, seen map[string]struct{}, msg_prefix string) {
for k := range expected {
if _, found := seen[k]; !found {
PrintError("%sMissing %s\n", msg_prefix, k)
}
}
for k := range seen {
if _, found := expected[k]; !found {
PrintError("%sUnexpected %s\n", msg_prefix, k)
}
}
return
}
var re_const_ptr_pre = regexp.MustCompile(`^const (\w+) \*$`)
var re_const_ptr_post = regexp.MustCompile(`^(.+)\bconst\*$`)
func VerifyType(cmd string, paramIndex int, expected string, seen semantic.Type) bool {
expected = strings.TrimSpace(expected)
name := seen.(semantic.NamedNode).Name()
switch s := seen.(type) {
case *semantic.Pointer:
if s.Const {
if match := re_const_ptr_pre.FindStringSubmatch(expected); match != nil {
return VerifyType(cmd, paramIndex, match[1], s.To)
}
if match := re_const_ptr_post.FindStringSubmatch(expected); match != nil {
return VerifyType(cmd, paramIndex, match[1], s.To)
}
} else {
if strings.HasSuffix(expected, "*") {
return VerifyType(cmd, paramIndex, strings.TrimSuffix(expected, "*"), s.To)
}
}
case *semantic.Pseudonym:
if s.Name() == expected {
return true
} else if expected == "GLDEBUGPROCKHR" && s.Name() == "GLDEBUGPROC" {
return true
} else {
return VerifyType(cmd, paramIndex, expected, s.To)
}
case *semantic.Enum:
if s.Name() == expected {
return true
}
case *semantic.Builtin:
if s.Name() == expected {
return true
} else if expected == "const GLchar *" && s.Name() == "string" {
return true
}
}
PrintError("%s: Param %v: Expected type %s but seen %s (%T)\n", cmd, paramIndex, expected, name, seen)
return false
}
func UniqueStrings(strs []string) (res []string) {
seen := map[string]struct{}{}
for _, str := range strs {
if _, ok := seen[str]; !ok {
res = append(res, str)
seen[str] = struct{}{}
}
}
return
}
func VerifyCommand(reg *Registry, cmd *Command) {
cmdName := cmd.Name()
versions := append(reg.GetVersions(GLES1API, cmdName), reg.GetVersions(GLES2API, cmdName)...)
extensions := append(reg.GetExtensions(GLES1API, cmdName), reg.GetExtensions(GLES2API, cmdName)...)
extensions = UniqueStrings(extensions)
if len(versions) == 0 && len(extensions) == 0 {
return // It is not a GLES command.
}
// Expected annotations.
annots := []string{}
if strings.HasPrefix(cmdName, "glDraw") && !strings.HasPrefix(cmdName, "glDrawBuffers") {
annots = append(annots, "@draw_call")
}
for _, version := range versions {
if version == Version("1.0") && len(versions) > 1 {
continue // TODO: Add those in the api file.
}
url, _ := GetCoreManpage(version, cmdName)
annots = append(annots, fmt.Sprintf(`@doc("%s", Version.GLES%v)`, url, strings.Replace(string(version), ".", "", -1)))
}
for _, extension := range extensions {
url, _ := GetExtensionManpage(extension)
annots = append(annots, fmt.Sprintf(`@doc("%s", Extension.%v)`, url, extension))
}
if len(versions) != 0 {
cond := fmt.Sprintf(`Version.GLES%v`, strings.Replace(string(versions[0]), ".", "", -1))
if len(versions) == 1 && versions[0] == Version("1.0") {
cond = "Version.GLES10 && !Version.GLES20" // Deprecated in GLES20
}
annots = append(annots, fmt.Sprintf(`@if(%v)`, cond))
}
if len(extensions) != 0 {
conds := []string{}
for _, extension := range extensions {
conds = append(conds, fmt.Sprintf(`Extension.%v`, extension))
}
annots = append(annots, fmt.Sprintf("@if(%s)", strings.Join(conds, " || ")))
}
// Find existing API function.
var apiCmd *semantic.Function
for _, apiFunction := range apiRoot.Functions {
if apiFunction.Name() == cmdName {
apiCmd = apiFunction
}
}
// Print command to stdout if it is missing.
if apiCmd == nil {
params := []string{}
for _, param := range cmd.Param {
params = append(params, param.Type()+" "+param.Name)
}
fmt.Printf("%s\ncmd %s %s(%s) { }\n", strings.Join(annots, "\n"),
cmd.Proto.Type(), cmdName, strings.Join(params, ", "))
return
}
// Check documentation strings.
expected := make(map[string]struct{})
for _, a := range annots {
expected[a] = struct{}{}
}
seen := make(map[string]struct{})
for _, a := range apiCmd.Annotations {
if a.Name() == "if" || a.Name() == "doc" || a.Name() == "draw_call" {
seen[getSource(mappings.AST.CST(a.AST))] = struct{}{}
}
}
CompareSets(expected, seen, fmt.Sprintf("%s: ", cmdName))
// Check parameter types.
if len(cmd.Param) != len(apiCmd.CallParameters()) {
PrintError("%s: Expected %v parameters but seen %v\n", cmdName, len(cmd.Param), len(apiCmd.CallParameters()))
} else {
for i, p := range cmd.Param {
VerifyType(cmdName, i, p.Type(), apiCmd.FullParameters[i].Type)
}
}
}
func getSource(n cst.Node) string {
return string(n.Tok().Source.Runes[n.Tok().Start:n.Tok().End])
}
|
[
0,
4,
5
] |
// Copyright 2017 Tomas Machalek <[email protected]>
//
// 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 tokenizer
import (
"bufio"
"github.com/tomachalek/gloomy/index/builder/files"
"github.com/tomachalek/vertigo"
"golang.org/x/text/encoding/charmap"
"golang.org/x/text/transform"
"io"
"log"
"regexp"
"strings"
)
const (
channelChunkSize = 250000 // changing the value affects performance (TODO how much?)
)
type simpleTokenizer struct {
lineRegexp *regexp.Regexp
charset *charmap.Charmap
}
func (st *simpleTokenizer) parseLine(s string) []string {
tmp := strings.TrimSpace(importString(s, st.charset))
return st.lineRegexp.Split(tmp, -1)
}
// ParseSource parses a text provided via a specified reader object
// (typically a file) and charset.
func (st *simpleTokenizer) parseSource(source io.Reader, lproc vertigo.LineProcessor) error {
brd := bufio.NewScanner(source)
ch := make(chan []interface{})
chunk := make([]interface{}, channelChunkSize)
go func() {
i := 0
for brd.Scan() {
line := st.parseLine(brd.Text())
for _, token := range line {
if token != "" {
chunk[i] = &vertigo.Token{Word: token}
i++
if i == channelChunkSize {
i = 0
ch <- chunk
chunk = make([]interface{}, channelChunkSize)
}
}
}
}
if i > 0 {
ch <- chunk[:i]
}
close(ch)
}()
for tokens := range ch {
for _, token := range tokens {
switch token.(type) {
case *vertigo.Token:
tk := token.(*vertigo.Token)
lproc.ProcToken(tk)
}
}
}
return nil
}
func importString(s string, ch *charmap.Charmap) string {
if ch == nil { // we assume utf-8 here (default Gloomy encoding)
return strings.ToLower(s)
}
ans, _, _ := transform.String(ch.NewDecoder(), s)
return strings.ToLower(ans)
}
func newSimpleTokenizer(charsetName string) (*simpleTokenizer, error) {
chm, chErr := vertigo.GetCharmapByName(charsetName)
if chErr != nil {
return nil, chErr
}
log.Printf("Configured conversion from charset %s", chm)
cr := regexp.MustCompile("[,\\.\\s;\\?\\!:]+")
return &simpleTokenizer{
lineRegexp: cr,
charset: chm,
}, nil
}
// ParseFile parses a file described (path + encoding) in a provided configuration file
// passing the data to LineProcessor.
func ParseFile(conf *vertigo.ParserConf, lproc vertigo.LineProcessor) error {
st, stErr := newSimpleTokenizer(conf.Encoding)
if stErr != nil {
return stErr
}
rd, err := files.NewReader(conf.InputFilePath)
if err == nil {
return st.parseSource(rd, lproc)
}
return err
}
|
[
7
] |
package controllers
import (
"net/http"
"strconv"
"github.com/anishmgoyal/calagora/models"
"github.com/anishmgoyal/calagora/utils"
)
type searchViewData struct {
Listings []models.Listing `json:"listings"`
Query string `json:"query"`
Page int `json:"page"`
StartOffset int `json:"start_offset"`
EndOffset int `json:"end_offset"`
MaxTotal int `json:"max_total"`
OutOf int `json:"out_of"`
}
// Search handles the route '/search/'
func Search(w http.ResponseWriter, r *http.Request) {
viewData := BaseViewData(w, r)
termMap := utils.GetSearchTermsForString(r.FormValue("q"), true)
terms := make([]string, len(termMap))
i := 0
for term := range termMap {
terms[i] = term
i++
}
pageNumStr := "1"
if len(r.FormValue("page")) > 0 {
pageNumStr = r.FormValue("page")
}
page, err := strconv.Atoi(pageNumStr)
if err != nil {
viewData.NotFound(w)
return
}
// Correct for the human readable format for page numbers used
// by the client here
page = page - 1
placeID := -1
if viewData.Session != nil {
placeID = viewData.Session.User.PlaceID
}
listings := []models.Listing{}
if len(terms) > 0 {
listings, err = models.DoSearchForTerms(Base.Db, terms, page, placeID)
if err != nil {
viewData.InternalError(w)
return
}
}
numPages := models.GetPageCountForTerms(Base.Db, terms, placeID)
viewData.Data = searchViewData{
Listings: listings,
Query: r.FormValue("q"),
Page: page + 1,
StartOffset: page*50 + 1,
EndOffset: page*50 + len(listings),
MaxTotal: numPages * 50,
OutOf: numPages,
}
RenderView(w, "search#search", viewData)
}
|
[
0
] |
package main
import (
"fmt"
"sort"
"adventofcode.com/misha/shared"
)
func main() {
numberStrings := shared.ReadFileLines("day5/input.txt")
numbers := make([]int, len(numberStrings))
for i := range numberStrings {
numbers[i] = 0
for j := range numberStrings[i] {
numbers[i] = numbers[i] << 1
if numberStrings[i][j] == 'B' || numberStrings[i][j] == 'R' {
numbers[i]++
}
}
}
sort.Ints(numbers)
max := 0
for i := range numbers {
if numbers[i] > max {
max = numbers[i]
}
}
fmt.Println(max)
sort.Ints(numbers)
previous := -1
for i := range numbers {
if previous == numbers[i]-2 {
break
}
previous = numbers[i]
}
fmt.Println(previous + 1)
}
|
[
0
] |
/*
* Copyright 2020 Aletheia Ware LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* 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 main
import (
"crypto/rsa"
"fmt"
"github.com/AletheiaWareLLC/aliasgo"
"github.com/AletheiaWareLLC/bcgo"
"github.com/AletheiaWareLLC/conveygo"
"github.com/golang/protobuf/proto"
"html/template"
"log"
"net/http"
"sort"
"strconv"
)
/* Token Bundles:
- 25 tokens for 50c ($0.02 each)
- 100 tokens for $1 ($0.01 each)
- 1250 tokens for $10 ($0.008 each)
- 20000 tokens for $100 ($0.005 each)
- 1000000 tokens for $1000 ($0.001 each)
*/
const (
ERROR_INVALID_TOKEN_QUANTITY = "Invalid token quantity: %d"
ERROR_NO_SUCH_ALIAS = "No such alias: %s"
ERROR_NO_SUCH_PRODUCT = "No such product: %s"
ERROR_NOT_ENOUGH_TOKENS_AVAILABLE = "Not enough tokens available: %d requested, %d available"
)
type TokenPurchaseTemplate struct {
Error string
TokenBundle []*TokenBundle
PaymentMethod []*PaymentMethod
}
type TokenBundle struct {
ID string
Quantity uint64
Price string
UnitPrice string
}
func TokenPurchaseHandler(sessions SessionStore, users conveygo.UserStore, payments PaymentProcessor, ledger *conveygo.Ledger, node *bcgo.Node, template *template.Template, productIds []string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.RemoteAddr, r.Proto, r.Method, r.Host, r.URL.Path, r.Header)
// If not signed in, redirect to sign in page
cookie, err := GetSignInSessionCookie(r)
if err == nil {
session := sessions.GetSignInSession(cookie.Value)
if session != nil {
id, err := sessions.RefreshSignInSession(session)
if err == nil {
http.SetCookie(w, CreateSignInSessionCookie(id, sessions.GetSignInSessionTimeout()))
}
registration, err := users.GetRegistration(session.Alias)
if err != nil {
// TODO(v2) if user exists but not registered as customer offer registration flow
log.Println(err)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
available := ledger.GetBalance(node.Alias)
if session.TokenPurchase == nil {
session.TokenPurchase = &TokenPurchaseSession{}
}
s := session.TokenPurchase
switch r.Method {
case "GET":
s.Product, err = payments.GetProducts(productIds)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
data := &TokenPurchaseTemplate{
Error: s.Error,
}
for _, p := range s.Product {
if p.Quantity <= uint64(available) {
price := float64(p.Price)
unit := price / float64(p.Quantity)
data.TokenBundle = append(data.TokenBundle, &TokenBundle{
ID: p.ID,
Quantity: p.Quantity,
Price: fmt.Sprintf("$%.2f", price/100),
UnitPrice: fmt.Sprintf("$%s", strconv.FormatFloat(unit/100, 'f', -1, 64)),
})
}
}
sort.Slice(data.TokenBundle, func(i, j int) bool {
return data.TokenBundle[i].Quantity < data.TokenBundle[j].Quantity
})
if registration != nil {
data.PaymentMethod, err = payments.GetPaymentMethods(registration.CustomerId)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
}
if err := template.Execute(w, data); err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
return
case "POST":
s.Error = ""
productId := r.FormValue("product")
paymentMethodId := r.FormValue("payment-method")
product, ok := s.Product[productId]
if !ok {
s.Error = fmt.Sprintf(ERROR_NO_SUCH_PRODUCT, productId)
RedirectTokenPurchase(w, r)
return
}
if product.Quantity > uint64(available) {
s.Error = fmt.Sprintf(ERROR_NOT_ENOUGH_TOKENS_AVAILABLE, product.Quantity, available)
RedirectTokenPurchase(w, r)
return
}
_, err := payments.NewPaymentIntent(registration.CustomerId, paymentMethodId, session.Alias, fmt.Sprintf("%d Convey Tokens", product.Quantity), int64(product.Quantity), int64(product.Price))
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
RedirectPurchased(w, r)
return
default:
log.Println("Unsupported method", r.Method)
}
}
}
RedirectSignIn(w, r)
}
}
func TokenSubscriptionHandler(sessions SessionStore, users conveygo.UserStore, payments PaymentProcessor, node *bcgo.Node, template *template.Template, productId, planId string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.RemoteAddr, r.Proto, r.Method, r.Host, r.URL.Path, r.Header)
// If not signed in, redirect to sign in page
cookie, err := GetSignInSessionCookie(r)
if err == nil {
session := sessions.GetSignInSession(cookie.Value)
if session != nil {
id, err := sessions.RefreshSignInSession(session)
if err == nil {
http.SetCookie(w, CreateSignInSessionCookie(id, sessions.GetSignInSessionTimeout()))
}
switch r.Method {
case "GET":
// TODO(v3)
return
case "POST":
// TODO(v3)
RedirectSubscribed(w, r)
return
default:
log.Println("Unsupported method", r.Method)
}
}
}
RedirectSignIn(w, r)
}
}
type TokenTransferTemplate struct {
Error string
Available int64
}
func TokenTransferHandler(sessions SessionStore, users conveygo.UserStore, ledger *conveygo.Ledger, aliases, transactions *bcgo.Channel, node *bcgo.Node, listener bcgo.MiningListener, template *template.Template) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.RemoteAddr, r.Proto, r.Method, r.Host, r.URL.Path, r.Header)
// If not signed in, redirect to sign in page
cookie, err := GetSignInSessionCookie(r)
if err == nil {
session := sessions.GetSignInSession(cookie.Value)
if session != nil {
id, err := sessions.RefreshSignInSession(session)
if err == nil {
http.SetCookie(w, CreateSignInSessionCookie(id, sessions.GetSignInSessionTimeout()))
}
available := ledger.GetBalance(session.Alias)
if session.TokenTransfer == nil {
session.TokenTransfer = &TokenTransferSession{}
}
s := session.TokenTransfer
switch r.Method {
case "GET":
data := &TokenTransferTemplate{
Error: s.Error,
Available: available,
}
if err := template.Execute(w, data); err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
return
case "POST":
s.Error = ""
quantity := r.FormValue("quantity")
recipient := r.FormValue("recipient")
q, err := strconv.Atoi(quantity)
if err != nil {
s.Error = err.Error()
} else if q <= 0 {
s.Error = fmt.Sprintf(ERROR_INVALID_TOKEN_QUANTITY, q)
} else if int64(q) > available {
s.Error = fmt.Sprintf(ERROR_NOT_ENOUGH_TOKENS_AVAILABLE, q, available)
} else {
_, err := aliasgo.GetPublicKey(aliases, node.Cache, node.Network, recipient)
if err != nil {
s.Error = fmt.Sprintf(ERROR_NO_SUCH_ALIAS, recipient)
} else {
if err := MineTransaction(node, listener, transactions, session.Alias, session.Key, recipient, uint64(q)); err != nil {
s.Error = err.Error()
} else {
RedirectTransfered(w, r)
return
}
}
}
RedirectTokenTransfer(w, r)
return
default:
log.Println("Unsupported method", r.Method)
}
}
}
RedirectSignIn(w, r)
}
}
func MineTransaction(node *bcgo.Node, listener bcgo.MiningListener, transactions *bcgo.Channel, senderAlias string, senderKey *rsa.PrivateKey, recipient string, amount uint64) error {
transaction := &conveygo.Transaction{
Sender: senderAlias,
Receiver: recipient,
Amount: amount,
}
log.Println("Transaction", transaction)
data, err := proto.Marshal(transaction)
if err != nil {
return err
}
_, record, err := bcgo.CreateRecord(bcgo.Timestamp(), senderAlias, senderKey, nil, nil, data)
if err != nil {
return err
}
log.Println("Record", record)
if _, err := bcgo.WriteRecord(transactions.Name, node.Cache, record); err != nil {
return err
}
if _, _, err := node.Mine(transactions, bcgo.THRESHOLD_G, listener); err != nil {
return err
}
if err := transactions.Push(node.Cache, node.Network); err != nil {
return err
}
return nil
}
|
[
5
] |
// Copyright 2016 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, 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 helpers
import (
"bytes"
"sync"
"github.com/kyokomi/emoji/v2"
)
var (
emojiInit sync.Once
emojis = make(map[string][]byte)
emojiDelim = []byte(":")
emojiWordDelim = []byte(" ")
emojiMaxSize int
)
// Emoji returns the emoji given a key, e.g. ":smile:", nil if not found.
func Emoji(key string) []byte {
emojiInit.Do(initEmoji)
return emojis[key]
}
// Emojify "emojifies" the input source.
// Note that the input byte slice will be modified if needed.
// See http://www.emoji-cheat-sheet.com/
func Emojify(source []byte) []byte {
emojiInit.Do(initEmoji)
start := 0
k := bytes.Index(source[start:], emojiDelim)
for k != -1 {
j := start + k
upper := j + emojiMaxSize
if upper > len(source) {
upper = len(source)
}
endEmoji := bytes.Index(source[j+1:upper], emojiDelim)
nextWordDelim := bytes.Index(source[j:upper], emojiWordDelim)
if endEmoji < 0 {
start++
} else if endEmoji == 0 || (nextWordDelim != -1 && nextWordDelim < endEmoji) {
start += endEmoji + 1
} else {
endKey := endEmoji + j + 2
emojiKey := source[j:endKey]
if emoji, ok := emojis[string(emojiKey)]; ok {
source = append(source[:j], append(emoji, source[endKey:]...)...)
}
start += endEmoji
}
if start >= len(source) {
break
}
k = bytes.Index(source[start:], emojiDelim)
}
return source
}
func initEmoji() {
emojiMap := emoji.CodeMap()
for k, v := range emojiMap {
emojis[k] = []byte(v)
if len(k) > emojiMaxSize {
emojiMaxSize = len(k)
}
}
}
|
[
5
] |
package lb_util
import (
"dynamicpath/lib/up_topology"
"dynamicpath/src/load_balancer/lb_context"
"dynamicpath/src/load_balancer/logger"
)
type PathListType string
const (
WorstPath PathListType = "WorstPath"
BestPath PathListType = "BestPath"
)
func pathMerge(leftPaths, rightPaths []up_topology.Path) {
leftLen, rightLen := len(leftPaths), len(rightPaths)
leftIndex, rightIndex := 0, 0
var sortedPath []up_topology.Path
for i := 0; i < rightLen+leftLen; i++ {
if leftIndex == leftLen {
sortedPath = append(sortedPath, rightPaths[rightIndex:]...)
break
} else if rightIndex == rightLen {
sortedPath = append(sortedPath, leftPaths[leftIndex:]...)
break
} else if *leftPaths[leftIndex].Cost < *rightPaths[rightIndex].Cost {
sortedPath = append(sortedPath, leftPaths[leftIndex])
leftIndex++
} else {
sortedPath = append(sortedPath, rightPaths[rightIndex])
rightIndex++
}
}
for i := 0; i < leftLen; i++ {
leftPaths[i] = sortedPath[i]
}
for i := 0; i < rightLen; i++ {
rightPaths[i] = sortedPath[leftLen+i]
}
}
func dpUpdateCost(path up_topology.Path) {
self := lb_context.LB_Self()
*path.Cost = 0
for _, edge := range path.Edges {
upf := self.UPFInfos[edge.Start.NodeId]
if upf != nil {
ethName := upf.RemoteIpMaps[edge.EndIp]
*path.Cost = *path.Cost + (1-*edge.Start.RemainRates[lb_context.GetIfaceTxName(ethName)]/upf.InterfaceInfos[ethName].TotalBandwidth.Tx)*100
}
upf = self.UPFInfos[edge.End.NodeId]
if upf != nil {
ethName := upf.RemoteIpMaps[edge.StartIp]
*path.Cost = *path.Cost + (1-*edge.End.RemainRates[lb_context.GetIfaceRxName(ethName)]/upf.InterfaceInfos[ethName].TotalBandwidth.Rx)*100
}
}
}
func PathMergeSort(pathList []up_topology.Path) {
if len(pathList) > 1 {
middle := len(pathList) / 2
leftPaths := pathList[:middle]
rightPaths := pathList[middle:]
PathMergeSort(leftPaths)
PathMergeSort(rightPaths)
pathMerge(leftPaths, rightPaths)
}
}
func GetSubPathList(pathList []up_topology.Path, types PathListType) (subPath []up_topology.Path, mean float64) {
if len(pathList) < 1 {
return nil, 0.0
}
mean = PathRemainRateMean(pathList)
switch types {
case WorstPath:
for _, path := range pathList {
if *path.RemainRate <= mean {
subPath = append(subPath, path)
}
}
case BestPath:
for _, path := range pathList {
if *path.RemainRate >= mean {
subPath = append(subPath, path)
}
}
}
return
}
func PathRemainRateMean(pathList []up_topology.Path) float64 {
sum := 0.0
// overLoadCnt := 0
for _, path := range pathList {
// if *path.Overload {
// overLoadCnt++
// continue
// }
sum = sum + *path.RemainRate
}
// n := len(pathList) - overLoadCnt
// if n == 0 {
// return 0.0
// }
return sum / float64(len(pathList))
}
func InitAllPath() {
self := lb_context.LB_Self()
for i, path := range self.Topology.PathListAll {
for _, edge := range path.Edges {
// Init Path Link To Node Remain Rate
// Only Record consider Uplink for one path
upf := self.UPFInfos[edge.Start.NodeId]
if upf != nil {
ethName := upf.RemoteIpMaps[edge.EndIp]
path.RemainRates = append(path.RemainRates, edge.Start.RemainRates[lb_context.GetIfaceTxName(ethName)])
}
upf = self.UPFInfos[edge.End.NodeId]
if upf != nil {
ethName := upf.RemoteIpMaps[edge.StartIp]
path.RemainRates = append(path.RemainRates, edge.End.RemainRates[lb_context.GetIfaceRxName(ethName)])
}
}
path.Id = i
self.Topology.PathInfos[i] = &lb_context.PathInfos{
Path: path,
PduSessionInfo: make(map[string]*lb_context.PduSessionContext),
}
self.Topology.PathListAll[i] = path
logger.UtilLog.Debugf("pathId: %d , nodes: %v", i, path.NodeIdList)
}
}
func FindPathThreshold(pathList []up_topology.Path) int {
middle := len(pathList)/2 - (1 - len(pathList)%2)
if !*pathList[middle].Overload {
return middle
}
left, right := 0, middle-1
for left <= right {
middle = (left + right) / 2
if *pathList[middle].Overload {
right = middle - 1
} else {
left = middle + 1
}
}
return right
}
|
[
0,
5
] |
package main
import "fmt"
func main() {
var n, m int
fmt.Scan(&n, &m)
A := make([]int, n)
B := make([]int, m)
for i := 0; i < n; i++ {
fmt.Scan(&A[i])
}
for i := 0; i < m; i++ {
fmt.Scan(&B[i])
}
var min int
for i := 0; i < n; i++ {
if min < A[i] {
min = A[i]
}
}
var max int = B[0]
for i := 0; i < n; i++ {
if max < A[i] {
max = A[i]
}
}
var x int = min
var ax, bx, X int
for min <= x && x <= max {
for i := 0; i < n; i++ {
if x%A[i] == 0 {
ax = ax + 1
}
}
for i := 0; i < m; i++ {
if B[i]%x == 0 {
bx = bx + 1
}
}
if ax == n && bx == m {
X = X + 1
}
ax = 0
bx = 0
x = x + min
}
fmt.Print(X)
}
|
[
0,
1
] |
package timing
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var randomPercentile int
var randomVariance int
func pseudoRandom(max int) int {
switch max {
case 100:
return randomPercentile
default:
return randomVariance
}
}
func setup(t *testing.T, p int) *RequestDuration {
randomPercentile = p
randomVariance = 10
return &RequestDuration{
percentile50: 1 * time.Millisecond,
percentile90: 2 * time.Millisecond,
percentile99: 3 * time.Millisecond,
variance: randomVariance,
randomFunc: pseudoRandom,
}
}
func TestGenerates50Percentile(t *testing.T) {
rd := setup(t, 50)
d := rd.Calculate()
assert.Equal(t, 1100*time.Microsecond, d)
}
func TestGenerates90Percentile(t *testing.T) {
rd := setup(t, 90)
d := rd.Calculate()
assert.Equal(t, 2200*time.Microsecond, d)
}
func TestGenerates99Percentile(t *testing.T) {
rd := setup(t, 99)
d := rd.Calculate()
assert.Equal(t, 3300*time.Microsecond, d)
}
|
[
1
] |
package ping
import (
"crypto/tls"
"encoding/csv"
"fmt"
"log"
"net/http"
"net/http/httptrace"
"os"
"runtime"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/fatih/color"
)
const (
httpsTemplate = `` +
` DNS Lookup TCP Connection TLS Handshake Server Processing Content Transfer` + "\n" +
`[%s | %s | %s | %s | %s ]` + "\n" +
` | | | | |` + "\n" +
` namelookup:%s | | | |` + "\n" +
` connect:%s | | |` + "\n" +
` pretransfer:%s | |` + "\n" +
` starttransfer:%s |` + "\n" +
` total:%s` + "\n"
)
// CmdOption is to save cmd option
type CmdOption struct {
Option string
OptionName string
ListFlg bool
Args []string
}
// StartCmd is to excute functions and differentiate report depends on cmd option
func (c *CmdOption) StartCmd() {
var regions = make(map[string]string)
var endpoints = make(map[string]string)
var err error
var csvpath string
homedir := os.Getenv("PINGCLOUD_DIR")
fmt.Println("")
// Read endpoints
if runtime.GOOS == "windows" {
csvpath = fmt.Sprintf("\\endpoints\\%s.csv", c.Option)
} else {
csvpath = fmt.Sprintf("/endpoints/%s.csv", c.Option)
}
regions, endpoints, err = ReadEndpoints(homedir + csvpath)
if err != nil {
log.Fatal(err)
}
if c.ListFlg {
// Init tabwriter
tr := tabwriter.NewWriter(os.Stdout, 40, 8, 2, '\t', 0)
fmt.Fprintf(tr, "%s Region Code\t%s Region Name", c.OptionName, c.OptionName)
fmt.Fprintln(tr)
fmt.Fprintf(tr, "------------------------------\t------------------------------")
fmt.Fprintln(tr)
for r, n := range regions {
fmt.Fprintf(tr, "[%v]\t[%v]", r, n)
fmt.Fprintln(tr)
}
// Flush tabwriter
tr.Flush()
} else if len(c.Args) == 0 {
// Init tabwriter
tr := tabwriter.NewWriter(os.Stdout, 40, 8, 2, '\t', 0)
fmt.Fprintf(tr, "%s Region Code\t%s Region Name\tLatency", c.OptionName, c.OptionName)
fmt.Fprintln(tr)
fmt.Fprintf(tr, "------------------------------\t------------------------------\t------------------------------")
fmt.Fprintln(tr)
// Flush tabwriter
tr.Flush()
for r, i := range endpoints {
p := PingDto{
Region: r,
Name: regions[r],
Address: i,
}
p.Ping()
}
fmt.Println("")
fmt.Println("You can also add region after command if you want http trace information of the specific region")
if c.Option == "gcp" {
fmt.Printf("ex> pingcloud-cli %s us-central1\n", c.Option)
} else if c.Option == "aws" {
fmt.Printf("ex> pingcloud-cli %s us-east-1\n", c.Option)
} else if c.Option == "azure" {
fmt.Printf("ex> pingcloud-cli %s koreasouth\n", c.Option)
}
} else {
for _, r := range c.Args {
if i, ok := endpoints[r]; ok {
p := PingDto{
Region: r,
Name: endpoints[r],
Address: i,
}
p.VerbosePing()
} else {
fmt.Printf("Region code [%v] is wrong. To check available region codes run the command with -l or --list flag\n", r)
fmt.Printf("Usage: pingcloud-cli %s -l\n", c.Option)
fmt.Printf("Usage: pingcloud-cli %s --list\n", c.Option)
}
}
}
fmt.Println("")
}
// ReadEndpoints parse CSV file into map of region names and endpoints
func ReadEndpoints(filename string) (map[string]string, map[string]string, error) {
region := make(map[string]string)
endpoints := make(map[string]string)
// Open CSV file
f, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer f.Close()
// Read File into a Variable
lines, err := csv.NewReader(f).ReadAll()
if err != nil {
log.Fatal(err)
}
for i, line := range lines {
if i != 0 {
region[line[0]] = line[1]
endpoints[line[0]] = line[2]
}
}
return region, endpoints, err
}
// PingDto is for endpoint and reponse time information
type PingDto struct {
Region string
Name string
Address string
Latency time.Duration
}
// TestPrint prints the PingDto struct.
func (p *PingDto) TestPrint() {
fmt.Println("Region: " + p.Region)
fmt.Println("Name: " + p.Name)
fmt.Println("Address: " + p.Address)
}
// Ping Send HTTP(S) request to endpoint and report its response time
func (p *PingDto) Ping() {
// Init tabwriter
tr := tabwriter.NewWriter(os.Stdout, 40, 8, 2, '\t', 0)
// Ping start time
start := time.Now()
// Create a new HTTP request
req, err := http.NewRequest("GET", p.Address, nil)
if err != nil {
log.Fatal(err)
}
// Send request by default HTTP client
client := http.DefaultClient
res, err := client.Do(req)
if err != nil || res == nil {
log.Fatal(err)
}
if res.StatusCode != http.StatusOK {
fmt.Fprintf(tr, "[%v]\t[%v]\tPing failed with status code: %v", p.Region, p.Name, res.StatusCode)
fmt.Fprintln(tr)
} else {
p.Latency = time.Since(start)
lowLatency, _ := time.ParseDuration("200ms")
highLatency, _ := time.ParseDuration("999ms")
if p.Latency < lowLatency {
fmt.Fprintf(tr, "[%v]\t[%v]\t%v", p.Region, p.Name, color.GreenString(p.Latency.String()))
} else if p.Latency < highLatency {
fmt.Fprintf(tr, "[%v]\t[%v]\t%v", p.Region, p.Name, color.YellowString(p.Latency.String()))
} else {
fmt.Fprintf(tr, "[%v]\t[%v]\t%v", p.Region, p.Name, color.RedString(p.Latency.String()))
}
fmt.Fprintln(tr)
}
// Flush tabwriter
tr.Flush()
}
// VerbosePing send HTTP(S) request to endpoint and report its respons time in httpstat style
func (p *PingDto) VerbosePing() {
// Create a new HTTP request
req, err := http.NewRequest("GET", p.Address, nil)
if err != nil {
log.Fatal(err)
}
var dnsStart, dnsEnd, tcpConnectStart, tcpConnectEnd, tlsHandshakeStart, tlsHandshakeEnd, serverStart, serverEnd, httpEnd time.Time
trace := &httptrace.ClientTrace{
DNSStart: func(dsi httptrace.DNSStartInfo) { dnsStart = time.Now() },
DNSDone: func(ddi httptrace.DNSDoneInfo) {
dnsEnd = time.Now()
},
ConnectStart: func(network, addr string) {
tcpConnectStart = time.Now()
if dnsStart.IsZero() {
dnsStart = tcpConnectStart
dnsEnd = tcpConnectStart
}
},
ConnectDone: func(network, addr string, err error) {
tcpConnectEnd = time.Now()
},
TLSHandshakeStart: func() { tlsHandshakeStart = time.Now() },
TLSHandshakeDone: func(cs tls.ConnectionState, err error) {
tlsHandshakeEnd = time.Now()
},
WroteRequest: func(info httptrace.WroteRequestInfo) {
serverStart = time.Now()
if tlsHandshakeStart.IsZero() {
tlsHandshakeStart = serverStart
tlsHandshakeEnd = serverStart
}
},
GotFirstResponseByte: func() {
serverEnd = time.Now()
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
if _, err := http.DefaultTransport.RoundTrip(req); err != nil {
log.Fatal(err)
}
httpEnd = time.Now()
t := TimeTrace{
DNSLookup: dnsEnd.Sub(dnsStart),
TCPConnect: tcpConnectEnd.Sub(tcpConnectStart),
TLSHandshake: tlsHandshakeEnd.Sub(tlsHandshakeStart),
ServerProcess: serverEnd.Sub(serverStart),
ContentTransfer: httpEnd.Sub(serverEnd),
NameLookup: dnsEnd.Sub(dnsStart),
ConnectTotal: tcpConnectEnd.Sub(dnsStart),
PreTransfer: tlsHandshakeEnd.Sub(dnsStart),
StartTransfer: serverEnd.Sub(dnsStart),
TotalTime: httpEnd.Sub(dnsStart),
}
fmt.Println("")
fmt.Printf("HTTP(S) trace of region [%v] - %v\n", p.Region, p.Name)
fmt.Println("-------------------------------------------------------------------------------------------")
t.PrintHttpTrace()
fmt.Println("-------------------------------------------------------------------------------------------")
}
// TimeTrace will be used for report httpstat
type TimeTrace struct {
DNSLookup time.Duration
TCPConnect time.Duration
TLSHandshake time.Duration
ServerProcess time.Duration
ContentTransfer time.Duration
NameLookup time.Duration
ConnectTotal time.Duration
PreTransfer time.Duration
StartTransfer time.Duration
TotalTime time.Duration
}
// PrintHttpTrace prints TimeTrace struct in httpstat style
// This function's codes are from https://github.com/reoim/httpstat-1
// They are slightly different from the original codes. But I used the same template and print format.
func (t *TimeTrace) PrintHttpTrace() {
fmta := func(d time.Duration) string {
return color.CyanString("%7dms", int(d/time.Millisecond))
}
fmtb := func(d time.Duration) string {
return color.CyanString("%-9s", strconv.Itoa(int(d/time.Millisecond))+"ms")
}
colorize := func(s string) string {
v := strings.Split(s, "\n")
v[0] = grayscale(16)(v[0])
return strings.Join(v, "\n")
}
printf(colorize(httpsTemplate),
fmta(t.DNSLookup),
fmta(t.TCPConnect),
fmta(t.TLSHandshake),
fmta(t.ServerProcess),
fmta(t.ContentTransfer),
fmtb(t.DNSLookup),
fmtb(t.ConnectTotal),
fmtb(t.PreTransfer),
fmtb(t.StartTransfer),
fmtb(t.TotalTime),
)
}
func printf(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(color.Output, format, a...)
}
func grayscale(code color.Attribute) func(string, ...interface{}) string {
return color.New(code + 232).SprintfFunc()
}
|
[
5
] |
package quoteprintable
import (
"fmt"
"io"
)
// 目标容量不足的错误,其值表示源被消费的字节数
type CapacityShortageError int
// 实现error接口
func (d CapacityShortageError) Error() string {
return fmt.Sprintf("lack of capacity error at %d", int(d))
}
// 源数据不完整的错误,其值表示源下一应被解码的字节索引
type IncompleteInputError int
// 实现error接口
func (d IncompleteInputError) Error() string {
return fmt.Sprintf("incomplete input error at %d", int(d))
}
// 源数据的格式错误,其值表示源下一应被解码的字节索引
type CorruptInputError int
// 实现error接口
func (d CorruptInputError) Error() string {
return fmt.Sprintf("corrupt input error at %d", int(d))
}
// 代表一个quote printable编解码器
type Encoding int
func (e *Encoding) encode(dst, src []byte) (int, int, int) {
fac := func(c byte) byte {
if c < 10 {
return c + '0'
}
return c + ('A' - 10)
}
t := *e
defer func() { *e = t }()
i, j, a, b := 0, 0, len(dst), len(src)
for j < b {
c := src[j]
if (c > 32 && c < 61) || (c > 61 && c < 127) {
if t >= 75 {
if i+2 >= a {
return 1, i, j
}
copy(dst[i:], "=\r\n")
i, t = i+3, 0
}
if i >= a {
return 1, i, j
}
dst[i] = c
i, t = i+1, t+1
} else {
if t >= 73 {
if i+2 >= a {
return 1, i, j
}
copy(dst[i:], "=\r\n")
i, t = i+3, 0
}
if i+2 >= a {
return 1, i, j
}
dst[i+0] = '='
dst[i+1] = fac(c >> 4)
dst[i+2] = fac(c & 15)
i, t = i+3, t+3
}
j++
}
return 0, i, j
}
func (e *Encoding) decode(dst, src []byte) (int, int, int) {
fac := func(c byte) byte {
if c >= '0' && c <= '9' {
return c - '0'
}
if c >= 'A' && c <= 'F' {
return c - ('A' - 10)
}
return 16
}
t := *e
defer func() { *e = t }()
i, j, a, b := 0, 0, len(dst), len(src)
for j < b {
c := src[j]
if (c > 8 && c < 61) || (c > 61 && c < 127) {
if t+1 > 75 {
return 3, i, j
}
t, j = t+1, j+1
} else if c == '=' {
if j+2 >= b {
return 2, i, j
}
x, y := src[j+1], src[j+2]
if x == '\r' && y == '\n' {
j += 3
t = 0
continue
}
if t+3 > 75 {
return 3, i, j
}
x = fac(x)
if x >= 16 {
return 3, i, j
}
y = fac(y)
if y >= 16 {
return 3, i, j
}
c = (x << 4) & y
t, j = t+3, j+3
} else {
return 3, i, j
}
if i >= a {
return 1, i, j
}
dst[i] = c
i++
}
return 0, i, j
}
// 编码,返回写入dst的字节数和可能的错误
func (e *Encoding) Encode(dst, src []byte) (int, error) {
*e = 0
t, i, j := e.encode(dst, src)
switch t {
case 1:
return i, CapacityShortageError(j)
case 2:
return i, IncompleteInputError(j)
case 3:
return i, CorruptInputError(j)
default:
}
return i, nil
}
// 解码,返回写入dst的字节数和可能的错误
func (e *Encoding) Decode(dst, src []byte) (int, error) {
*e = 0
t, i, j := e.decode(dst, src)
switch t {
case 1:
return i, CapacityShortageError(j)
case 2:
return i, IncompleteInputError(j)
case 3:
return i, CorruptInputError(j)
default:
}
return i, nil
}
type writer struct {
e *Encoding
w io.Writer
m []byte
}
// 实现io.Writer接口
func (p *writer) Write(data []byte) (int, error) {
x := 0
for {
t, i, j := p.e.encode(p.m, data)
n, e := p.w.Write(p.m[:i])
x += n
if e != nil {
return x, e
}
if t == 0 {
break
}
data = data[j:]
}
return x, nil
}
type reader struct {
e *Encoding
r io.Reader
m []byte
o error
n int
}
// 实现io.Reader接口
func (p *reader) Read(data []byte) (int, error) {
if p.o != nil {
return 0, p.o
}
x, y, n := 0, 0, 0
for {
n, p.o = p.r.Read(p.m[p.n:])
p.n += n
t, i, j := p.e.decode(data, p.m[:p.n])
x, y = x+i, y+j
switch t {
case 0:
p.n = 0
if p.o != nil {
return x, p.o
}
case 1:
copy(p.m, p.m[j:p.n])
p.n = 4096 - j
break
case 2:
copy(p.m, p.m[j:p.n])
p.n = 4096 - j
if p.o != nil {
return x, IncompleteInputError(y)
}
default:
return x, CorruptInputError(y)
}
data = data[i:]
}
return x, nil
}
// 返回一个io.Writer接口,所有写入下层的数据都会先编码
func NewEncoder(e *Encoding, w io.Writer) io.Writer {
return &writer{e, w, make([]byte, 4096)}
}
// 返回一个io.Reader接口,所有下层读取的数据都会先解码
func NewDecoder(e *Encoding, r io.Reader) io.Reader {
return &reader{e, r, make([]byte, 4096), nil, 0}
}
|
[
5
] |
package main
import (
"fmt"
"sync"
)
func main() {
// START,OMIT
m := make(map[int]string)
var wg sync.WaitGroup
wg.Add(3)
// PRODUCER 1
go func() {
m[0] = "ANO"
wg.Done()
}()
// PRODUCER 2
x := 0
go func() {
x = x + 1
m[0] = "NE"
wg.Done()
}()
// CONSUMER
go func() {
i := 0
for i < 5 {
fmt.Println(i, m[0])
i++
}
wg.Done()
}()
wg.Wait()
// END,OMIT
_ = x
}
|
[
0
] |
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
)
var sc *bufio.Scanner
func readInt() int {
sc.Scan()
i, _ := strconv.Atoi(sc.Text())
return i
}
func run(r io.Reader) string {
sc = bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
t := readInt()
answers := make([]int, t)
for i := 0; i < t; i++ {
n2, n3, n4 := readInt(), readInt(), readInt()
ans := 0
n3 = n3 / 2
if n3 > n4 {
ans += n4
n3 -= n4
if n3 < n2/2 {
ans += n3
n2 -= n3 * 2
ans += n2 / 5
} else {
ans += n2 / 2
}
} else {
ans += n3
n4 -= n3
n4amari := n4 % 2
n4 = n4 / 2
if n4 < n2 {
ans += n4
n2 -= n4
if n4amari > 0 && n2 >= 3 {
ans++
n2 -= 3
}
ans += n2 / 5
} else {
ans += n2
}
}
answers[i] = ans
}
ret := fmt.Sprintf("%v", answers)
return ret[1 : len(ret)-1]
}
func main() {
fmt.Println(run(os.Stdin))
}
|
[
0
] |
package crud
import (
"fmt"
"reflect"
"github.com/vmihailenco/msgpack/v5"
"github.com/vmihailenco/msgpack/v5/msgpcode"
)
// FieldFormat contains field definition: {name='...',type='...'[,is_nullable=...]}.
type FieldFormat struct {
Name string
Type string
IsNullable bool
}
// DecodeMsgpack provides custom msgpack decoder.
func (format *FieldFormat) DecodeMsgpack(d *msgpack.Decoder) error {
l, err := d.DecodeMapLen()
if err != nil {
return err
}
for i := 0; i < l; i++ {
key, err := d.DecodeString()
if err != nil {
return err
}
switch key {
case "name":
if format.Name, err = d.DecodeString(); err != nil {
return err
}
case "type":
if format.Type, err = d.DecodeString(); err != nil {
return err
}
case "is_nullable":
if format.IsNullable, err = d.DecodeBool(); err != nil {
return err
}
default:
if err := d.Skip(); err != nil {
return err
}
}
}
return nil
}
// Result describes CRUD result as an object containing metadata and rows.
type Result struct {
Metadata []FieldFormat
Rows interface{}
rowType reflect.Type
}
// MakeResult create a Result object with a custom row type for decoding.
func MakeResult(rowType reflect.Type) Result {
return Result{
rowType: rowType,
}
}
func msgpackIsArray(code byte) bool {
return code == msgpcode.Array16 || code == msgpcode.Array32 ||
msgpcode.IsFixedArray(code)
}
// DecodeMsgpack provides custom msgpack decoder.
func (r *Result) DecodeMsgpack(d *msgpack.Decoder) error {
arrLen, err := d.DecodeArrayLen()
if err != nil {
return err
}
if arrLen < 2 {
return fmt.Errorf("array len doesn't match: %d", arrLen)
}
l, err := d.DecodeMapLen()
if err != nil {
return err
}
for i := 0; i < l; i++ {
key, err := d.DecodeString()
if err != nil {
return err
}
switch key {
case "metadata":
metadataLen, err := d.DecodeArrayLen()
if err != nil {
return err
}
metadata := make([]FieldFormat, metadataLen)
for i := 0; i < metadataLen; i++ {
fieldFormat := FieldFormat{}
if err = d.Decode(&fieldFormat); err != nil {
return err
}
metadata[i] = fieldFormat
}
r.Metadata = metadata
case "rows":
if r.rowType != nil {
tuples := reflect.New(reflect.SliceOf(r.rowType))
if err = d.DecodeValue(tuples); err != nil {
return err
}
r.Rows = tuples.Elem().Interface()
} else {
var decoded []interface{}
if err = d.Decode(&decoded); err != nil {
return err
}
r.Rows = decoded
}
default:
if err := d.Skip(); err != nil {
return err
}
}
}
code, err := d.PeekCode()
if err != nil {
return err
}
var retErr error
if msgpackIsArray(code) {
crudErr := newErrorMany(r.rowType)
if err := d.Decode(&crudErr); err != nil {
return err
}
retErr = *crudErr
} else if code != msgpcode.Nil {
crudErr := newError(r.rowType)
if err := d.Decode(&crudErr); err != nil {
return err
}
retErr = *crudErr
} else {
if err := d.DecodeNil(); err != nil {
return err
}
}
for i := 2; i < arrLen; i++ {
if err := d.Skip(); err != nil {
return err
}
}
return retErr
}
// NumberResult describes CRUD result as an object containing number.
type NumberResult struct {
Value uint64
}
// DecodeMsgpack provides custom msgpack decoder.
func (r *NumberResult) DecodeMsgpack(d *msgpack.Decoder) error {
arrLen, err := d.DecodeArrayLen()
if err != nil {
return err
}
if arrLen < 2 {
return fmt.Errorf("array len doesn't match: %d", arrLen)
}
if r.Value, err = d.DecodeUint64(); err != nil {
return err
}
var crudErr *Error = nil
if err := d.Decode(&crudErr); err != nil {
return err
}
for i := 2; i < arrLen; i++ {
if err := d.Skip(); err != nil {
return err
}
}
if crudErr != nil {
return crudErr
}
return nil
}
// BoolResult describes CRUD result as an object containing bool.
type BoolResult struct {
Value bool
}
// DecodeMsgpack provides custom msgpack decoder.
func (r *BoolResult) DecodeMsgpack(d *msgpack.Decoder) error {
arrLen, err := d.DecodeArrayLen()
if err != nil {
return err
}
if arrLen < 2 {
if r.Value, err = d.DecodeBool(); err != nil {
return err
}
return nil
}
if _, err = d.DecodeInterface(); err != nil {
return err
}
var crudErr *Error = nil
if err := d.Decode(&crudErr); err != nil {
return err
}
if crudErr != nil {
return crudErr
}
return nil
}
|
[
5
] |
package linkedin
import (
"gopkg.in/resty.v0"
"log"
)
// Function validates response. If response is not valid returns `false` and call logs with error details
func ValidateResponse(response *resty.Response, err error) bool {
var validation bool
if response.RawResponse.StatusCode != 200 {
log.Println(response.RawResponse.Status + " " + response.Request.URL)
validation = false
} else if err != nil {
log.Println(err)
validation = false
} else {
validation = true
}
return validation
}
|
[
5
] |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE2.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 model
import (
"strings"
"gopkg.in/yaml.v3"
)
// NewOpenAPISchema returns an empty instance of an OpenAPISchema object.
func NewOpenAPISchema() *OpenAPISchema {
return &OpenAPISchema{
Enum: []interface{}{},
Metadata: map[string]string{},
Properties: map[string]*OpenAPISchema{},
Required: []string{},
}
}
// OpenAPISchema declares a struct capable of representing a subset of Open API Schemas
// supported by Kubernetes which can also be specified within Protocol Buffers.
//
// There are a handful of notable differences:
// - The validating constructs `allOf`, `anyOf`, `oneOf`, `not`, and type-related restrictsion are
// not supported as they can be better validated in the template 'validator' block.
// - The $ref field supports references to other schema definitions, but such aliases
// should be removed before being serialized.
// - The `additionalProperties` and `properties` fields are not currently mutually exclusive as is
// the case for Kubernetes.
//
// See: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#validation
type OpenAPISchema struct {
Title string `yaml:"title,omitempty"`
Description string `yaml:"description,omitempty"`
Type string `yaml:"type,omitempty"`
TypeRef string `yaml:"$ref,omitempty"`
DefaultValue interface{} `yaml:"default,omitempty"`
Enum []interface{} `yaml:"enum,omitempty"`
Format string `yaml:"format,omitempty"`
Items *OpenAPISchema `yaml:"items,omitempty"`
Metadata map[string]string `yaml:"metadata,omitempty"`
Required []string `yaml:"required,omitempty"`
Properties map[string]*OpenAPISchema `yaml:"properties,omitempty"`
AdditionalProperties *OpenAPISchema `yaml:"additionalProperties,omitempty"`
}
// ModelType returns the CEL Policy Templates type name associated with the schema element.
func (s *OpenAPISchema) ModelType() string {
commonType := openAPISchemaTypes[s.Type]
switch commonType {
case "string":
switch s.Format {
case "byte", "binary":
return BytesType
case "date", "date-time":
return TimestampType
}
}
return commonType
}
// Equal returns whether two schemas are equal.
func (s *OpenAPISchema) Equal(other *OpenAPISchema) bool {
if s.ModelType() != other.ModelType() {
return false
}
// perform deep equality here.
switch s.ModelType() {
case "any":
return false
case MapType:
if len(s.Properties) != len(other.Properties) {
return false
}
for prop, nested := range s.Properties {
otherNested, found := other.Properties[prop]
if !found || !nested.Equal(otherNested) {
return false
}
}
if s.AdditionalProperties != nil && other.AdditionalProperties != nil &&
!s.AdditionalProperties.Equal(other.AdditionalProperties) {
return false
}
if s.AdditionalProperties != nil && other.AdditionalProperties == nil ||
s.AdditionalProperties == nil && other.AdditionalProperties != nil {
return false
}
return true
case ListType:
return s.Items.Equal(other.Items)
default:
return true
}
}
// FindProperty returns the Open API Schema type for the given property name.
//
// A property may either be explicitly defined in a `properties` map or implicitly defined in an
// `additionalProperties` block.
func (s *OpenAPISchema) FindProperty(name string) (*OpenAPISchema, bool) {
if s.ModelType() == "any" {
return s, true
}
if s.Properties != nil {
prop, found := s.Properties[name]
if found {
return prop, true
}
}
if s.AdditionalProperties != nil {
return s.AdditionalProperties, true
}
return nil, false
}
var (
// SchemaDef defines an Open API Schema definition in terms of an Open API Schema.
SchemaDef *OpenAPISchema
// AnySchema indicates that the value may be of any type.
AnySchema *OpenAPISchema
// InstanceSchema defines a basic schema for defining Policy Instances where the instance rule
// references a TemplateSchema derived from the Instance's template kind.
InstanceSchema *OpenAPISchema
// TemplateSchema defines a schema for defining Policy Templates.
TemplateSchema *OpenAPISchema
openAPISchemaTypes map[string]string = map[string]string{
"boolean": BoolType,
"number": DoubleType,
"integer": IntType,
"null": NullType,
"string": StringType,
"date": TimestampType,
"date-time": TimestampType,
"array": ListType,
"object": MapType,
"": "any",
}
)
const (
schemaDefYaml = `
type: object
properties:
type:
type: string
format:
type: string
description:
type: string
required:
type: array
items:
type: string
enum:
type: array
items:
type: string
default: {}
items:
$ref: "#openAPISchema"
properties:
type: object
additionalProperties:
$ref: "#openAPISchema"
additionalProperties:
$ref: "#openAPISchema"
metadata:
type: object
additionalProperties:
type: string
`
templateSchemaYaml = `
type: object
required:
- apiVersion
- kind
- metadata
- evaluator
properties:
apiVersion:
type: string
kind:
type: string
metadata:
type: object
required:
- name
properties:
uid:
type: string
name:
type: string
namespace:
type: string
default: "default"
etag:
type: string
labels:
type: object
additionalProperties:
type: string
pluralName:
type: string
description:
type: string
schema:
$ref: "#openAPISchema"
validator:
type: object
required:
- productions
properties:
description:
type: string
environment:
type: string
terms:
type: object
additionalProperties: {}
productions:
type: array
items:
type: object
required:
- message
properties:
match:
type: string
default: true
message:
type: string
details: {}
evaluator:
type: object
required:
- productions
properties:
description:
type: string
environment:
type: string
ranges:
type: array
items:
type: object
required:
- in
properties:
in:
type: string
key:
type: string
index:
type: string
value:
type: string
terms:
type: object
additionalProperties:
type: string
productions:
type: array
items:
type: object
properties:
match:
type: string
default: "true"
decision:
type: string
decisionRef:
type: string
output: {}
decisions:
type: array
items:
type: object
required:
- output
properties:
decision:
type: string
decisionRef:
type: string
output: {}
`
instanceSchemaYaml = `
type: object
required:
- apiVersion
- kind
- metadata
properties:
apiVersion:
type: string
kind:
type: string
metadata:
type: object
additionalProperties:
type: string
description:
type: string
selector:
type: object
properties:
matchLabels:
type: object
additionalProperties:
type: string
matchExpressions:
type: array
items:
type: object
required:
- key
- operator
properties:
key:
type: string
operator:
type: string
enum: ["DoesNotExist", "Exists", "In", "NotIn"]
values:
type: array
items: {}
default: []
rule:
$ref: "#templateRuleSchema"
rules:
type: array
items:
$ref: "#templateRuleSchema"
`
)
func init() {
AnySchema = NewOpenAPISchema()
InstanceSchema = NewOpenAPISchema()
in := strings.ReplaceAll(instanceSchemaYaml, "\t", " ")
err := yaml.Unmarshal([]byte(in), InstanceSchema)
if err != nil {
panic(err)
}
SchemaDef = NewOpenAPISchema()
in = strings.ReplaceAll(schemaDefYaml, "\t", " ")
err = yaml.Unmarshal([]byte(in), SchemaDef)
if err != nil {
panic(err)
}
TemplateSchema = NewOpenAPISchema()
in = strings.ReplaceAll(templateSchemaYaml, "\t", " ")
err = yaml.Unmarshal([]byte(in), TemplateSchema)
if err != nil {
panic(err)
}
}
|
[
7
] |
package webutil
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/blend/go-sdk/exception"
)
var (
// ErrURLUnset is a (hopefully) uncommon error.
ErrURLUnset = exception.Class("request url unset")
// DefaultRequestTimeout is the default webhook timeout.
DefaultRequestTimeout = 10 * time.Second
// DefaultRequestMethod is the default webhook method.
DefaultRequestMethod = "POST"
)
// NewRequestSender creates a new request sender.
/*
A request sender is a sepcialized request factory that makes request to a single endpoint.
It is useful when calling out to predefined things like webhooks.
You can send either raw bytes as the contents.
*/
func NewRequestSender(destination *url.URL) *RequestSender {
transport := &http.Transport{
DisableCompression: false,
DisableKeepAlives: false,
}
return &RequestSender{
URL: destination,
method: DefaultRequestMethod,
transport: transport,
headers: http.Header{},
client: &http.Client{
Transport: transport,
Timeout: DefaultRequestTimeout,
},
}
}
// RequestSender is a slack webhook sender.
type RequestSender struct {
*url.URL
transport *http.Transport
close bool
method string
client *http.Client
headers http.Header
tracer RequestTracer
}
// Send sends a request to the destination without a payload.
func (rs *RequestSender) Send() (*http.Response, error) {
return rs.send(rs.req())
}
// SendBytes sends a message to the webhook with a given msg body as raw bytes.
func (rs *RequestSender) SendBytes(ctx context.Context, contents []byte) (*http.Response, error) {
req, err := rs.reqBytes(contents)
if err != nil {
return nil, err
}
return rs.send(req.WithContext(ctx))
}
// SendJSON sends a message to the webhook with a given msg body as json.
func (rs *RequestSender) SendJSON(ctx context.Context, contents interface{}) (*http.Response, error) {
req, err := rs.reqJSON(contents)
if err != nil {
return nil, err
}
return rs.send(req.WithContext(ctx))
}
// properties
// WithMethod sets the request method (defaults to POST).
func (rs *RequestSender) WithMethod(method string) *RequestSender {
rs.method = method
return rs
}
// Method is the request method.
// It defaults to "POST".
func (rs *RequestSender) Method() string {
if len(rs.method) == 0 {
return DefaultRequestMethod
}
return rs.method
}
// WithTracer sets the request tracer.
func (rs *RequestSender) WithTracer(tracer RequestTracer) *RequestSender {
rs.tracer = tracer
return rs
}
// Tracer returns the request tracer.
func (rs *RequestSender) Tracer() RequestTracer {
return rs.tracer
}
// WithClose sets if we should close the connection.
func (rs *RequestSender) WithClose(close bool) *RequestSender {
rs.close = close
rs.transport.DisableKeepAlives = close
return rs
}
// Close returns if we should close the connection.
func (rs *RequestSender) Close() bool {
return rs.close
}
// WithHeaders sets headers.
func (rs *RequestSender) WithHeaders(headers http.Header) *RequestSender {
rs.headers = headers
return rs
}
// WithHeader adds an individual header.
func (rs *RequestSender) WithHeader(key, value string) *RequestSender {
rs.headers.Set(key, value)
return rs
}
// Headers returns the headers.
func (rs *RequestSender) Headers() http.Header {
return rs.headers
}
// WithTransport sets the transport.
func (rs *RequestSender) WithTransport(transport *http.Transport) *RequestSender {
rs.transport = transport
return rs
}
// Transport returns the transport.
func (rs *RequestSender) Transport() *http.Transport {
return rs.transport
}
// Client returns the underlying client.
func (rs *RequestSender) Client() *http.Client {
return rs.client
}
// internal methods
// Send sends a message to the webhook with a given msg body as raw bytes.
func (rs *RequestSender) send(req *http.Request) (res *http.Response, err error) {
if req.URL == nil {
return nil, ErrURLUnset
}
if rs.tracer != nil {
tf := rs.tracer.Start(req)
if tf != nil {
defer func() { tf.Finish(req, res, err) }()
}
}
res, err = rs.client.Do(req)
return
}
func (rs *RequestSender) req() *http.Request {
return &http.Request{
Method: rs.Method(),
Close: rs.Close(),
URL: rs.URL,
Header: rs.headers,
}
}
func (rs *RequestSender) reqBytes(contents []byte) (*http.Request, error) {
req := rs.req()
req.Body = ioutil.NopCloser(bytes.NewBuffer(contents))
req.ContentLength = int64(len(contents))
return req, nil
}
func (rs *RequestSender) reqJSON(msg interface{}) (*http.Request, error) {
contents, err := json.Marshal(msg)
if err != nil {
return nil, err
}
req := rs.req()
req.Body = ioutil.NopCloser(bytes.NewBuffer(contents))
req.ContentLength = int64(len(contents))
req.Header.Add(HeaderContentType, ContentTypeApplicationJSON)
return req, nil
}
|
[
1
] |
package main
func main() {
}
// leetcode1140_石子游戏II
func stoneGameII(piles []int) int {
n := len(piles)
dp := make([][]int, n+1) // dp[i][j]=>有piles[i:],M=j的情况下得分
for i := 0; i <= n; i++ {
dp[i] = make([]int, n+1)
}
sum := 0
for i := n - 1; i >= 0; i-- {
sum = sum + piles[i]
for M := 1; M <= n; M++ {
if i+2*M >= n { // 可以全部拿走
dp[i][M] = sum
} else {
for j := 1; j <= 2*M; j++ { // 尝试不同拿法,dp[i+j][max(j, M)]其中M=max(j,M)
dp[i][M] = max(dp[i][M], sum-dp[i+j][max(j, M)])
}
}
}
}
return dp[0][1]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
|
[
0
] |
package main
import (
"bytes"
"errors"
"fmt"
"github.com/PuerkitoBio/goquery"
"log"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"syscall"
"unsafe"
)
var _TIOCGWINSZ int
type WinSize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
func init() {
if runtime.GOOS == "darwin" {
_TIOCGWINSZ = 1074295912
} else {
_TIOCGWINSZ = 0x5413
}
}
func GetWinsize() (*WinSize, error) {
wsize := new(WinSize)
r1, _, errno := syscall.Syscall(syscall.SYS_IOCTL,
uintptr(syscall.Stdin),
uintptr(_TIOCGWINSZ),
uintptr(unsafe.Pointer(wsize)),
)
if int(r1) == -1 {
wsize.Col = 80
wsize.Row = 25
return wsize, os.NewSyscallError("GetWinsize", errors.New("Failed to get Winsize "+string(int(errno))))
}
return wsize, nil
}
func ClearScrean() {
c := exec.Command("clear")
c.Stdout = os.Stdout
c.Run()
}
func OverwriteCurrentLine(str string, positionCursorAtBeginning bool) {
winSize, _ := GetWinsize()
PositionCursor(0, int(winSize.Row))
fmt.Print("\033[K")
fmt.Print(str)
if positionCursorAtBeginning {
PositionCursor(0, int(winSize.Row))
}
}
func PositionCursor(x, y int) {
fmt.Printf("\033[%d;%dH", y, x)
}
func ToggleAlternateScreen(onoff bool) {
if onoff {
fmt.Print("\033[?1049h")
} else {
fmt.Print("\033[?1049l")
}
}
func SetCursorVisible(visible bool) {
if visible {
fmt.Print("\033[?25h")
} else {
fmt.Print("\033[?25l")
}
}
func RestoreShell() {
SetRawModeEnabled(false)
SetCursorVisible(true)
ToggleAlternateScreen(false)
}
func PrintCommands(winSize *WinSize) {
PositionCursor(0, int(winSize.Row)-2)
optionWidth := int((winSize.Col - 4) / 4)
nextPage := Truncate(WhiteBackground("N")+" Next Page", optionWidth, true)
prevPage := Truncate(WhiteBackground("P")+" Previous Page", optionWidth, true)
back := Truncate(WhiteBackground("B")+" Back", optionWidth, true)
goTo := Truncate(WhiteBackground("G")+" Go To", optionWidth, false)
openInBrowser := Truncate(WhiteBackground("O")+" Open in Browser", optionWidth, true)
copyURL := Truncate(WhiteBackground("U")+" Copy URL", optionWidth, true)
copyText := Truncate(WhiteBackground("T")+" Copy Text", optionWidth, true)
quit := Truncate(WhiteBackground("Q")+" Quit", optionWidth, false)
fmt.Printf(" %s%s%s%s\n %s%s%s%s\n", nextPage, prevPage, back, goTo, openInBrowser, copyURL, copyText, quit)
}
func PrintCentered(str string, winSize *WinSize) {
lines := strings.Split(str, "\n")
var lineLen int
if len(lines) == 0 {
lineLen = len(str)
lines = append(lines, str)
} else {
lineLen = len(lines[0])
}
nEmpty := (int(winSize.Row) - (5 + len(lines))) / 2
fmt.Print(EmptyLines(nEmpty))
for _, s := range lines {
fmt.Print(Spaces((int(winSize.Col)-lineLen)/2) + s + "\n")
}
}
func PrintGoTo() {
fmt.Print("Go to: ")
}
func MarkLinks(paragraphText string, options []Ref) string {
var buffer bytes.Buffer
for _, option := range options {
index := strings.Index(paragraphText, option.text)
if index >= 0 {
buffer.WriteString(paragraphText[:index] + Underline(option.text))
paragraphText = paragraphText[index+len(option.text):]
}
}
buffer.WriteString(paragraphText)
paragraphText = buffer.String()
return paragraphText
}
func WikishellAscii() (str string) {
str = " _ _ _ _ _ _\n" +
" (_) | (_) | | | | |\n" +
" __ ___| | ___ ___| |__ ___| | |\n" +
" \\ \\ /\\ / / | |/ / / __| '_ \\ / _ \\ | |\n" +
" \\ V V /| | <| \\__ \\ | | | __/ | |\n" +
" \\_/\\_/ |_|_|\\_\\_|___/_| |_|\\___|_|_|\n"
return
}
func GetHrefValue(s *goquery.Selection) (string, bool) {
val, exists := s.Attr("href")
if !exists {
return val, false
}
titleAttr, titleExists := s.Attr("title")
if (strings.HasPrefix(val, "/wiki/") || strings.HasPrefix(val, "/w/")) && len(s.Text()) > 1 &&
(!titleExists || (!strings.HasPrefix(titleAttr, "Help:IPA") && !strings.HasPrefix(titleAttr, "Wikipedia:") && !strings.HasPrefix(titleAttr, "File:") && !strings.Contains(val, "redlink=1"))) {
return val, true
} else {
return val, false
}
}
func Truncate(str string, width int, pad bool) string {
strLen := len(str)
strLenStripped := strLen - 15
if strLenStripped > width-1 {
truncation := Max(16, strLen-3-(strLenStripped-width))
newStr := str[:int(truncation)] + "..."
return newStr
} else if pad {
return str + Spaces(width-strLenStripped)
} else {
return str
}
}
func TruncateParagraph(paragraphText string, options []Ref, winSize *WinSize) (string, int) {
maxOptions := Min(10, len(options))
length := len(paragraphText)
escapeLength := Min(10, len(options)) * 14
rows := (length - escapeLength) / int(winSize.Col-5)
availableRows := int(winSize.Row) - 9
if rows > availableRows {
maxOptions = 0
toIndex := Max(0, Min(length-1, length-(rows-availableRows+1)*int(winSize.Col-5)))
paragraphText = paragraphText[:toIndex] + "\033[0m..."
} else {
maxOptions = Min(maxOptions, availableRows-rows)
}
return paragraphText, maxOptions
}
func IsParagraphValid(text string) bool {
if len(text) == 0 {
return false
}
if strings.HasPrefix(text, "Coordinates: ") {
return false
}
return true
}
func Spaces(n int) string {
return RepeatString(n, " ")
}
func EmptyLines(n int) string {
return RepeatString(n, "\n")
}
func RepeatString(n int, str string) string {
if n <= 0 {
return ""
}
var buffer bytes.Buffer
for i := 0; i < n; i++ {
buffer.WriteString(str)
}
return buffer.String()
}
func WhiteBackground(str string) string {
return "\033[107m\033[30m" + str + "\033[0m"
}
func Bold(str string) string {
return "\033[1m" + str + "\033[0m"
}
func Underline(str string) string {
return "\033[38;5;27m" + str + "\033[0m"
}
func Backspace() {
fmt.Print("\033[1D \033[1D")
}
func RemoveBrackets(s string) string {
reg, err := regexp.Compile("\\[([0-9]+|citation needed)\\]")
if err != nil {
log.Fatal(err)
}
modified := reg.ReplaceAllString(s, "")
return modified
}
func Alert() {
fmt.Print("\x07")
}
func Max(x, y int) int {
if x > y {
return x
} else {
return y
}
}
func Min(x, y int) int {
if x < y {
return x
} else {
return y
}
}
|
[
5
] |
package types
import (
"crypto/ecdsa"
"errors"
"fmt"
"math/big"
"github.com/kowala-tech/kUSD/common"
"github.com/kowala-tech/kUSD/crypto"
"github.com/kowala-tech/kUSD/params"
)
var (
ErrInvalidSig = errors.New("invalid v, r, s values")
errNoSigner = errors.New("missing signing methods")
ErrInvalidChainId = errors.New("invalid chain id for signer")
errAbstractSigner = errors.New("abstract signer")
abstractSignerAddress = common.HexToAddress("ffffffffffffffffffffffffffffffffffffffff")
big8 = big.NewInt(8)
)
// sigCache is used to cache the derived sender and contains
// the signer used to derive it.
type sigCache struct {
signer Signer
from common.Address
}
// MakeSigner returns a Signer based on the given chain config and block number.
func MakeSigner(config *params.ChainConfig, blockNumber *big.Int) Signer {
var signer Signer
switch {
default:
signer = NewAndromedaSigner(config.ChainID)
}
return signer
}
// SignTx signs the transaction using the given signer and private key
func SignTx(tx *Transaction, signer Signer, prv *ecdsa.PrivateKey) (*Transaction, error) {
var h common.Hash
if signer.ChainID() == nil {
h = tx.UnprotectedHash()
} else {
h = tx.ProtectedHash(signer.ChainID())
}
sig, err := crypto.Sign(h.Bytes(), prv)
if err != nil {
return nil, err
}
return tx.WithSignature(signer, sig)
}
// SignProposal signs the proposal using the given signer and private key
func SignProposal(proposal *Proposal, signer Signer, prv *ecdsa.PrivateKey) (*Proposal, error) {
h := proposal.ProtectedHash(signer.ChainID())
sig, err := crypto.Sign(h[:], prv)
if err != nil {
return nil, err
}
return proposal.WithSignature(signer, sig)
}
// SignVote signs the vote using the given signer and private key
func SignVote(vote *Vote, signer Signer, prv *ecdsa.PrivateKey) (*Vote, error) {
h := vote.ProtectedHash(signer.ChainID())
sig, err := crypto.Sign(h[:], prv)
if err != nil {
return nil, err
}
return vote.WithSignature(signer, sig)
}
func TxSender(signer Signer, tx *Transaction) (common.Address, error) {
if sc := tx.from.Load(); sc != nil {
sigCache := sc.(sigCache)
// If the signer used to derive from in a previous
// call is not the same as used current, invalidate
// the cache.
if sigCache.signer.Equal(signer) {
return sigCache.from, nil
}
}
var h common.Hash
V := tx.data.V
if !tx.Protected() {
h = tx.UnprotectedHash()
signer = &UnprotectedSigner{}
} else {
V = new(big.Int).Sub(V, signer.ChainIDMul())
V.Sub(V, big8)
h = tx.ProtectedHash(signer.ChainID())
}
addr, err := signer.Sender(h, tx.data.R, tx.data.S, V)
if err != nil {
return common.Address{}, err
}
tx.from.Store(sigCache{signer: signer, from: addr})
return addr, nil
}
func ProposalSender(signer Signer, proposal *Proposal) (common.Address, error) {
if sc := proposal.from.Load(); sc != nil {
sigCache := sc.(sigCache)
// If the signer used to derive from in a previous
// call is not the same as used current, invalidate
// the cache.
if sigCache.signer.Equal(signer) {
return sigCache.from, nil
}
}
V := new(big.Int).Sub(proposal.data.V, signer.ChainIDMul())
V.Sub(V, big8)
addr, err := signer.Sender(proposal.ProtectedHash(signer.ChainID()), proposal.data.R, proposal.data.S, V)
if err != nil {
return common.Address{}, err
}
proposal.from.Store(sigCache{signer: signer, from: addr})
return addr, nil
}
func VoteSender(signer Signer, vote *Vote) (common.Address, error) {
if sc := vote.from.Load(); sc != nil {
sigCache := sc.(sigCache)
// If the signer used to derive from in a previous
// call is not the same as used current, invalidate
// the cache.
if sigCache.signer.Equal(signer) {
return sigCache.from, nil
}
}
V := new(big.Int).Sub(vote.data.V, signer.ChainIDMul())
V.Sub(V, big8)
addr, err := signer.Sender(vote.ProtectedHash(signer.ChainID()), vote.data.R, vote.data.S, V)
if err != nil {
return common.Address{}, err
}
vote.from.Store(sigCache{signer: signer, from: addr})
return addr, nil
}
type Signer interface {
// PubilcKey returns the public key derived from the signature
Sender(hash common.Hash, R, S, V *big.Int) (common.Address, error)
// SignatureValues returns the raw R, S, V values corresponding to the
// given signature.
SignatureValues(sig []byte) (R, S, V *big.Int, err error)
// Checks for equality on the signers
Equal(Signer) bool
// Returns the current network ID
ChainID() *big.Int
// Returns the current network ID
ChainIDMul() *big.Int
}
type UnprotectedSigner struct{}
func (s UnprotectedSigner) ChainID() *big.Int { return nil }
func (s UnprotectedSigner) ChainIDMul() *big.Int { return nil }
func (s UnprotectedSigner) Equal(s2 Signer) bool {
_, ok := s2.(UnprotectedSigner)
return ok
}
func (s UnprotectedSigner) Sender(hash common.Hash, R, S, V *big.Int) (common.Address, error) {
return recoverPlain(hash, R, S, V, true)
}
func (s UnprotectedSigner) SignatureValues(sig []byte) (R, S, V *big.Int, err error) {
if len(sig) != 65 {
panic(fmt.Sprintf("wrong size for signature: got %d, want 65", len(sig)))
}
R = new(big.Int).SetBytes(sig[:32])
S = new(big.Int).SetBytes(sig[32:64])
V = new(big.Int).SetBytes([]byte{sig[64] + 27})
return
}
// AndromedaSigner implements the Signer interface using andromeda's rules
type AndromedaSigner struct {
chainID, chainIDMul *big.Int
}
func NewAndromedaSigner(chainID *big.Int) *AndromedaSigner {
if chainID == nil {
chainID = new(big.Int)
}
return &AndromedaSigner{
chainID: chainID,
chainIDMul: new(big.Int).Mul(chainID, big.NewInt(2)),
}
}
func (s AndromedaSigner) Equal(s2 Signer) bool {
andromeda, ok := s2.(AndromedaSigner)
return ok && andromeda.chainID.Cmp(s.chainID) == 0
}
func (s AndromedaSigner) Sender(hash common.Hash, R, S, V *big.Int) (common.Address, error) {
return recoverPlain(hash, R, S, V, true)
}
// SignatureValues returns a new signature. This signature
// needs to be in the [R || S || V] format where V is 0 or 1.
func (s AndromedaSigner) SignatureValues(sig []byte) (R, S, V *big.Int, err error) {
R, S, V, err = UnprotectedSigner{}.SignatureValues(sig)
if err != nil {
return nil, nil, nil, err
}
if s.chainID.Sign() != 0 {
V = big.NewInt(int64(sig[64] + 35))
V.Add(V, s.chainIDMul)
}
return R, S, V, nil
}
func (s AndromedaSigner) ChainID() *big.Int {
return s.chainID
}
func (s AndromedaSigner) ChainIDMul() *big.Int {
return s.chainIDMul
}
// deriveChainID derives the chain id from the given v parameter
func deriveChainID(v *big.Int) *big.Int {
if v.BitLen() <= 64 {
v := v.Uint64()
if v == 27 || v == 28 {
return new(big.Int)
}
return new(big.Int).SetUint64((v - 35) / 2)
}
v = new(big.Int).Sub(v, big.NewInt(35))
return v.Div(v, big.NewInt(2))
}
func recoverPlain(sighash common.Hash, R, S, Vb *big.Int, homestead bool) (common.Address, error) {
if Vb.BitLen() > 8 {
return common.Address{}, ErrInvalidSig
}
V := byte(Vb.Uint64() - 27)
if !crypto.ValidateSignatureValues(V, R, S, homestead) {
return common.Address{}, ErrInvalidSig
}
// encode the snature in uncompressed format
r, s := R.Bytes(), S.Bytes()
sig := make([]byte, 65)
copy(sig[32-len(r):32], r)
copy(sig[64-len(s):64], s)
sig[64] = V
// recover the public key from the signature
pub, err := crypto.Ecrecover(sighash[:], sig)
if err != nil {
return common.Address{}, err
}
if len(pub) == 0 || pub[0] != 4 {
return common.Address{}, errors.New("invalid public key")
}
var addr common.Address
copy(addr[:], crypto.Keccak256(pub[1:])[12:])
return addr, nil
}
|
[
2,
7
] |
package problems
/*
* @lc app=leetcode.cn id=520 lang=golang
*
* [520] 检测大写字母
*/
// @lc code=start
func detectCapitalUse(word string) bool {
n := len(word)
count := 0
for i := 0; i < n; i++ {
if word[i] >= 65 && word[i] <= 90 {
count++
}
}
if n == count {
return true
} else if count == 0 {
return true
} else if count == 1 && (word[0] >= 65 && word[0] <= 90) {
return true
} else {
return false
}
}
// @lc code=end
// USA
|
[
5
] |
package ABC_problemC_gray
import (
"testing"
)
// [ABC100C - *3 or /2](https://atcoder.jp/contests/abc100/tasks/abc100_c)
func AnswerABC100Cその1(N int, A []int) int {
// 必ず誰か1人が「2で割れる」を負担する必要がある
// いくら3倍しても、「2で割れる」回数は増えない
// → 2で割れる回数で決まる
var ans int
for _, a := range A {
countDivide2 := 0 // 2で割れる回数
for a > 0 {
if a%2 == 0 {
a /= 2
countDivide2++
} else {
break
}
}
ans += countDivide2
}
return ans
}
func TestAnswerABC100Cその1(t *testing.T) {
tests := []struct {
name string
N int
A []int
want int
}{
{"入力例1", 3, []int{5, 2, 4}, 3},
{"入力例2", 4, []int{631, 577, 243, 199}, 0},
{"入力例3", 10, []int{2184, 2126, 1721, 1800, 1024, 2528, 3360, 1945, 1280, 1776}, 39},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := AnswerABC100Cその1(tt.N, tt.A)
if got != tt.want {
t.Errorf("got %v want %v", got, tt.want)
}
})
}
}
|
[
2
] |
package amount_decliension
import (
"fmt"
"strconv"
"strings"
)
type declensioner struct {}
func NewDeclensioner() *declensioner{
return &declensioner{}
}
func (m *declensioner) AmountToString(totalSum float64) (stringAmount string) {
partOfNumbers := strings.Split(strconv.FormatFloat(totalSum, 'f', 2, 64), ".")
intPart, _ := strconv.Atoi(partOfNumbers[0])
stringAmount = m.GetNumberInWords(float64(intPart))
if len(partOfNumbers) == 2 {
stringAmount += " " + partOfNumbers[1]
fractalPart, _ := strconv.Atoi(partOfNumbers[1])
if fractalPart >= 11 && fractalPart <= 19 {
stringAmount += " " + FractionalPart.DeclensionMany
return
}
lastDigit := string(partOfNumbers[1][1])
if m.inArray(lastDigit, []string{"2", "3", "4"}) {
stringAmount += " " + FractionalPart.DeclensionSome
} else if lastDigit == "1" {
stringAmount += " " + FractionalPart.DeclensionOne
} else {
stringAmount += " " + FractionalPart.DeclensionMany
}
}
return stringAmount
}
func (m *declensioner) GetNumberInWords(num float64) (numInWords string) {
partOfNumbers := strings.Split(strconv.FormatFloat(num, 'f', 2, 64), ".")
intPart, _ := strconv.Atoi(partOfNumbers[0])
if intPart != 0 {
parts := m.splitStringByLength(fmt.Sprint(intPart), 3)
strNumParts := []string{}
for i, part := range m.reverse(parts) {
numPart := NumberParts[i]
numPart.Init(part)
if isEmpty, strNumPart := numPart.ToString(); !isEmpty {
strNumParts = append(strNumParts, strNumPart)
}
}
numInWords = strings.Join(m.reverse(strNumParts), " ")
} else {
numInWords = WordZero + " " + NumberParts[0].DeclensionMany
}
if len(partOfNumbers) == 2 {
parts := m.splitStringByLength(partOfNumbers[1], 2)
fractionalPart := FractionalPart
fractionalPart.Init(parts[0])
isEmpty, strNumPart := fractionalPart.ToString()
if !isEmpty {
if len(numInWords) != 0 {
numInWords += " "
}
numInWords += strNumPart
}
}
return
}
func (m *declensioner) splitStringByLength(str string, count int) []string {
strLen := len(str)
parts := []string{}
for i := strLen; i >= 0; i -= count {
if i == 0 {
continue
}
if i-count < 0 {
parts = append(parts, str[0:i])
continue
}
parts = append(parts, str[i-count:i])
}
return m.reverse(parts)
}
func (m *declensioner) inArray(val string, array []string) bool {
for _, v := range array {
if val == v {
return true
}
}
return false
}
func (m *declensioner) reverse(numbers []string) []string {
for i := 0; i < len(numbers)/2; i++ {
j := len(numbers) - i - 1
numbers[i], numbers[j] = numbers[j], numbers[i]
}
return numbers
}
|
[
5
] |
package system
import (
"encoding/json"
"gin-admin/app/utility/app"
"github.com/goinggo/mapstructure"
"reflect"
)
// json转struct
func JsonToStruct(jsonStr string, obj interface{}) error {
err := json.Unmarshal([]byte(jsonStr), &obj)
if err != nil {
app.Panic(err)
}
return nil
}
// struct转json
func StructToJson(Struct interface{}) string {
jsonBytes, err := json.Marshal(Struct)
if err != nil {
app.Panic(err)
}
return string(jsonBytes)
}
// json转map
func JsonToMap(jsonStr string) (result map[string]interface{}) {
err := json.Unmarshal([]byte(jsonStr), &result)
if err != nil {
app.Panic(err)
}
return result
}
// map转json
func MapToJson(instance map[string]interface{}) string {
jsonStr, err := json.Marshal(instance)
if err != nil {
app.Panic(err)
}
return string(jsonStr)
}
// map转struct
func MapToStruct(instance map[string]interface{}, people struct{}) struct{} {
err := mapstructure.Decode(instance, &people)
if err != nil {
app.Panic(err)
}
return people
}
// struct转map
func StructToMap(obj interface{}) map[string]interface{} {
objType := reflect.TypeOf(obj)
objValue := reflect.ValueOf(obj)
var data = make(map[string]interface{})
for i := 0; i < objType.NumField(); i++ {
data[objType.Field(i).Name] = objValue.Field(i).Interface()
}
return data
}
|
[
2
] |
package entity
import (
"fmt"
"strings"
"time"
"github.com/gosimple/slug"
"github.com/jinzhu/gorm"
"github.com/photoprism/photoprism/pkg/fs"
"github.com/photoprism/photoprism/pkg/rnd"
"github.com/ulule/deepcopier"
)
type Files []File
// File represents an image or sidecar file that belongs to a photo.
type File struct {
ID uint `gorm:"primary_key" json:"-" yaml:"-"`
UUID string `gorm:"type:varbinary(42);index;" json:"InstanceID,omitempty" yaml:"InstanceID,omitempty"`
Photo *Photo `json:"-" yaml:"-"`
PhotoID uint `gorm:"index;" json:"-" yaml:"-"`
PhotoUID string `gorm:"type:varbinary(42);index;" json:"PhotoUID" yaml:"PhotoUID"`
FileUID string `gorm:"type:varbinary(42);unique_index;" json:"UID" yaml:"UID"`
FileName string `gorm:"type:varbinary(768);unique_index:idx_files_name_root;" json:"Name" yaml:"Name"`
FileRoot string `gorm:"type:varbinary(16);default:'';unique_index:idx_files_name_root;" json:"Root" yaml:"Root,omitempty"`
OriginalName string `gorm:"type:varbinary(768);" json:"OriginalName" yaml:"OriginalName,omitempty"`
FileHash string `gorm:"type:varbinary(128);index" json:"Hash" yaml:"Hash,omitempty"`
FileModified time.Time `json:"Modified" yaml:"Modified,omitempty"`
FileSize int64 `json:"Size" yaml:"Size,omitempty"`
FileCodec string `gorm:"type:varbinary(32)" json:"Codec" yaml:"Codec,omitempty"`
FileType string `gorm:"type:varbinary(32)" json:"Type" yaml:"Type,omitempty"`
FileMime string `gorm:"type:varbinary(64)" json:"Mime" yaml:"Mime,omitempty"`
FilePrimary bool `json:"Primary" yaml:"Primary,omitempty"`
FileSidecar bool `json:"Sidecar" yaml:"Sidecar,omitempty"`
FileMissing bool `json:"Missing" yaml:"Missing,omitempty"`
FileDuplicate bool `json:"Duplicate" yaml:"Duplicate,omitempty"`
FilePortrait bool `json:"Portrait" yaml:"Portrait,omitempty"`
FileVideo bool `json:"Video" yaml:"Video,omitempty"`
FileDuration time.Duration `json:"Duration" yaml:"Duration,omitempty"`
FileWidth int `json:"Width" yaml:"Width,omitempty"`
FileHeight int `json:"Height" yaml:"Height,omitempty"`
FileOrientation int `json:"Orientation" yaml:"Orientation,omitempty"`
FileAspectRatio float32 `gorm:"type:FLOAT;" json:"AspectRatio" yaml:"AspectRatio,omitempty"`
FileMainColor string `gorm:"type:varbinary(16);index;" json:"MainColor" yaml:"MainColor,omitempty"`
FileColors string `gorm:"type:varbinary(9);" json:"Colors" yaml:"Colors,omitempty"`
FileLuminance string `gorm:"type:varbinary(9);" json:"Luminance" yaml:"Luminance,omitempty"`
FileDiff uint32 `json:"Diff" yaml:"Diff,omitempty"`
FileChroma uint8 `json:"Chroma" yaml:"Chroma,omitempty"`
FileNotes string `gorm:"type:text" json:"Notes" yaml:"Notes,omitempty"`
FileError string `gorm:"type:varbinary(512)" json:"Error" yaml:"Error,omitempty"`
Share []FileShare `json:"-" yaml:"-"`
Sync []FileSync `json:"-" yaml:"-"`
CreatedAt time.Time `json:"CreatedAt" yaml:"-"`
CreatedIn int64 `json:"CreatedIn" yaml:"-"`
UpdatedAt time.Time `json:"UpdatedAt" yaml:"-"`
UpdatedIn int64 `json:"UpdatedIn" yaml:"-"`
DeletedAt *time.Time `sql:"index" json:"DeletedAt,omitempty" yaml:"-"`
}
type FileInfos struct {
FileWidth int
FileHeight int
FileOrientation int
FileAspectRatio float32
FileMainColor string
FileColors string
FileLuminance string
FileDiff uint32
FileChroma uint8
}
// FirstFileByHash gets a file in db from its hash
func FirstFileByHash(fileHash string) (File, error) {
var file File
q := Db().Unscoped().First(&file, "file_hash = ?", fileHash)
return file, q.Error
}
// BeforeCreate creates a random UID if needed before inserting a new row to the database.
func (m *File) BeforeCreate(scope *gorm.Scope) error {
if rnd.IsUID(m.FileUID, 'f') {
return nil
}
return scope.SetColumn("FileUID", rnd.PPID('f'))
}
// ShareFileName returns a meaningful file name useful for sharing.
func (m *File) ShareFileName() string {
photo := m.RelatedPhoto()
if photo == nil {
return fmt.Sprintf("%s.%s", m.FileHash, m.FileType)
} else if len(m.FileHash) < 8 {
return fmt.Sprintf("%s.%s", rnd.UUID(), m.FileType)
} else if photo.TakenAtLocal.IsZero() || photo.PhotoTitle == "" {
return fmt.Sprintf("%s.%s", m.FileHash, m.FileType)
}
name := strings.Title(slug.MakeLang(photo.PhotoTitle, "en"))
taken := photo.TakenAtLocal.Format("20060102-150405")
token := rnd.Token(3)
result := fmt.Sprintf("%s-%s-%s.%s", taken, name, token, m.FileType)
return result
}
// Changed returns true if new and old file size or modified time are different.
func (m File) Changed(fileSize int64, fileModified time.Time) bool {
if m.DeletedAt != nil {
return true
}
if m.FileSize != fileSize {
return true
}
if m.FileModified.Round(time.Second).Equal(fileModified.Round(time.Second)) {
return false
}
return true
}
// Purge removes a file from the index by marking it as missing.
func (m *File) Purge() error {
return Db().Unscoped().Model(m).Updates(map[string]interface{}{"file_missing": true, "file_primary": false}).Error
}
// AllFilesMissing returns true, if all files for the photo of this file are missing.
func (m *File) AllFilesMissing() bool {
count := 0
if err := Db().Model(&File{}).
Where("photo_id = ? AND file_missing = 0", m.PhotoID).
Count(&count).Error; err != nil {
log.Errorf("file: %s", err.Error())
}
return count == 0
}
// Saves the file in the database.
func (m *File) Save() error {
if m.PhotoID == 0 {
return fmt.Errorf("file: photo id is empty (%s)", m.FileUID)
}
if err := Db().Save(m).Error; err != nil {
return err
}
photo := Photo{}
return Db().Model(m).Related(&photo).Error
}
// UpdateVideoInfos updates related video infos based on this file.
func (m *File) UpdateVideoInfos() error {
values := FileInfos{}
if err := deepcopier.Copy(&values).From(m); err != nil {
return err
}
return Db().Model(File{}).Where("photo_id = ? AND file_video = 1", m.PhotoID).Updates(values).Error
}
// Updates a column in the database.
func (m *File) Update(attr string, value interface{}) error {
return UnscopedDb().Model(m).UpdateColumn(attr, value).Error
}
// RelatedPhoto returns the related photo entity.
func (m *File) RelatedPhoto() *Photo {
if m.Photo != nil {
return m.Photo
}
photo := Photo{}
UnscopedDb().Model(m).Related(&photo)
return &photo
}
// NoJPEG returns true if the file is not a JPEG image file.
func (m *File) NoJPEG() bool {
return m.FileType != string(fs.TypeJpeg)
}
// Links returns all share links for this entity.
func (m *File) Links() Links {
return FindLinks("", m.FileUID)
}
|
[
5
] |
package models
import (
"errors"
"fmt"
"os"
"time"
"todo/src/db"
jwt "github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt"
)
// User - the user creating todos
type User struct {
ID string `db:"id" json:"id"`
Email string `db:"email" json:"email"`
FirstName string `db:"first_name" json:"first_name"`
LastName string `db:"last_name" json:"last_name"`
EncryptedPassword *string `db:"encrypted_password" json:"-"`
Password *string `db:"-" json:"password"`
JwtToken string `db:"-" json:"jwt_token"`
}
func (u *User) Create() error {
fmt.Println("User ", *u)
if u.Password != nil {
// would need better check of strength for real
if len(*u.Password) < 6 {
return errors.New("Password needs to be at least six characters long")
}
hash, err := bcrypt.GenerateFromPassword([]byte(*u.Password), bcrypt.DefaultCost)
if err != nil {
fmt.Println("Here2")
return err
}
encryptedPassword := string(hash)
u.EncryptedPassword = &encryptedPassword
}
err := db.Todo.Get(&u.ID, `
INSERT INTO users (
email,
first_name,
last_name,
encrypted_password
) VALUES ($1, $2, $3, $4) RETURNING id
`,
u.Email,
u.FirstName,
u.LastName,
u.EncryptedPassword,
)
fmt.Println("Here3, err ", err)
GetTokenHandler(u)
return err
}
// Update syncs the struct instance changes into the database
func (u *User) Update() error {
var prevUser User
err := db.Todo.Get(&prevUser,
`Select * from users where id = $1 or email = $2`,
u.ID, u.Email)
if err != nil {
return errors.New("No user with specified ID to update")
}
if u.Password != nil && *u.Password != "" {
if len(*u.Password) < 6 {
return errors.New("Password needs to be at least four characters long")
}
hash, err := bcrypt.GenerateFromPassword([]byte(*u.Password), bcrypt.DefaultCost)
if err != nil {
fmt.Printf("Here2")
return err
}
encryptedPassword := string(hash)
u.EncryptedPassword = &encryptedPassword
}
_, err = db.Todo.Exec(
`UPDATE users SET
email=$2,
first_name=$3,
last_name=$4,
encrypted_password=$5
WHERE id=$1`,
prevUser.ID,
u.Email,
u.FirstName,
u.LastName,
u.EncryptedPassword)
if err != nil {
fmt.Printf("Here1")
return err
}
return nil
}
// Update syncs the struct instance changes into the database
func (u *User) Get() error {
// could potentially get other ways as well, keeping this simple
if u.Email != "" {
err := db.Todo.Get(u,
`Select * from users where email = $1`,
u.Email)
if err != nil {
return errors.New("No user with specified email to get")
}
} else if u.ID != "" {
err := db.Todo.Get(u,
`Select * from users where id = $1`,
u.ID)
if err != nil {
return errors.New("No user with specified email to get")
}
} else {
return errors.New("Need email or id for user to get")
}
return nil
}
// Delete the struct user from the database
func (u *User) Delete() error {
_, err := db.Todo.Exec(
`DELETE FROM users where id = $1 or email = $2`,
u.ID, u.Email)
if err != nil {
return errors.New("No user with specified ID or email to delete")
}
return nil
}
// Authenticate returns true if the provided password matches the one stored in the database
func (u *User) Authenticate(password string) error {
if u.EncryptedPassword == nil {
return errors.New("OAuth user cannot be authenticated with pasword")
}
err := bcrypt.CompareHashAndPassword(
[]byte(*u.EncryptedPassword),
[]byte(password))
if err != nil {
return errors.New("invalid password")
}
return nil
}
/* Handlers */
var GetTokenHandler = func(user *User) {
/* Create the token */
token := jwt.New(jwt.SigningMethodHS256)
// Create a map to store our claims
claims := token.Claims.(jwt.MapClaims)
/* Set token claims */
claims["first_name"] = user.FirstName
claims["last_name"] = user.LastName
claims["encrypted_password"] = user.EncryptedPassword
claims["id"] = user.ID
claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
/* Sign the token with our secret */
tokenString, _ := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
user.JwtToken = tokenString
}
|
[
5
] |
// Copyright 2015,2016,2017,2018,2019,2020,2021 SeukWon Kang ([email protected])
// 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 stage
import (
"math"
"time"
"github.com/kasworld/g2rand"
"github.com/kasworld/gowasm2dgame/config/gameconst"
"github.com/kasworld/gowasm2dgame/enum/acttype"
"github.com/kasworld/gowasm2dgame/enum/acttype_vector"
"github.com/kasworld/gowasm2dgame/enum/gameobjtype"
"github.com/kasworld/gowasm2dgame/enum/teamtype"
"github.com/kasworld/gowasm2dgame/lib/vector2f"
"github.com/kasworld/gowasm2dgame/lib/w2dlog"
"github.com/kasworld/gowasm2dgame/protocol_w2d/w2d_obj"
"github.com/kasworld/uuidstr"
)
type Team struct {
rnd *g2rand.G2Rand `prettystring:"hide"`
log *w2dlog.LogBase `prettystring:"hide"`
ActStats acttype_vector.ActTypeVector
UUID string
TeamType teamtype.TeamType
IsAlive bool
RespawnTick int64
Ball *GameObj // ball is special
Objs []*GameObj
}
func NewTeam(l *w2dlog.LogBase, TeamType teamtype.TeamType, seed int64) *Team {
nowtick := time.Now().UnixNano()
bt := &Team{
rnd: g2rand.NewWithSeed(seed),
log: l,
IsAlive: true,
TeamType: TeamType,
UUID: uuidstr.New(),
Objs: make([]*GameObj, 0),
}
bt.Ball = &GameObj{
teamType: TeamType,
GOType: gameobjtype.Ball,
UUID: uuidstr.New(),
BirthTick: nowtick,
LastMoveTick: nowtick,
PosVt: vector2f.Vector2f{
bt.rnd.Float64() * gameconst.StageW,
bt.rnd.Float64() * gameconst.StageH,
},
}
maxv := gameobjtype.Attrib[gameobjtype.Ball].SpeedLimit
vt := vector2f.NewVectorLenAngle(
bt.rnd.Float64()*maxv,
bt.rnd.Float64()*360,
)
bt.Ball.SetDxy(vt)
return bt
}
func (bt *Team) RespawnBall(now int64) {
bt.IsAlive = true
bt.Ball.toDelete = false
bt.Ball.PosVt = vector2f.Vector2f{
bt.rnd.Float64() * gameconst.StageW,
bt.rnd.Float64() * gameconst.StageH,
}
bt.Ball.VelVt = vector2f.Vector2f{
0, 0,
}
bt.Ball.LastMoveTick = now
// bt.Ball.BirthTick = now
}
func (bt *Team) ToPacket() *w2d_obj.Team {
rtn := &w2d_obj.Team{
TeamType: bt.TeamType,
Ball: bt.Ball.ToPacket(),
Objs: make([]*w2d_obj.GameObj, 0),
}
for _, v := range bt.Objs {
if v.toDelete {
continue
}
rtn.Objs = append(rtn.Objs, v.ToPacket())
}
return rtn
}
func (bt *Team) Count(ot gameobjtype.GameObjType) int {
rtn := 0
for _, v := range bt.Objs {
if v.toDelete {
continue
}
if v.GOType == ot {
rtn++
}
}
return rtn
}
func (bt *Team) addGObj(o *GameObj) {
for i, v := range bt.Objs {
if v.toDelete {
bt.Objs[i] = o
return
}
}
bt.Objs = append(bt.Objs, o)
}
func (bt *Team) GetRemainAct(now int64, act acttype.ActType) float64 {
durSec := float64(now-bt.Ball.BirthTick) / float64(time.Second)
actedCount := float64(bt.ActStats[act])
totalCanAct := durSec * acttype.Attrib[act].PerSec
remainAct := totalCanAct - actedCount
return remainAct
}
func (bt *Team) ApplyAct(actObj *w2d_obj.Act) {
bt.ActStats.Inc(actObj.Act)
switch actObj.Act {
default:
bt.log.Fatal("unknown act %+v %v", actObj, bt)
case acttype.Nothing:
case acttype.Shield:
bt.AddShield(actObj.Angle, actObj.AngleV)
case acttype.SuperShield:
bt.AddSuperShield(actObj.Angle, actObj.AngleV)
case acttype.HommingShield:
bt.AddHommingShield(actObj.Angle, actObj.AngleV)
case acttype.Bullet:
bt.AddBullet(actObj.Angle, actObj.AngleV)
case acttype.SuperBullet:
bt.AddSuperBullet(actObj.Angle, actObj.AngleV)
case acttype.HommingBullet:
bt.AddHommingBullet(actObj.Angle, actObj.AngleV, actObj.DstObjID)
case acttype.Accel:
vt := vector2f.NewVectorLenAngle(actObj.AngleV, actObj.Angle)
bt.Ball.AddDxy(vt)
}
}
func (bt *Team) AddShield(angle, anglev float64) *GameObj {
nowtick := time.Now().UnixNano()
o := &GameObj{
teamType: bt.TeamType,
GOType: gameobjtype.Shield,
UUID: uuidstr.New(),
BirthTick: nowtick,
LastMoveTick: nowtick,
Angle: angle,
AngleV: anglev,
}
bt.addGObj(o)
return o
}
func (bt *Team) AddSuperShield(angle, anglev float64) *GameObj {
nowtick := time.Now().UnixNano()
o := &GameObj{
teamType: bt.TeamType,
GOType: gameobjtype.SuperShield,
UUID: uuidstr.New(),
BirthTick: nowtick,
LastMoveTick: nowtick,
Angle: angle,
AngleV: anglev,
}
bt.addGObj(o)
return o
}
func (bt *Team) AddBullet(angle, anglev float64) *GameObj {
nowtick := time.Now().UnixNano()
o := &GameObj{
teamType: bt.TeamType,
GOType: gameobjtype.Bullet,
UUID: uuidstr.New(),
BirthTick: nowtick,
LastMoveTick: nowtick,
PosVt: bt.Ball.PosVt,
VelVt: vector2f.NewVectorLenAngle(anglev, angle),
}
bt.addGObj(o)
return o
}
func (bt *Team) AddSuperBullet(angle, anglev float64) *GameObj {
nowtick := time.Now().UnixNano()
o := &GameObj{
teamType: bt.TeamType,
GOType: gameobjtype.SuperBullet,
UUID: uuidstr.New(),
BirthTick: nowtick,
LastMoveTick: nowtick,
PosVt: bt.Ball.PosVt,
VelVt: vector2f.NewVectorLenAngle(anglev, angle),
}
bt.addGObj(o)
return o
}
func (bt *Team) AddHommingShield(angle, anglev float64) *GameObj {
nowtick := time.Now().UnixNano()
mvvt := vector2f.NewVectorLenAngle(anglev, angle)
o := &GameObj{
teamType: bt.TeamType,
GOType: gameobjtype.HommingShield,
UUID: uuidstr.New(),
BirthTick: nowtick,
LastMoveTick: nowtick,
Angle: angle,
AngleV: anglev,
PosVt: bt.Ball.PosVt.Add(mvvt),
VelVt: mvvt,
}
bt.addGObj(o)
return o
}
func (bt *Team) AddHommingBullet(angle, anglev float64, dstid string) *GameObj {
nowtick := time.Now().UnixNano()
o := &GameObj{
teamType: bt.TeamType,
GOType: gameobjtype.HommingBullet,
UUID: uuidstr.New(),
BirthTick: nowtick,
LastMoveTick: nowtick,
Angle: angle,
AngleV: anglev,
PosVt: bt.Ball.PosVt,
VelVt: vector2f.NewVectorLenAngle(anglev, angle),
DstUUID: dstid,
}
bt.addGObj(o)
return o
}
func (bt *Team) CalcAimAngleAndV(
bullet gameobjtype.GameObjType, dsto *GameObj) (float64, float64) {
s1 := gameobjtype.Attrib[bullet].SpeedLimit
vt := dsto.PosVt.Sub(bt.Ball.PosVt)
s2 := dsto.VelVt.Abs()
if s2 == 0 {
return vt.Phase(), s1
}
a2 := dsto.VelVt.Phase() - vt.Phase()
a1 := math.Asin(s2 / s1 * math.Sin(a2))
return vt.AddAngle(a1).Phase(), s1
}
|
[
2
] |
// Copyright 2019 DxChain, All rights reserved.
// Use of this source code is governed by an Apache
// License 2.0 that can be found in the LICENSE file.
package storagehosttree
import (
"github.com/DxChainNetwork/godx/storage"
)
// node defines the storage host tree node
type node struct {
parent *node
left *node
right *node
// count includes the amount of storage hosts including the sum of all its' children
// and the node itself
count int
// indicates if the node contained any storage host information
occupied bool
// total evaluation of the storage hosts, including the sum of all its' child's
// evaluation and the evaluation of node it self
evalTotal int64
entry *nodeEntry
}
// nodeEntry is the information stored in a storage host tree node
type nodeEntry struct {
storage.HostInfo
eval int64
}
// nodeEntries defines a collection of node entry that implemented the sorting methods
// the sorting will be ranked from the higher evaluation to lower evaluation
type nodeEntries []nodeEntry
// the storage host with higher weight will placed in the front of the list
func (ne nodeEntries) Len() int { return len(ne) }
func (ne nodeEntries) Less(i, j int) bool { return ne[i].eval > ne[j].eval }
func (ne nodeEntries) Swap(i, j int) { ne[i], ne[j] = ne[j], ne[i] }
// newNode will create and initialize a new node object, which will be inserted into
// the StorageHostTree
func newNode(parent *node, entry *nodeEntry) *node {
return &node{
parent: parent,
occupied: true,
evalTotal: entry.eval,
count: 1,
entry: entry,
}
}
// nodeRemove will not remove the actual node from the tree
// instead, it update the evaluation, and occupied status
func (n *node) nodeRemove() {
n.evalTotal = n.evalTotal - n.entry.eval
n.occupied = false
parent := n.parent
for parent != nil {
parent.evalTotal = parent.evalTotal - n.entry.eval
parent = parent.parent
}
}
// nodeInsert will insert the node entry into the StorageHostTree
func (n *node) nodeInsert(entry *nodeEntry) (nodesAdded int, nodeInserted *node) {
// 1. check if the node is root node
if n.parent == nil && !n.occupied && n.left == nil && n.right == nil {
n.occupied = true
n.entry = entry
n.evalTotal = entry.eval
nodesAdded = 0
nodeInserted = n
return
}
// 2. add all child evaluation
n.evalTotal = n.evalTotal + entry.eval
// 3. check if the node is occupied
if !n.occupied {
n.occupied = true
n.entry = entry
nodesAdded = 0
nodeInserted = n
return nodesAdded, nodeInserted
}
// 4. insert new node, binary tree
if n.left == nil {
n.left = newNode(n, entry)
nodesAdded = 1
nodeInserted = n.left
} else if n.right == nil {
n.right = newNode(n, entry)
nodesAdded = 1
nodeInserted = n.right
} else if n.left.count <= n.right.count {
nodesAdded, nodeInserted = n.left.nodeInsert(entry)
} else {
nodesAdded, nodeInserted = n.right.nodeInsert(entry)
}
// 5. update the node count
n.count += nodesAdded
return
}
// nodeWithEval will retrieve node with the specific evaluation
func (n *node) nodeWithEval(eval int64) (*node, error) {
if eval > n.evalTotal {
return nil, ErrEvaluationTooLarge
}
if n.left != nil {
if eval < n.left.evalTotal {
return n.left.nodeWithEval(eval)
}
eval = eval - n.left.evalTotal
}
if n.right != nil && eval < n.right.evalTotal {
return n.right.nodeWithEval(eval)
}
if !n.occupied {
return nil, ErrNodeNotOccupied
}
return n, nil
}
|
[
0,
5
] |
package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func matPrint(X mat.Matrix) {
fa := mat.Formatted(X, mat.Prefix(""), mat.Squeeze())
fmt.Printf("%v\n", fa)
}
func main() {
// u := mat.NewVecDense(3, []float64{1, 2, 3})
// println("u: ")
// matPrint(u)
// v := mat.NewVecDense(3, []float64{4, 5, 6})
// println("v: ")
// matPrint(v)
// w := mat.NewVecDense(3, nil)
// w.AddVec(u, v)
// println("u + v: ")
// matPrint(w)
// // Or, you can overwrite u with the result of your operation to
// //save space.
// u.AddVec(u, v)
// println("u (overwritten):")
// matPrint(u)
// // Add u + alpha * v for some scalar alpha
// w.AddScaledVec(u, 2, v)
// println("u + 2 * v: ")
// matPrint(w)
// // Subtract v from u
// w.SubVec(u, v)
// println("v - u: ")
// matPrint(w)
// // Scale u by alpha
// w.ScaleVec(23, u)
// println("u * 23: ")
// matPrint(w)
// // Compute the dot product of u and v
// // Since float64’s don’t have a dot method, this is not done
// //inplace
// d := mat.Dot(u, v)
// println("u dot v: ", d)
// // Find length of v
// l := v.Len()
// println("Length of v: ", l)
// // We can also find the length of v in Euclidean space
// // The 2 parameter specifices that this is the Frobenius norm
// // Rather than the maximum absolute column sum
// // This distinction is more important when Norm is applied to
// // Matrices since vectors only have one column and the the
// // maximum absolute column sum is the Frobenius norm squared.
// println(mat.Norm(v, 2))
// fmt.Println("\n\n\n\n")
v := make([]float64, 12)
for i := 0; i < 12; i++ {
v[i] = float64(i)
}
// Create a new matrix
A := mat.NewDense(3, 4, v)
println("A:")
matPrint(A)
// Setting and getting are pretty simple
a := A.At(0, 2)
println("A[0, 2]: ", a)
A.Set(0, 2, -1.5)
matPrint(A)
// However, we can also set and get rows and columns
// Rows and columns are returned as vectors, which can be used for
// other computations
println("Row 1 of A:")
matPrint(A.RowView(1))
println("Column 0 of A:")
matPrint(A.ColView(0))
// Rows and columns may be set,
// But this is done from slices of floats
row := []float64{10, 9, 8, 7}
A.SetRow(0, row)
matPrint(A)
col := []float64{3, 2, 1}
A.SetCol(0, col)
matPrint(A)
// Addition and subtraction are identical for Matrices and vectors
// However, if the dimensions don't match,
// the function will throw a panic.
B := mat.NewDense(3, 4, nil)
B.Add(A, A)
println("B:")
matPrint(B)
C := mat.NewDense(3, 4, nil)
C.Sub(A, B)
println("A - B:")
matPrint(C)
// We can scale all elements of the matrix by a constant
C.Scale(3.5, B)
println("3.5 * B:")
matPrint(C)
// Transposing a matrix is a little funky.
// A.T() is no longer *Dense, but is now a Matrix
// We can still do most of the same operations with it,
// but we cannot set any of its values.
println("A'")
matPrint(A.T())
// Multiplication is pretty straightforward
D := mat.NewDense(3, 3, nil)
D.Product(A, B.T())
println("A * B'")
matPrint(D)
// We can use Product to multiply as many matrices as we want,
// provided the receiver has the appropriate dimensions
// The order of operations is optimized to reduce operations.
D.Product(D, A, B.T(), D)
println("D * A * B' * D")
matPrint(D)
// We can also apply a function to elements of the matrix.
// This function must take two integers and a float64,
// representing the row and column indices and the value in the
// input matrix. It must return a float. See sumOfIndices below.
C.Apply(sumOfIndices, A)
println("C:")
matPrint(C)
// Once again, we have some functions that return scalar values
// For example, we can compute the determinant
E := A.Slice(0, 3, 0, 3)
println("A:")
matPrint(A)
println("E (slice of A):")
matPrint(E)
d := mat.Det(E)
println("det(E): ", d)
// And the trace
t := mat.Trace(E)
println("tr(E)", t)
}
func sumOfIndices(i, j int, v float64) float64 {
return float64(i + j)
}
|
[
2
] |
package main
type operator = func([]int) int
type Instruction struct {
code int
name string
params int
op operator
write bool
jump bool
}
func MakeInstructionSet(comp *computer) map[int]Instruction {
return map[int]Instruction{
1: {
code: 1,
name: "add",
params: 2,
op: add,
write: true,
jump: false,
},
2: {
code: 2,
name: "mul",
params: 2,
op: mul,
write: true,
jump: false,
},
3: {
code: 3,
name: "input",
params: 0,
op: comp.in,
write: true,
jump: false,
},
4: {
code: 4,
name: "output",
params: 1,
op: comp.out,
write: false,
jump: false,
},
5: {
code: 5,
name: "jump-true",
params: 2,
op: jt,
write: false,
jump: true,
},
6: {
code: 6,
name: "jump-false",
params: 2,
op: jf,
write: false,
jump: true,
},
7: {
code: 7,
name: "lt",
params: 2,
op: lt,
write: true,
jump: false,
},
8: {
code: 8,
name: "eq",
params: 2,
op: eq,
write: true,
jump: false,
},
9: {
code: 9,
name: "rel",
params: 1,
op: comp.rel,
write: false,
jump: false,
},
99: {
code: 99,
name: "exit",
params: 0,
op: nil,
write: false,
jump: false,
},
}
}
func add(params []int) int {
return params[0] + params[1]
}
func mul(params []int) int {
return params[0] * params[1]
}
func jt(params []int) int {
if params[0] != 0 {
return params[1]
} else {
return -1
}
}
func jf(params []int) int {
if params[0] == 0 {
return params[1]
} else {
return -1
}
}
func lt(params []int) int {
var isLt = params[0] < params[1]
if isLt {
return 1
} else {
return 0
}
}
func eq(params []int) int {
var isEq = params[0] == params[1]
if isEq {
return 1
} else {
return 0
}
}
func (comp *computer) in(params []int) int {
return <-comp.input
}
func (comp *computer) out(params []int) int {
if comp.output != nil {
comp.output <- params[0]
} else {
println(params[0])
}
return 0 // Return value is ignored
}
func (comp *computer) rel(params []int) int {
comp.relativeBase = comp.relativeBase + params[0]
return 0 // Ignored
}
|
[
0
] |
package main
import (
"context"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
"time"
)
func main() {
cfg := NewRouterConfig()
if len(cfg.UpstreamURL) == 0 {
log.Panicln("give an upstream_url as an env-var")
}
c := makeProxy(cfg.Timeout)
log.Printf("Timeout set to: %s\n", cfg.Timeout)
log.Printf("Upstream URL: %s\n", cfg.UpstreamURL)
router := http.NewServeMux()
router.HandleFunc("/", makeHandler(c, cfg.Timeout, cfg.UpstreamURL))
s := &http.Server{
Addr: ":" + cfg.Port,
Handler: router,
ReadTimeout: cfg.Timeout,
WriteTimeout: cfg.Timeout,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())
}
// makeHandler builds a router to convert sub-domains into OpenFaaS gateway URLs with
// a username prefix and suffix of the destination function.
// i.e. system.o6s.io/dashboard
// becomes: gateway:8080/function/system-dashboard, where gateway:8080
// is specified in upstreamURL
func makeHandler(c *http.Client, timeout time.Duration, upstreamURL string) func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(upstreamURL, "/") == false {
upstreamURL = upstreamURL + "/"
}
return func(w http.ResponseWriter, r *http.Request) {
var host string
tldSepCount := 1
tldSep := "."
if len(r.Host) == 0 || strings.Count(r.Host, tldSep) <= tldSepCount {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("invalid sub-domain in Host header"))
return
}
host = r.Host[0:strings.Index(r.Host, tldSep)]
requestURI := r.RequestURI
if strings.HasPrefix(requestURI, "/") {
requestURI = requestURI[1:]
}
upstreamFullURL := fmt.Sprintf("%sfunction/%s-%s", upstreamURL, host, requestURI)
if r.Body != nil {
defer r.Body.Close()
}
req, _ := http.NewRequest(r.Method, upstreamFullURL, r.Body)
timeoutContext, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
copyHeaders(req.Header, &r.Header)
res, resErr := c.Do(req.WithContext(timeoutContext))
if resErr != nil {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(resErr.Error()))
fmt.Printf("Upstream %s status: %d\n", upstreamFullURL, http.StatusBadGateway)
return
}
copyHeaders(w.Header(), &res.Header)
fmt.Printf("Upstream %s status: %d\n", upstreamFullURL, res.StatusCode)
w.WriteHeader(res.StatusCode)
if res.Body != nil {
defer res.Body.Close()
bytesOut, _ := ioutil.ReadAll(res.Body)
w.Write(bytesOut)
}
}
}
func copyHeaders(destination http.Header, source *http.Header) {
for k, v := range *source {
vClone := make([]string, len(v))
copy(vClone, v)
(destination)[k] = vClone
}
}
func makeProxy(timeout time.Duration) *http.Client {
proxyClient := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: timeout,
KeepAlive: 1 * time.Second,
}).DialContext,
IdleConnTimeout: 120 * time.Millisecond,
ExpectContinueTimeout: 1500 * time.Millisecond,
},
}
return &proxyClient
}
|
[
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.