text stringlengths 11 4.05M |
|---|
package commands
import (
"errors"
"fmt"
"regexp"
"strings"
"github.com/LiveSocket/bot/command-runner/helpers"
"github.com/LiveSocket/bot/conv"
"github.com/LiveSocket/bot/service"
"github.com/LiveSocket/bot/service/socket"
)
type addInput struct {
Channel string
Username string
Name string
Response string
}
// Add Adds or updates a command
//
// !add !<name> <response>
//
// command.add
// [name, response...]{message twitch.PrivateMessage}
//
// Returns [string] as response for chat
func Add(service *service.Service) func(*socket.Invocation) socket.Result {
return func(invocation *socket.Invocation) socket.Result {
// Get input args from call
input, err := getAddInput(service, invocation)
if err != nil {
return socket.Error(err)
}
// Trim ! off command name
input.Name = input.Name[1:len(input.Name)]
// Check if command exists
command, err := helpers.GetCommandByID(service, input.Channel, input.Name)
if err != nil {
return socket.Error(err)
}
// If command exists
if command != nil {
// Create wamp.Dict of command
command.Response = input.Response
command.UpdatedBy = input.Username
// Update command
_, err = helpers.UpdateCommand(service, command)
} else {
// Create new command
err = helpers.CreateCommand(service, input.Channel, input.Name, input.Response, input.Username)
}
if err != nil {
return socket.Error(err)
}
// Return message to display in chat
return socket.Success(fmt.Sprintf("Command !%s added/updated", input.Name))
}
}
func getAddInput(service *service.Service, invocation *socket.Invocation) (*addInput, error) {
if invocation.ArgumentsKw["message"] == nil {
return nil, errors.New("Missing message")
}
if len(invocation.Arguments) == 0 {
return nil, errors.New("Missing args")
}
if invocation.Arguments[0] == nil {
return nil, errors.New("Missing name")
}
if len(invocation.Arguments) < 2 {
return nil, errors.New("Missing response")
}
// Splice response together back into a string
parts := []string{}
for _, arg := range invocation.Arguments[1:len(invocation.Arguments)] {
parts = append(parts, conv.ToString(arg))
}
response := strings.Join(parts, " ")
m, err := conv.ToStringMap(invocation.ArgumentsKw["message"])
if err != nil {
return nil, err
}
user, err := conv.ToStringMap(m["User"])
if err != nil {
return nil, err
}
// Create input args
input := &addInput{
Channel: conv.ToString(m["Channel"]),
Username: conv.ToString(user["Name"]),
Name: conv.ToString(invocation.Arguments[0]),
Response: response,
}
// Validate input args
message := validateAdd(service, input)
if message != nil {
return nil, message
}
return input, nil
}
func validateAdd(service *service.Service, data *addInput) error {
// Check command starts with !
if !strings.HasPrefix(data.Name, "!") {
return errors.New("Command name must start with !")
}
// Check command contains at least 1 letter or number
match, _ := regexp.MatchString("!\\w+", data.Name)
if !match {
return errors.New("Command name should contain at least 1 letter or number")
}
// Check command name does not include special characters
match, _ = regexp.MatchString("!.*[!?.,[\\\\\\]{}%$#@^&*()_+\\-=|<>:;'\"~`]+.*", data.Name)
if match {
return errors.New("Command name should not include any additional special characters")
}
// Check command name is not already reserved
exists, err := helpers.CustomExists(service, data.Channel, data.Name[1:len(data.Name)])
if err != nil {
return err
}
// Fail if is reserved name
if exists {
return errors.New("Cannot overwrite custom commands")
}
// Validation checks passed
return nil
}
|
package main
import (
"fmt"
)
func coin(deno []int, v int) int {
n := len(deno)
dp := make([][]int, 0, n)
for i := 0; i < n; i++ {
dp = append(dp, make([]int, v+1))
dp[i][0] = 1
}
for j := 0; j <= v; j++ {
if j%deno[0] == 0 {
dp[0][j] = 1
}
/*else {
dp[0][j] = 0
}*/
}
for i := 1; i < n; i++ {
for j := 1; j <= v; j++ {
tmp := 0
for k := 0; k*deno[i] <= j; k++ {
tmp += dp[i-1][j-k*deno[i]]
}
dp[i][j] = tmp
}
}
for _, v := range dp {
fmt.Println(v)
}
return dp[n-1][v]
}
func main() {
deno := make([]int, 0, 5)
deno = append(deno, 50, 20, 10, 5, 1)
/*
for i := range deno {
fmt.Println(deno[i])
}
*/
head := make([]int, 0, 101)
for i := 0; i < 101; i++ {
head = append(head, i)
}
fmt.Println(head)
c := coin(deno, 100)
fmt.Println(c)
}
|
package main
import (
"fmt"
"math"
)
// Geometry interface requires an area() and perim() method for each type implementing it
type geometry interface {
area() float64
perim() float64
}
// Define 2 types - circle and rectangle
type rectangle struct {
width, height float64
}
type circle struct {
radius float64
}
// Define the methods for each type - each has a different implementation of the area() method
// Area methods
func (r rectangle) area() float64 {
return r.width * r.height
}
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
// Perimeter methods
func (r rectangle) perim() float64 {
return 2*r.width + 2*r.height
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
/* Helper functions take the interface as argument
- making use of the method that is defined for the correct type */
//MeasureArea is a helper function, allowing use of geometry interface with shape types
func MeasureArea(g geometry) {
// Call area on whichever type is being operated on
fmt.Println(g.area())
}
//MeasurePerim is a helper function, allowing use of geometry interface with shape types
func MeasurePerim(g geometry) {
fmt.Println(g.perim())
}
// Main
func main() {
// Define instances of the shape types
rec := rectangle{width: 3, height: 4}
circ := circle{radius: 10}
// Apply measure helper function to the rec instance
MeasureArea(rec)
// Apply measure helper function to the rec instance
MeasurePerim(circ)
}
|
package main
import (
"context"
"github.com/wuzuoliang/log"
"os"
)
func main() {
newLog := log.New()
newLog.Info("newLog", "test1", log.JSON(&struct {
A int
B string
}{1, "2"}))
newLog.Log("newLog", "test2", &struct {
A int
B string
}{3, "4"})
newLog2 := log.New("withinit", "test2")
newLog2.Error("sss", "1", "2")
newLog2.Warn("1111", "fuck", "you")
newLog3 := log.New()
newLog3.SetHandler(log.CallerFileHandler(log.StreamHandler(os.Stdout, log.LogfmtFormat())))
newLog3.Debug("1111", "asd", "aaaa")
newLog3.SetHandler(log.CallerFuncHandler(log.StreamHandler(os.Stdout, log.LogfmtFormat())))
newLog3.Debug("2222", "asd", "aaaa")
newLog3.SetHandler(log.CallerFuncHandler(log.StreamHandler(os.Stdout, log.TerminalFormat())))
newLog3.Debug("3333", "asd", "aaaa")
newLog3.SetHandler(log.CallerFileHandler(log.StreamHandler(os.Stdout, log.JsonFormat())))
newLog3.Debug("4444", "asd", "aaaa")
log.Root().SetHandler(log.StderrHandler)
logLevel := "111"
switch logLevel {
case "debug":
log.SetOutLevel(log.LvlDebug)
case "info":
log.SetOutLevel(log.LvlInfo)
case "warn":
log.SetOutLevel(log.LvlWarn)
default:
log.SetOutLevel(log.LvlTrace)
}
log.Log("asdasdas")
log.Debug("a", "1", 2, "3", 4, "5", 6, "7", 8, "9", 10)
//nCtx:=context.WithValue(context.Background(),"trace","9527")
//log.FatalContext(nCtx,"12","11","22")
log.DebugContext(context.Background(), "a", "1", 2, "3", 4, "5", 6, "7", 8, "9", 10)
ctx := context.WithValue(context.Background(), "request_id", "asdasdkjcxizcjci")
log.LogContext(ctx, "1", "123", "123123")
log.FatalContext(ctx, "asdas", "213", "12312", "1111")
}
|
package args_test
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/go-task/task/v3/args"
"github.com/go-task/task/v3/internal/orderedmap"
"github.com/go-task/task/v3/taskfile"
)
func TestArgsV3(t *testing.T) {
tests := []struct {
Args []string
ExpectedCalls []taskfile.Call
ExpectedGlobals *taskfile.Vars
}{
{
Args: []string{"task-a", "task-b", "task-c"},
ExpectedCalls: []taskfile.Call{
{Task: "task-a", Direct: true},
{Task: "task-b", Direct: true},
{Task: "task-c", Direct: true},
},
},
{
Args: []string{"task-a", "FOO=bar", "task-b", "task-c", "BAR=baz", "BAZ=foo"},
ExpectedCalls: []taskfile.Call{
{Task: "task-a", Direct: true},
{Task: "task-b", Direct: true},
{Task: "task-c", Direct: true},
},
ExpectedGlobals: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"FOO": {Static: "bar"},
"BAR": {Static: "baz"},
"BAZ": {Static: "foo"},
},
[]string{"FOO", "BAR", "BAZ"},
),
},
},
{
Args: []string{"task-a", "CONTENT=with some spaces"},
ExpectedCalls: []taskfile.Call{
{Task: "task-a", Direct: true},
},
ExpectedGlobals: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"CONTENT": {Static: "with some spaces"},
},
[]string{"CONTENT"},
),
},
},
{
Args: []string{"FOO=bar", "task-a", "task-b"},
ExpectedCalls: []taskfile.Call{
{Task: "task-a", Direct: true},
{Task: "task-b", Direct: true},
},
ExpectedGlobals: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"FOO": {Static: "bar"},
},
[]string{"FOO"},
),
},
},
{
Args: nil,
ExpectedCalls: []taskfile.Call{
{Task: "default", Direct: true},
},
},
{
Args: []string{},
ExpectedCalls: []taskfile.Call{
{Task: "default", Direct: true},
},
},
{
Args: []string{"FOO=bar", "BAR=baz"},
ExpectedCalls: []taskfile.Call{
{Task: "default", Direct: true},
},
ExpectedGlobals: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"FOO": {Static: "bar"},
"BAR": {Static: "baz"},
},
[]string{"FOO", "BAR"},
),
},
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("TestArgs%d", i+1), func(t *testing.T) {
calls, globals := args.ParseV3(test.Args...)
assert.Equal(t, test.ExpectedCalls, calls)
if test.ExpectedGlobals.Len() > 0 || globals.Len() > 0 {
assert.Equal(t, test.ExpectedGlobals.Keys(), globals.Keys())
assert.Equal(t, test.ExpectedGlobals.Values(), globals.Values())
}
})
}
}
func TestArgsV2(t *testing.T) {
tests := []struct {
Args []string
ExpectedCalls []taskfile.Call
ExpectedGlobals *taskfile.Vars
}{
{
Args: []string{"task-a", "task-b", "task-c"},
ExpectedCalls: []taskfile.Call{
{Task: "task-a", Direct: true},
{Task: "task-b", Direct: true},
{Task: "task-c", Direct: true},
},
},
{
Args: []string{"task-a", "FOO=bar", "task-b", "task-c", "BAR=baz", "BAZ=foo"},
ExpectedCalls: []taskfile.Call{
{
Task: "task-a",
Direct: true,
Vars: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"FOO": {Static: "bar"},
},
[]string{"FOO"},
),
},
},
{Task: "task-b", Direct: true},
{
Task: "task-c",
Direct: true,
Vars: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"BAR": {Static: "baz"},
"BAZ": {Static: "foo"},
},
[]string{"BAR", "BAZ"},
),
},
},
},
},
{
Args: []string{"task-a", "CONTENT=with some spaces"},
ExpectedCalls: []taskfile.Call{
{
Task: "task-a",
Direct: true,
Vars: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"CONTENT": {Static: "with some spaces"},
},
[]string{"CONTENT"},
),
},
},
},
},
{
Args: []string{"FOO=bar", "task-a", "task-b"},
ExpectedCalls: []taskfile.Call{
{Task: "task-a", Direct: true},
{Task: "task-b", Direct: true},
},
ExpectedGlobals: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"FOO": {Static: "bar"},
},
[]string{"FOO"},
),
},
},
{
Args: nil,
ExpectedCalls: []taskfile.Call{
{Task: "default", Direct: true},
},
},
{
Args: []string{},
ExpectedCalls: []taskfile.Call{
{Task: "default", Direct: true},
},
},
{
Args: []string{"FOO=bar", "BAR=baz"},
ExpectedCalls: []taskfile.Call{
{Task: "default", Direct: true},
},
ExpectedGlobals: &taskfile.Vars{
OrderedMap: orderedmap.FromMapWithOrder(
map[string]taskfile.Var{
"FOO": {Static: "bar"},
"BAR": {Static: "baz"},
},
[]string{"FOO", "BAR"},
),
},
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("TestArgs%d", i+1), func(t *testing.T) {
calls, globals := args.ParseV2(test.Args...)
assert.Equal(t, test.ExpectedCalls, calls)
if test.ExpectedGlobals.Len() > 0 || globals.Len() > 0 {
assert.Equal(t, test.ExpectedGlobals, globals)
}
})
}
}
|
package single
import (
"fmt"
)
/*
在某个节点后面插入节点
在某个节点前面插入节点
在链表头部插入节点
链表尾部插入节点
通过索引查找节点
删除传入的节点
打印链表
*/
type ListNode struct{
next *ListNode
value interface{}
}
type LinkedList struct{
head *ListNode
len uint
}
func NewListNode(v interface{}) *ListNode {
return &ListNode{nil, v}
}
func (node *ListNode) Value() interface{}{
return node.value
}
func (node *ListNode) Next() *ListNode {
return node.next
}
func NewLinkedList() *LinkedList {
return &LinkedList{NewListNode(0),0}
}
func (list *LinkedList)InsertAfter(node *ListNode, v interface{}) bool {
if node == nil {
return false
}
newNode := NewListNode(v)
newNode.next = node.next
node.next = newNode
list.len++
return true
}
func (list *LinkedList)InsertBefore(node *ListNode, v interface{}) bool {
if node == nil {
return false
}
cur := list.head.next
pre := list.head
for cur != nil{
if cur == node{
break
}
pre = cur
cur = cur.next
}
if cur == nil {
return false
}
newNode := NewListNode(v)
newNode.next = cur
pre.next=newNode
list.len++
return true
}
func (list *LinkedList)InsertToHead(v interface{}) bool {
return list.InsertAfter(list.head,v)
}
func (list *LinkedList)InsertToTail(v interface{}) bool {
cur := list.head
for cur.next != nil {
cur = cur.next
}
return list.InsertAfter(cur, v)
}
func (list *LinkedList)FindIndex(index uint) *ListNode{
if index >= list.len{
return nil
}
cur := list.head.next
var i uint
for ; i <index;i++{
cur = cur.next
}
return cur
}
func (list *LinkedList)Delete(node *ListNode) bool{
if node == nil {
return false
}
cur := list.head.next
pre := list.head
for cur != nil{
if cur == node{
break
}
pre = cur
cur = cur.next
}
if cur == nil{
return false
}
pre.next = cur.next
node = nil
list.len--
return true
}
func (list *LinkedList)Print(){
cur := list.head
format := ""
for cur != nil{
format += fmt.Sprintf("%+v", cur.Value())
cur = cur.next
if cur != nil {
format += "->"
}
}
fmt.Println(format)
}
func (list *LinkedList)Revert() {
if list.head == nil || list.head.next == nil || list.head.next.next == nil {
return
}
var pre *ListNode
cur := list.head.next
for cur != nil {
tmp := cur.next
cur.next = pre
pre = cur
cur = tmp
}
list.head.next = pre
}
func MergeSorted(l1,l2 *LinkedList) *LinkedList {
if l1 == nil || l1.head == nil || l1.head.next == nil {
return l2
}
if l2 == nil || l2.head == nil || l2.head.next == nil {
return l1
}
l := &LinkedList{head:&ListNode{}}
cur := l.head
cur1 := l1.head.next
cur2 := l2.head.next
if cur1 != nil && cur2 != nil{
if cur1.Value().(int) > cur2.Value().(int){
cur.next = cur2
cur2 = cur2.next
} else {
cur.next = cur1
cur1 = cur1.next
}
cur = cur.next
}
if cur1 != nil {
cur.next = cur1
} else if cur2 != nil{
cur.next = cur2
}
return l
}
func (list *LinkedList)DeleteBottomN(n int) {
if n < 0 || list.head == nil || list.head.next == nil {
return
}
fast := list.head
for i := 0; i <= n; i++ {
fast = fast.next
}
if fast == nil{
return
}
slow := list.head
for fast.next != nil {
slow = slow.next
fast = fast.next
}
slow.next = slow.next.next
}
func (list *LinkedList) FindMiddleNode() *ListNode {
if list.head == nil || list.head.next == nil {
return nil
}
if list.head.next.next == nil {
return list.head.next
}
slow, fast := list.head, list.head
for fast != nil && fast.next != nil {
slow = slow.next
fast = fast.next.next
}
return slow
} |
package apachetizer
import (
"encoding/json"
"log"
"os"
"reflect"
"testing"
)
func TestVHostConfDetector(t *testing.T) {
got, err := VHostConfDetector("./etc/apache2/sites-available")
if err != nil {
log.Fatal(err)
}
if reflect.TypeOf(got).Kind() != reflect.Slice {
panic(got)
} else {
log.Println("VHostConfDetector successfully returns a slice (string array)")
}
}
func TestVHostConfParser(t *testing.T) {
Reader, err := os.Open("./etc/apache2/testconfig-le-ssl.conf")
if err != nil {
panic(err)
}
config, _ := VHostConfParser(Reader)
jsonEncoded, _ := json.Marshal(config)
log.Println(string(jsonEncoded))
}
|
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"regexp"
"strings"
"github.com/BurntSushi/xgb/xproto"
"github.com/BurntSushi/xgbutil"
"github.com/BurntSushi/xgbutil/ewmh"
"github.com/BurntSushi/xgbutil/icccm"
"github.com/chrispickard/btf/version"
"github.com/mattn/go-shellwords"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
app = kingpin.New("btf", "btf(1) is a system utility that will find, focus and launch windows on your X11 desktop.")
list = app.Flag("list", "list all properties").Short('l').Bool()
matches = app.Flag("match", "Class or Title to match").Short('m').Strings()
excludes = app.Flag("exclude", "Class or Title to exclude").Short('e').Strings()
program = app.Arg("program", "program to launch if matching fails").Strings()
)
type Window struct {
Class string
Instance string
Name string
ID xproto.Window
}
func BuildProperties(X *xgbutil.XUtil) ([]*Window, error) {
// Connect to the X server using the DISPLAY environment variable.
// Get a list of all client ids.
clientids, err := ewmh.ClientListGet(X)
if err != nil {
log.Fatal(err)
}
var windows []*Window
// Iterate through each client, find its name and find its size.
for _, clientid := range clientids {
name, err := ewmh.WmNameGet(X, clientid)
// If there was a problem getting _NET_WM_NAME or if its empty,
// try the old-school version.
// if err != nil || len(name) == 0 {
// name, err = icccm.WmNameGet(X, clientid)
// // If we still can't find anything, give up.
// if err != nil || len(name) == 0 {
// return nil, err
// }
// }
// If we still can't find anything, give up.
if err != nil || len(name) == 0 {
return nil, err
}
class, err := icccm.WmClassGet(X, clientid)
if err != nil || len(name) == 0 {
return nil, err
}
window := &Window{
Class: class.Class,
Instance: class.Instance,
Name: name,
ID: clientid,
}
windows = append(windows, window)
}
return windows, nil
}
// PrintProperties dumps the properties of `windows` to `w`
func PrintProperties(windows []*Window, w io.Writer) {
for _, window := range windows {
fmt.Fprintf(w, "%s %s %s %v\n", window.Class, window.Instance, window.Name, window.ID)
}
}
// FocusWindow ...
func FocusWindow(X *xgbutil.XUtil, id xproto.Window) error {
return ewmh.ActiveWindowReq(X, id)
}
// from https://www.calhoun.io/concatenating-and-building-strings-in-go/
func join(strs ...string) string {
var sb strings.Builder
for _, str := range strs {
sb.WriteString(str)
}
return sb.String()
}
// largely from https://www.calhoun.io/concatenating-and-building-strings-in-go/
func buildRegex(excludes []string) (*regexp.Regexp, error) {
var sb strings.Builder
for _, str := range excludes {
s := regexp.QuoteMeta(str)
sb.WriteString(s)
}
return regexp.Compile(sb.String())
}
func main() {
app.Version(version.VERSION)
app.Parse(os.Args)
X, err := xgbutil.NewConn()
if err != nil {
log.Fatal(err)
}
if !*list && len(*program) == 1 {
app.FatalUsage("either --list or <program> is required")
}
r, err := buildRegex(*matches)
if err != nil {
log.Fatal(err)
}
excluder, err := buildRegex(*excludes)
if err != nil {
log.Fatal(err)
}
windows, err := BuildProperties(X)
if err != nil {
log.Fatal(err)
}
if *list {
PrintProperties(windows, os.Stdout)
os.Exit(0)
}
for _, w := range windows {
if r.FindString(w.Name) != "" || r.FindString(w.Class) != "" || r.FindString(w.Instance) != "" {
if excluder.FindString(w.Name) == "" && excluder.FindString(w.Class) == "" && excluder.FindString(w.Instance) == "" {
err := FocusWindow(X, w.ID)
if err != nil {
log.Println(err)
}
os.Exit(0)
}
}
}
args := (*program)[1:]
line := join(args...)
fmt.Println("not found, opening", line)
words, err := shellwords.Parse(line)
if err != nil {
log.Fatal(err)
}
err = exec.Command(words[0], words[1:]...).Start()
if err != nil {
log.Fatal(err)
}
}
|
package set1
import (
"bytes"
"encoding/hex"
"testing"
)
func TestRepeatingKeyXOR(t *testing.T) {
input := []byte(`Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal`)
key := []byte("ICE")
expected := "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"
xored := RepeatingKeyXOR(input, key)
if !bytes.Equal(xored, decodeHex(expected)) {
t.Error("Failed to XOR encode by repeating key. Expected", expected, "got", hex.EncodeToString(xored))
}
}
|
package public
import (
"github.com/google/go-querystring/query"
"github.com/pkg/errors"
"github.com/potix/gobitflyer/client"
)
const (
getChatsPath string = "/v1/getchats"
)
type GetChatsResponse []*GetChatsChat
type GetChatsChat struct {
Nickname string `json:"nickname"`
Message string `json:"message"`
Date string `json:"date"`
}
type GetChatsRequest struct {
Path string `url:"-"`
FromDate int64 `url:"from_date,omitempty"`
}
func (r *GetChatsRequest) CreateHTTPRequest(endpoint string) (*client.HTTPRequest, error) {
v, err := query.Values(r)
if err != nil {
return nil, errors.Wrapf(err, "can not create query of get chats request")
}
query := v.Encode()
pathQuery := r.Path + "?" + query
return &client.HTTPRequest {
PathQuery: pathQuery,
URL: endpoint + pathQuery,
Method: "GET",
Headers: nil,
Body: nil,
}, nil
}
func NewGetChatsRequest(fromDate int64) (*GetChatsRequest) {
return &GetChatsRequest{
Path: getChatsPath,
FromDate: fromDate,
}
}
|
/*
Copyright 2023 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or 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 tracing_test
import (
"testing"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/context/store"
"github.com/stretchr/testify/require"
"github.com/docker/compose/v2/internal/tracing"
)
var testStoreCfg = store.NewConfig(
func() interface{} {
return &map[string]interface{}{}
},
)
func TestExtractOtelFromContext(t *testing.T) {
if testing.Short() {
t.Skip("Requires filesystem access")
}
dir := t.TempDir()
st := store.New(dir, testStoreCfg)
err := st.CreateOrUpdate(store.Metadata{
Name: "test",
Metadata: command.DockerContext{
Description: t.Name(),
AdditionalFields: map[string]interface{}{
"otel": map[string]interface{}{
"OTEL_EXPORTER_OTLP_ENDPOINT": "localhost:1234",
},
},
},
Endpoints: make(map[string]interface{}),
})
require.NoError(t, err)
cfg, err := tracing.ConfigFromDockerContext(st, "test")
require.NoError(t, err)
require.Equal(t, "localhost:1234", cfg.Endpoint)
}
|
package delivery
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/vivaldy22/cleanEnigmaSchool/models"
"github.com/vivaldy22/cleanEnigmaSchool/tools/msgJson"
"github.com/vivaldy22/cleanEnigmaSchool/tools/varMux"
)
type TeacherHandler struct {
TUseCase models.TeacherUseCase
}
func NewTeacherHandler(tu models.TeacherUseCase, router *mux.Router) {
handler := &TeacherHandler{TUseCase: tu}
router.HandleFunc("/teachers", handler.ShowTeachers).Methods(http.MethodGet)
router.HandleFunc("/teacher", handler.CreateTeacher).Methods(http.MethodPost)
router.HandleFunc("/teacher/{id}", handler.GetTeacherByID).Methods(http.MethodGet)
router.HandleFunc("/teacher/{id}", handler.UpdateTeacher).Methods(http.MethodPut)
router.HandleFunc("/teacher/{id}", handler.RemoveTeacher).Methods(http.MethodDelete)
}
func (t *TeacherHandler) ShowTeachers(w http.ResponseWriter, r *http.Request) {
var resp *msgJson.ResponseMessage
data, err := t.TUseCase.Fetch()
if err != nil {
resp = msgJson.Response("ShowTeachers Failed", http.StatusNotFound, nil, err)
} else {
log.Println("Endpoint hit: FetchTeachers")
resp = msgJson.Response("Teachers Data", http.StatusOK, data, nil)
}
msgJson.WriteJSON(resp, w)
}
func (t *TeacherHandler) GetTeacherByID(w http.ResponseWriter, r *http.Request) {
var resp *msgJson.ResponseMessage
id := varMux.GetVarsMux("id", r)
data, err := t.TUseCase.GetByID(id)
if err != nil {
resp = msgJson.Response("GetTeacherByID Failed", http.StatusNotFound, nil, err)
} else {
log.Println("Endpoint hit: GetTeacherByID")
resp = msgJson.Response("Teacher Data", http.StatusOK, data, nil)
}
msgJson.WriteJSON(resp, w)
}
func (t *TeacherHandler) CreateTeacher(w http.ResponseWriter, r *http.Request) {
var resp *msgJson.ResponseMessage
var teacher *models.Teacher
err := json.NewDecoder(r.Body).Decode(&teacher)
if err != nil {
resp = msgJson.Response("Decode failed", http.StatusBadRequest, nil, err)
} else {
err = t.TUseCase.Store(teacher)
if err != nil {
resp = msgJson.Response("CreateTeacher failed", http.StatusBadRequest, nil, err)
} else {
log.Println("Endpoint hit: CreateTeacher")
resp = msgJson.Response("CreateTeacher success", http.StatusCreated, teacher, nil)
}
}
msgJson.WriteJSON(resp, w)
}
func (t *TeacherHandler) RemoveTeacher(w http.ResponseWriter, r *http.Request) {
var resp *msgJson.ResponseMessage
id := varMux.GetVarsMux("id", r)
data, err := t.TUseCase.GetByID(id)
if err != nil {
log.Println(err)
resp = msgJson.Response("Data not found", http.StatusNotFound, nil, err)
} else {
err := t.TUseCase.Delete(id)
if err != nil {
log.Println(err)
resp = msgJson.Response("Delete failed", http.StatusNotFound, nil, err)
} else {
log.Println("Endpoint hit: RemoveTeacher")
resp = msgJson.Response("Delete success", http.StatusOK, data, nil)
}
}
msgJson.WriteJSON(resp, w)
}
func (t *TeacherHandler) UpdateTeacher(w http.ResponseWriter, r *http.Request) {
var resp *msgJson.ResponseMessage
var teacher *models.Teacher
err := json.NewDecoder(r.Body).Decode(&teacher)
if err != nil {
log.Println(err)
resp = msgJson.Response("Decode failed", http.StatusBadRequest, nil, err)
} else {
id := varMux.GetVarsMux("id", r)
data, err := t.TUseCase.GetByID(id)
if err != nil {
log.Println(err)
resp = msgJson.Response("Data not found", http.StatusNotFound, nil, err)
} else {
err = t.TUseCase.Update(id, teacher)
if err != nil {
log.Println(err)
resp = msgJson.Response("Update failed", http.StatusNotFound, nil, err)
} else {
log.Println("Endpoint hit: UpdateTeacher")
resp = msgJson.Response("Update success", http.StatusOK, data, nil)
}
}
}
msgJson.WriteJSON(resp, w)
}
|
/*
Copyright 2017 Mirantis
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 libvirttools
import (
"fmt"
"strings"
// use this instead of "gopkg.in/yaml.v2" so we don't get
// map[interface{}]interface{} when unmarshalling cloud-init data
"github.com/ghodss/yaml"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"github.com/Mirantis/virtlet/pkg/metadata/types"
"github.com/Mirantis/virtlet/pkg/utils"
)
func init() {
types.SetExternalDataLoader(loadExternalUserData)
}
func loadExternalUserData(va *types.VirtletAnnotations, ns string, podAnnotations map[string]string) error {
if ns == "" {
return nil
}
var clientset *kubernetes.Clientset
var err error
userDataSourceKey := podAnnotations[types.CloudInitUserDataSourceKeyName]
sshKeySourceKey := podAnnotations[types.SSHKeySourceKeyName]
if userDataSourceKey != "" || sshKeySourceKey != "" {
if clientset == nil {
clientset, err = utils.GetK8sClientset(nil)
if err != nil {
return err
}
}
}
if userDataSourceKey != "" {
err = loadUserDataFromDataSource(va, ns, userDataSourceKey, clientset)
if err != nil {
return err
}
}
if sshKeySourceKey != "" {
err = loadSSHKeysFromDataSource(va, ns, sshKeySourceKey, clientset)
if err != nil {
return err
}
}
return nil
}
func loadUserDataFromDataSource(va *types.VirtletAnnotations, ns, key string, clientset *kubernetes.Clientset) error {
parts := strings.Split(key, "/")
if len(parts) != 2 {
return fmt.Errorf("invalid %s annotation format. Expected kind/name, but insted got %s", types.CloudInitUserDataSourceKeyName, key)
}
ud, err := readK8sKeySource(parts[0], parts[1], ns, "", clientset)
if err != nil {
return err
}
va.UserData = map[string]interface{}{}
for k, v := range ud {
var value interface{}
if yaml.Unmarshal([]byte(v), &value) == nil {
va.UserData[k] = value
}
}
return nil
}
func loadSSHKeysFromDataSource(va *types.VirtletAnnotations, ns, key string, clientset *kubernetes.Clientset) error {
parts := strings.Split(key, "/")
if len(parts) != 2 && len(parts) != 3 {
return fmt.Errorf("invalid %s annotation format. Expected kind/name[/key], but insted got %s", types.SSHKeySourceKeyName, key)
}
dataKey := "authorized_keys"
if len(parts) == 3 {
dataKey = parts[2]
}
ud, err := readK8sKeySource(parts[0], parts[1], ns, dataKey, clientset)
if err != nil {
return err
}
sshKeys := ud[dataKey]
keys := strings.Split(sshKeys, "\n")
for _, k := range keys {
k = strings.TrimSpace(k)
if k != "" {
va.SSHKeys = append(va.SSHKeys, k)
}
}
return nil
}
func readK8sKeySource(sourceType, sourceName, ns, key string, clientset *kubernetes.Clientset) (map[string]string, error) {
sourceType = strings.ToLower(sourceType)
switch sourceType {
case "secret":
secret, err := clientset.CoreV1().Secrets(ns).Get(sourceName, meta_v1.GetOptions{})
if err != nil {
return nil, err
}
if key != "" {
return map[string]string{key: string(secret.Data[key])}, nil
}
result := map[string]string{}
for k, v := range secret.Data {
result[k] = string(v)
}
return result, nil
case "configmap":
configmap, err := clientset.CoreV1().ConfigMaps(ns).Get(sourceName, meta_v1.GetOptions{})
if err != nil {
return nil, err
}
if key != "" {
return map[string]string{key: configmap.Data[key]}, nil
}
result := map[string]string{}
for k, v := range configmap.Data {
result[k] = v
}
return result, nil
default:
return nil, fmt.Errorf("unsupported source kind %s. Must be one of (secret, configmap)", sourceType)
}
}
// TODO: create a test for loadExternalUserData
|
package domains
type User struct {
UserId string `json:"user_id"`
Name string `json:"name"`
Age int `json:"age"`
}
|
package db
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
type Map map[string]any
// Value implements the driver.Valuer interface.
func (m Map) Value() (driver.Value, error) {
b, err := json.Marshal(m)
return b, err
}
// Scan implements the sql.Scanner interface.
func (m *Map) Scan(value any) error {
dbMap := make(map[string]any)
if value == nil {
*m = dbMap
return nil
}
if buf, ok := value.(string); ok {
value = []byte(buf)
}
buf, ok := value.([]byte)
if !ok {
return fmt.Errorf("canot parse %T to bytes", value)
}
if err := json.Unmarshal(buf, &dbMap); err != nil {
return err
}
*m = dbMap
return nil
}
|
package main
import "fmt"
import "asyncapi"
func main(){
c := asyncapi.Controller{}
fmt.Printf("%v", c)
}
|
package main
import (
"fmt"
s "strings"
)
func main() {
fmt.Println("Contains: ", s.Contains("test", "es"))
fmt.Println("Count: ", s.Count("test", "t"))
fmt.Println("HasPrefix: ", s.HasPrefix("test", "te"))
fmt.Println("HasSuffix:", s.HasSuffix("test", "st"))
fmt.Println("Index:", s.Index("test", "e"))
fmt.Println("Join:", s.Join([]string{"Hello", "World"}, " "))
fmt.Println("Repeat:", s.Repeat("blah ", 6))
fmt.Println("Replace:", s.Replace("test", "t", "z", 1))
fmt.Println("Replace:", s.Replace("test", "t", "d", -1))
fmt.Println("Split:", s.Split("test", "e"))
fmt.Println("ToLower:", s.ToLower("TEST"))
fmt.Println("ToUpper:", s.ToUpper("test"))
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package inputsimulations
import (
"context"
"fmt"
"math"
"time"
"chromiumos/tast/common/action"
"chromiumos/tast/errors"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/display"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/mouse"
"chromiumos/tast/local/coords"
"chromiumos/tast/local/input"
"chromiumos/tast/testing"
)
// MoveMouseFor moves the mouse in a spiral according to r = theta, starting at the
// center of the screen. The mouse position is reset to the center of the screen once it
// reaches the border of the screen. Using this math function allows for both specifying
// a path for the mouse without defining coordinates in advance, as well as progressively
// increasing the speed that the mouse moves.
func MoveMouseFor(ctx context.Context, tconn *chrome.TestConn, duration time.Duration) error {
info, err := display.GetPrimaryInfo(ctx, tconn)
if err != nil {
return errors.Wrap(err, "failed to get the primary display info")
}
// Time to move the mouse between points.
const deltaTime = 500 * time.Millisecond
// How long it takes to spiral to the edge of the screen.
const singleSpiralDuration = 2 * time.Minute
// Maximum radius of the spiral before it is reset.
maxRadius := math.Min(float64(info.Bounds.Width), float64(info.Bounds.Height)) / 2.0
center := info.Bounds.CenterPoint()
now := time.Now()
endTime := now.Add(duration)
for spiralStartTime := now; ; spiralStartTime = spiralStartTime.Add(singleSpiralDuration) {
// Move mouse to the center of the screen.
if err := mouse.Move(tconn, center, 0)(ctx); err != nil {
return errors.Wrap(err, "failed to move mouse")
}
// Move the mouse in a spiral.
spiralEndTime := spiralStartTime.Add(singleSpiralDuration)
for {
targetTime := time.Now().Add(deltaTime)
if !targetTime.Before(endTime) {
return nil
} else if !targetTime.Before(spiralEndTime) {
break
}
timeSinceSpiralStart := targetTime.Sub(spiralStartTime)
a := float64(timeSinceSpiralStart) / float64(singleSpiralDuration)
theta := a * maxRadius
point := coords.NewPoint(
center.X+int(theta*math.Cos(theta)),
center.Y+int(theta*math.Sin(theta)))
if err := mouse.Move(tconn, point, deltaTime)(ctx); err != nil {
return errors.Wrap(err, "failed to move mouse")
}
if err := testing.Sleep(ctx, time.Second); err != nil {
return errors.Wrap(err, "failed to sleep")
}
}
}
}
// ScrollMouseDownFor rolls the scroll wheel for |duration|, with a |delay|
// between ticks.
func ScrollMouseDownFor(ctx context.Context, mw *input.MouseEventWriter, delay, duration time.Duration) error {
if err := runActionFor(ctx, duration, action.Combine(
"scroll down and sleep",
func(ctx context.Context) error { return mw.ScrollDown() },
action.Sleep(delay),
)); err != nil {
return errors.Wrap(err, "failed to scroll down repeatedly")
}
return nil
}
// RepeatMousePressFor presses the left mouse button at the current
// location for |pressDuration| and then releases it. This action
// is repeated until |totalDuration| has passed.
func RepeatMousePressFor(ctx context.Context, mw *input.MouseEventWriter, delay, pressDuration, totalDuration time.Duration) error {
return runActionFor(ctx, totalDuration, action.Combine(
"mouse press, sleep, and mouse release",
func(ctx context.Context) error { return mw.Press() },
action.Sleep(pressDuration),
func(ctx context.Context) error { return mw.Release() },
action.Sleep(delay),
))
}
// RunDragMouseCycle presses the left mouse button at the center of the
// screen, and moves the mouse to the leftmost side of the screen and
// then to the rightmost side, then releases the mouse back at the
// center of the screen. This function can easily incorporate mouse
// drag actions on the screen, by highlighting elements of the page
// with minimal side effects for the test itself. This function works
// best when the center of the screen is a highlightable webpage, such
// as a Google Sheet or a Google Doc.
func RunDragMouseCycle(ctx context.Context, tconn *chrome.TestConn, info *display.Info) error {
return action.Combine(
"drag mouse from center of page to the left and right sides and then back to the center",
mouse.Move(tconn, info.Bounds.CenterPoint(), 500*time.Millisecond),
mouse.Press(tconn, mouse.LeftButton),
mouse.Move(tconn, info.Bounds.LeftCenter(), 500*time.Millisecond),
mouse.Move(tconn, info.Bounds.RightCenter(), time.Second),
mouse.Move(tconn, info.Bounds.CenterPoint(), 500*time.Millisecond),
mouse.Release(tconn, mouse.LeftButton),
action.Sleep(500*time.Millisecond),
)(ctx)
}
// RepeatMouseScroll scrolls down if |scrollDown| is true and up if it
// is false |n| times, with a |delay| in between each scroll tick.
func RepeatMouseScroll(ctx context.Context, mw *input.MouseEventWriter, scrollDown bool, delay time.Duration, n int) error {
dir := "up"
scroll := mw.ScrollUp
if scrollDown {
scroll = mw.ScrollDown
dir = "down"
}
return uiauto.Repeat(
n,
action.Combine(
fmt.Sprintf("scroll %s and sleep", dir),
func(ctx context.Context) error { return scroll() },
action.Sleep(delay),
),
)(ctx)
}
|
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package wmp
import (
"context"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/apps"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/ash"
"chromiumos/tast/local/chrome/browser"
"chromiumos/tast/local/chrome/browser/browserfixt"
"chromiumos/tast/local/chrome/display"
"chromiumos/tast/local/chrome/uiauto/faillog"
"chromiumos/tast/local/chrome/uiauto/filesapp"
"chromiumos/tast/local/chrome/uiauto/mouse"
"chromiumos/tast/local/coords"
"chromiumos/tast/testing"
"chromiumos/tast/testing/hwdep"
)
type windowSnapAndRotateTestParam struct {
portrait bool
bt browser.Type
}
func init() {
testing.AddTest(&testing.Test{
Func: WindowSnapAndRotate,
LacrosStatus: testing.LacrosVariantExists,
Desc: "In clamshell mode, checks that snap in landscape and portrait works properly",
Contacts: []string{
"zxdan@chromium.org",
"chromeos-wmp@google.com",
"chromeos-sw-engprod@google.com",
},
Attr: []string{"group:mainline", "informational"},
SoftwareDeps: []string{"chrome"},
HardwareDeps: hwdep.D(hwdep.InternalDisplay()),
Params: []testing.Param{{
Name: "portrait",
Fixture: "chromeLoggedIn",
Val: windowSnapAndRotateTestParam{portrait: true, bt: browser.TypeAsh},
}, {
Name: "landscape",
Fixture: "chromeLoggedIn",
Val: windowSnapAndRotateTestParam{portrait: false, bt: browser.TypeAsh},
}, {
Name: "portrait_lacros",
Fixture: "lacros",
ExtraSoftwareDeps: []string{"lacros"},
Val: windowSnapAndRotateTestParam{portrait: true, bt: browser.TypeLacros},
}, {
Name: "landscape_lacros",
Fixture: "lacros",
ExtraSoftwareDeps: []string{"lacros"},
Val: windowSnapAndRotateTestParam{portrait: false, bt: browser.TypeLacros},
}},
})
}
func WindowSnapAndRotate(ctx context.Context, s *testing.State) {
// Reserve a few seconds for various cleanup.
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 10*time.Second)
defer cancel()
cr := s.FixtValue().(chrome.HasChrome).Chrome()
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to connect to test API: ", err)
}
defer faillog.DumpUITreeOnError(cleanupCtx, s.OutDir(), s.HasError, tconn)
// Ensure there is no window open before test starts.
if err := ash.CloseAllWindows(ctx, tconn); err != nil {
s.Fatal("Failed to ensure no window is open: ", err)
}
info, err := display.GetInternalInfo(ctx, tconn)
if err != nil {
s.Fatal("Failed to obtain internal display info: ", err)
}
// Rotate the screen if it is a portrait test.
portrait := s.Param().(windowSnapAndRotateTestParam).portrait
portraitByDefault := info.Bounds.Height > info.Bounds.Width
rotations := []display.RotationAngle{display.Rotate0, display.Rotate90, display.Rotate180, display.Rotate270}
rotIndex := 0
if portrait != portraitByDefault {
if portrait {
// Start with primary portrait which is |display.Rotate270| from the primary landscape display.
rotIndex = 3
} else {
// Start with primary landscape which is |display.Rotate90| from the primary portrait display.
rotIndex = 1
}
if err = display.SetDisplayRotationSync(ctx, tconn, info.ID, rotations[rotIndex]); err != nil {
s.Fatal("Failed to rotate display: ", err)
}
defer display.SetDisplayRotationSync(cleanupCtx, tconn, info.ID, display.Rotate0)
}
// Obtain the latest display info after rotating the display.
info, err = display.GetInternalInfo(ctx, tconn)
if err != nil {
s.Fatal("Failed to obtain internal display info: ", err)
}
// Open two windows, a browser and a File app.
bt := s.Param().(windowSnapAndRotateTestParam).bt
conn, _, closeBrowser, err := browserfixt.SetUpWithURL(ctx, cr, bt, chrome.NewTabURL)
if err != nil {
s.Fatal("Failed to start browser: ", err)
}
defer closeBrowser(cleanupCtx)
defer conn.Close()
if _, err := filesapp.Launch(ctx, tconn); err != nil {
s.Fatal("Failed to launch the Files app: ", err)
}
if err := ash.WaitForApp(ctx, tconn, apps.FilesSWA.ID, 10*time.Second); err != nil {
s.Fatal("Files app did not appear in shelf after launch: ", err)
}
cleanup, err := ash.EnsureTabletModeEnabled(ctx, tconn, false)
if err != nil {
s.Fatal("Failed to ensure clamshell mode: ", err)
}
defer cleanup(cleanupCtx)
// Set the state of browser window and Files window to normal.
if err := ash.ForEachWindow(ctx, tconn, func(w *ash.Window) error {
return ash.SetWindowStateAndWait(ctx, tconn, w.ID, ash.WindowStateNormal)
}); err != nil {
s.Fatal("Failed to set window states: ", err)
}
windows, err := ash.GetAllWindows(ctx, tconn)
if err != nil {
s.Fatal("Failed to obtain all windows: ", err)
}
// Activate the first window.
if err := windows[0].ActivateWindow(ctx, tconn); err != nil {
s.Fatalf("Failed to activate the first window(id=%d): %v", windows[0].ID, err)
}
if window, err := ash.GetWindow(ctx, tconn, windows[0].ID); err != nil || !window.IsActive {
s.Fatalf("The first window(id=%d) is not active", windows[0].ID)
}
if err = verifyState(ctx, tconn, windows[0].ID, ash.WindowStateNormal); err != nil {
s.Fatalf("The first window(id=%d) is opened with non-default state: %v", windows[0].ID, err)
}
if err = verifyState(ctx, tconn, windows[1].ID, ash.WindowStateNormal); err != nil {
s.Fatalf("The second window(id=%d) is opened with non-default state: %v", windows[1].ID, err)
}
workArea := info.WorkArea
if portrait {
// Test drag to maximize, snap top and snap bottom.
// Drag a window to the position that y-value is greater than |kSnapTriggerVerticalMoveThreshold|
// first to make sure that it can be snapped top or maximized (see crbug/1158553).
startingWindowPosition := coords.NewPoint(workArea.CenterPoint().X, workArea.Top+100)
if err = dragWindowTo(ctx, tconn, windows[0].ID, startingWindowPosition, 0); err != nil {
s.Fatal("Failed to drag the first window to the starting position: ", err)
}
// Test that maximizing works with the presence of snap top when holding longer than a second.
topSnappedPoint := coords.NewPoint(workArea.CenterPoint().X, workArea.Top)
if err = dragWindowTo(ctx, tconn, windows[0].ID, topSnappedPoint, 1600*time.Millisecond); err != nil {
s.Fatal("Failed to drag to maximize: ", err)
}
if err = verifyState(ctx, tconn, windows[0].ID, ash.WindowStateMaximized); err != nil {
s.Fatal("Failed to maximize: ", err)
}
// Drag a window down to unmaximize and then up to snap top.
if err = dragWindowTo(ctx, tconn, windows[0].ID, startingWindowPosition, 0); err != nil {
s.Fatal("Failed to drag to unmaximize: ", err)
}
if err = dragWindowTo(ctx, tconn, windows[0].ID, topSnappedPoint, 0); err != nil {
s.Fatal("Failed to drag to snap top: ", err)
}
// TODO(crbug/1264617): Rename left and right snapped to primary and secondary snapped.
if err = verifyState(ctx, tconn, windows[0].ID, ash.WindowStateLeftSnapped); err != nil {
s.Fatal("Failed to snap top: ", err)
}
// Activate the second window to make sure it is not hidden behind |windows[0]| before
// dragging it to snap bottom.
if err = windows[1].ActivateWindow(ctx, tconn); err != nil {
s.Fatalf("Failed to activate the second window(id=%d): %v", windows[1].ID, err)
}
bottomSnappedPoint := coords.NewPoint(workArea.CenterPoint().X, workArea.BottomRight().Y)
if err = dragWindowTo(ctx, tconn, windows[1].ID, bottomSnappedPoint, 0); err != nil {
s.Fatal("Failed to drag to snap bottom: ", err)
}
// After snap both windows, tests their state.
if err = verifyState(ctx, tconn, windows[1].ID, ash.WindowStateRightSnapped); err != nil {
s.Fatal("The first window lost top-snapped state after snapping the second window to the bottom: ", err)
}
// Make sure the first window still remains primary snapped.
if err = verifyState(ctx, tconn, windows[0].ID, ash.WindowStateLeftSnapped); err != nil {
s.Fatal("Failed to snap bottom: ", err)
}
} else {
// For landscape display, test drag to snap left and right.
leftSnappedPoint := coords.NewPoint(workArea.Left, workArea.CenterPoint().Y)
if err = dragWindowTo(ctx, tconn, windows[0].ID, leftSnappedPoint, 0); err != nil {
s.Fatal("Failed to drag to snap left: ", err)
}
// Activate the second window first to make sure it is not hidden behind |windows[0]|
// before dragging it to snap right.
if err = windows[1].ActivateWindow(ctx, tconn); err != nil {
s.Fatalf("Failed to activate the second window(id=%d): %v", windows[1].ID, err)
}
rightSnappedPoint := coords.NewPoint(workArea.BottomRight().X, workArea.CenterPoint().Y)
if err = dragWindowTo(ctx, tconn, windows[1].ID, rightSnappedPoint, 0); err != nil {
s.Fatal("Failed to drag to snap right: ", err)
}
// Test states of windows after being snapped.
if err = verifyState(ctx, tconn, windows[0].ID, ash.WindowStateLeftSnapped); err != nil {
s.Fatal("Failed to snap left: ", err)
}
if err = verifyState(ctx, tconn, windows[1].ID, ash.WindowStateRightSnapped); err != nil {
s.Fatal("Failed to snap right: ", err)
}
}
// Rotate the display for all four possible orientations and makes sure that
// for each orientation, |windows[0]| and |windows[1]| remain primary and secondary
// snapped respectively.
for i := 1; i <= 4; i++ {
rot := rotations[(rotIndex+i)%len(rotations)]
if err = display.SetDisplayRotationSync(ctx, tconn, info.ID, rot); err != nil {
s.Fatal("Failed to rotate display: ", err)
}
if err = verifyState(ctx, tconn, windows[0].ID, ash.WindowStateLeftSnapped); err != nil {
s.Fatalf("The first window lost primary snapped state after rotating %d times to rotation = %v: %v", i, rot, err)
}
if err = verifyState(ctx, tconn, windows[1].ID, ash.WindowStateRightSnapped); err != nil {
s.Fatalf("The second window lost primary snapped state after rotating %d times to rotation = %v: %v", i, rot, err)
}
}
}
// verifyState checks whether the state of the window with the given id |windowID| is |wantState| or not.
func verifyState(ctx context.Context, tconn *chrome.TestConn, windowID int, wantState ash.WindowStateType) error {
window, err := ash.GetWindow(ctx, tconn, windowID)
if err != nil {
return errors.Wrapf(err, "failed to obtain window(id=%d)", windowID)
}
if window.State != wantState {
return errors.Errorf("unexpected window(id=%d) state = got %v, want %v",
windowID, window.State, wantState)
}
return nil
}
// dragWindowTo drags the caption center of the window with the given id |windowID| to |targetPoint|
// via a mouse and holds for |holdDuration| at the target point before releasing the mouse.
func dragWindowTo(ctx context.Context, tconn *chrome.TestConn, windowID int, targetPoint coords.Point, holdDuration time.Duration) error {
window, err := ash.GetWindow(ctx, tconn, windowID)
if err != nil {
return errors.Wrapf(err, "failed to obtain window(id=%d)", windowID)
}
captionCenterPoint := coords.NewPoint(window.BoundsInRoot.CenterPoint().X, window.BoundsInRoot.Top+10)
// Move the mouse to caption and press down.
if err := mouse.Move(tconn, captionCenterPoint, 100*time.Millisecond)(ctx); err != nil {
return errors.Wrap(err, "failed to move to caption")
}
if err := mouse.Press(tconn, mouse.LeftButton)(ctx); err != nil {
return errors.Wrap(err, "failed to press the button")
}
// Drag the window around.
const dragTime = 800 * time.Millisecond
if err := mouse.Move(tconn, targetPoint, dragTime)(ctx); err != nil {
return errors.Wrap(err, "failed to drag")
}
// Hold the window there for |holdDuration| before releasing the mouse.
if err := testing.Sleep(ctx, holdDuration); err != nil {
return errors.Wrap(err, "failed to sleep")
}
// Release the window. It is near the top of the screen so it should snap to maximize.
if err := mouse.Release(tconn, mouse.LeftButton)(ctx); err != nil {
return errors.Wrap(err, "failed to release the button")
}
// Wait for a window to finish snapping or maximizing animating before ending.
if err := ash.WaitWindowFinishAnimating(ctx, tconn, windowID); err != nil {
return errors.Wrap(err, "failed to wait for window animation to finish")
}
return nil
}
|
package goisgod
import (
"bytes"
"image"
// require
_ "image/gif"
"image/jpeg"
_ "image/png"
)
type GigImage struct {
key string
image *image.Image
}
func (gimg *GigImage) toByte() (bs []byte, err error) {
buf := new(bytes.Buffer)
if err = jpeg.Encode(buf, *gimg.image, nil); err != nil {
return
}
bs = buf.Bytes()
return
}
func (gimg *GigImage) fromByte(bs []byte) (err error) {
var img image.Image
buf := new(bytes.Buffer)
if _, err = buf.Write(bs); err != nil {
return
}
if img, err = jpeg.Decode(buf); err != nil {
return
}
gimg.image = &img
return
}
|
package main
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
)
func download(url string, name string) {
// Get the data
fmt.Printf("downloading %s\n", name)
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
// Check server response
if resp.StatusCode != http.StatusOK {
return
}
// Create the file
out, err := os.Create(name)
if err != nil {
return
}
defer out.Close()
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return
}
}
func main() {
file, err := os.Open("chunklist_dvr.m3u8")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
if strings.HasPrefix(text, "8t6") {
name := "media_" + strings.Split(text, "_")[3]
download(fmt.Sprintf("https://bcovlive-a.akamaihd.net/a1a395c883004c05b3184dc2ea9570f1/eu-west-1/6252938537001/profile_0/%s", text), name)
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
|
package model
import "fmt"
type TargetGraph struct {
// Targets in topological order.
sortedTargets []TargetSpec
byID map[TargetID]TargetSpec
}
func NewTargetGraph(targets []TargetSpec) (TargetGraph, error) {
sortedTargets, err := TopologicalSort(targets)
if err != nil {
return TargetGraph{}, err
}
return TargetGraph{
sortedTargets: sortedTargets,
byID: MakeTargetMap(sortedTargets),
}, nil
}
// In Tilt, Manifests should always be DAGs with a single root node
// (the deploy target). This is just a quick sanity check to make sure
// that's true, because many of our graph-traversal algorithms won't work if
// it's not true.
func (g TargetGraph) IsSingleSourceDAG() bool {
seenIDs := make(map[TargetID]bool, len(g.sortedTargets))
lastIdx := len(g.sortedTargets) - 1
for i := lastIdx; i >= 0; i-- {
t := g.sortedTargets[i]
id := t.ID()
isLastTarget := i == lastIdx
if !isLastTarget && !seenIDs[id] {
return false
}
for _, depID := range t.DependencyIDs() {
seenIDs[depID] = true
}
}
return true
}
// Visit t and its transitive dependencies in post-order (aka depth-first)
func (g TargetGraph) VisitTree(root TargetSpec, visit func(dep TargetSpec) error) error {
visitedIDs := make(map[TargetID]bool)
// pre-declare the variable, so that this function can recurse
var helper func(current TargetSpec) error
helper = func(current TargetSpec) error {
deps, err := g.DepsOf(current)
if err != nil {
return err
}
for _, dep := range deps {
if visitedIDs[dep.ID()] {
continue
}
err := helper(dep)
if err != nil {
return err
}
}
err = visit(current)
if err != nil {
return err
}
visitedIDs[current.ID()] = true
return nil
}
return helper(root)
}
// Return the direct dependency targets.
func (g TargetGraph) DepsOf(t TargetSpec) ([]TargetSpec, error) {
depIDs := t.DependencyIDs()
result := make([]TargetSpec, len(depIDs))
for i, depID := range depIDs {
dep, ok := g.byID[depID]
if !ok {
return nil, fmt.Errorf("Dep %q not found in graph", depID)
}
result[i] = dep
}
return result, nil
}
// Is this image directly deployed a container?
func (g TargetGraph) IsDeployedImage(iTarget ImageTarget) bool {
id := iTarget.ID()
for _, t := range g.sortedTargets {
switch t := t.(type) {
case K8sTarget, DockerComposeTarget:
// Returns true if a K8s or DC target directly depends on this image.
for _, depID := range t.DependencyIDs() {
if depID == id {
return true
}
}
}
}
return false
}
func (g TargetGraph) Images() []ImageTarget {
return ExtractImageTargets(g.sortedTargets)
}
// Returns all the images in the graph that are directly deployed to a container.
func (g TargetGraph) DeployedImages() []ImageTarget {
result := []ImageTarget{}
for _, iTarget := range g.Images() {
if g.IsDeployedImage(iTarget) {
result = append(result, iTarget)
}
}
return result
}
|
package history
import (
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"reflect"
"testing"
)
type (
ID string
)
func (p ID) IsZero() bool {
return p == "zero"
}
func TestMakePtr(t *testing.T) {
tests := []struct {
name string
value interface{}
}{
{
name: "non pointer",
value: Person{},
},
{
name: "pointer",
value: &Person{},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
p := makePtr(test.value)
v := reflect.ValueOf(p)
require.Equal(t, reflect.Ptr, v.Kind())
require.NotEqual(t, reflect.Ptr, reflect.Indirect(v).Kind())
})
}
}
func TestUnsetStructField(t *testing.T) {
tests := []struct {
name string
value interface{}
fieldName string
err bool
}{
{
name: "valid",
value: &Person{
FirstName: "John",
},
fieldName: "FirstName",
},
{
name: "non pointer returns an err",
value: Person{
FirstName: "John",
},
err: true,
},
{
name: "non struct returns an err",
value: func() *int {
i := 100
return &i
}(),
err: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := unsetStructField(test.value, test.fieldName)
if test.err {
require.Error(t, err)
return
}
require.NoError(t, err)
v := reflect.ValueOf(test.value)
require.True(t, v.Elem().FieldByName(test.fieldName).IsZero())
})
}
}
func TestGetPrimaryKeyValue(t *testing.T) {
a := require.New(t)
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{})
a.NoError(err)
db = db.Session(&gorm.Session{})
type Foo struct {
Bar string
}
type EntityWithIsZeroerPK struct {
ID ID
Name string
}
tests := []struct {
name string
object interface{}
expected primaryKeyField
err bool
}{
{
name: "value object",
object: Person{
Model: gorm.Model{
ID: 444,
},
FirstName: "John",
LastName: "Doe",
},
expected: primaryKeyField{
name: "ID",
value: uint(444),
isZero: false,
},
},
{
name: "pointer object",
object: &Person{
Model: gorm.Model{
ID: 444,
},
FirstName: "John",
LastName: "Doe",
},
expected: primaryKeyField{
name: "ID",
value: uint(444),
isZero: false,
},
},
{
name: "object with no primary key",
object: Foo{
Bar: "foobar",
},
err: true,
},
{
name: "object with IsZeroer PK",
object: EntityWithIsZeroerPK{
ID: "zero",
Name: "John",
},
expected: primaryKeyField{
name: "ID",
value: ID("zero"),
isZero: true,
},
},
{
name: "nil object",
object: nil,
err: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.object != nil {
err = db.Statement.Parse(test.object)
require.NoError(t, err)
}
actual, err := getPrimaryKeyValue(db, reflect.ValueOf(test.object))
if test.err {
require.Error(t, err)
return
}
require.NoError(t, err)
require.Equal(t, test.expected, *actual)
})
}
}
|
package main
import (
"strings"
"github.com/dghubble/go-twitter/twitter"
)
func analyzeSource(tweets []twitter.Tweet) map[string]int {
var sources = make(map[string]int)
for _, v := range tweets {
source := strings.Split(strings.Split(v.Source, ">")[1], "<")[0]
if _, ok := sources[source]; ok {
sources[source] = sources[source] + 1
} else {
sources[source] = 1
}
}
return (sources)
}
|
package models
// QueueInterface : queue interface
type QueueInterface map[string]interface{}
// GetperiodQWeek : get hourly period queues in week
func (q *QueueInterface) GetperiodQWeek (hID, year, week string) error {
rows, err := db.Raw(`
SELECT SUBSTRING(create_time, 1, 2) as Hour, COUNT(queue_id) as Queues
FROM Queue as Q, Hospital as H, Station as S
WHERE Q.station_id=S.station_id AND S.hospital_id=H.hospital_id AND H.hospital_id=? AND SUBSTRING(create_date, 1, 4)=?
AND DATEPART(wk, create_date)=?
GROUP BY SUBSTRING(create_time, 1, 2)
`, hID, year, week).Rows()
if err != nil {
return err
}
tmp := make(map[string]interface{})
for rows.Next() {
var hour string; var queues int32
rows.Scan(&hour, &queues)
tmp[hour] = queues
}
*q = tmp
return nil
}
// GetperiodQMonth : get hourly period queues in month
func (q *QueueInterface) GetperiodQMonth (hID, date string) error {
rows, err := db.Raw(`
SELECT SUBSTRING(create_time, 1, 2) as Hour, COUNT(queue_id) as Queues
FROM Queue as Q, dbo.Hospital as H, dbo.Station as S
WHERE Q.station_id=S.station_id and S.hospital_id=H.hospital_id and H.hospital_id=? and SUBSTRING(create_date, 1, 7)=?
GROUP BY SUBSTRING(create_time, 1, 2)
`, hID, date).Rows()
if err != nil {
return err
}
tmp := make(map[string]interface{})
for rows.Next() {
var hour string; var queues int32
rows.Scan(&hour, &queues)
tmp[hour] = queues
}
*q = tmp
return nil
}
|
package main
import (
"fmt"
"time"
)
func main() {
t1 := time.Now()
t2 := t1.Add(10 * time.Second)
sub := t1.Sub(t2)
fmt.Printf("%#v\n", sub)
}
|
package main
import "fmt"
func main() {
finger := 3
switch finger {
case 1:
fmt.Println("Thumb!")
case 2:
fmt.Println("Index")
case 3:
fmt.Println("Middle")
case 4:
fmt.Println("Ring")
case 5:
fmt.Println("Pinky")
}
num := 23
switch {
case num >= 0 && num <= 50:
fmt.Println("Between 0 and 50")
case num >= 51 && num <= 100:
fmt.Println("Between 51 and 100")
default:
fmt.Println("I don't know")
}
}
|
package ftp
import (
"os"
"github.com/aws/aws-sdk-go/aws/awserr"
)
type Test struct{}
func (test Test) Upload(filepath string, bucketName string, objectKey string) (err error) {
success := os.Getenv("IS_SUCCESS")
if success == "1" {
return nil
}
return awserr.New("ReadRequestBody", "unable to initialize upload", err)
}
|
package resolvers
import (
"context"
"fmt"
graphql "github.com/99designs/gqlgen/graphql"
json "github.com/json-iterator/go"
dataloader "github.com/proxima-one/proxima-data-vertex/pkg/dataloaders"
models "github.com/proxima-one/proxima-data-vertex/pkg/models"
proximaIterables "github.com/proxima-one/proxima-db-client-go/pkg/iterables"
)
func (r *dPoolResolver) Users(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).UserById.LoadAll(obj.UserIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.User, 0), nil
}
return results.([]*models.User), nil
//}
}
func (r *dPoolResolver) Deposits(ctx context.Context, obj *models.DPool) ([]*models.Deposit, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).DepositById.LoadAll(obj.DepositIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.Deposit, 0), nil
}
return results.([]*models.Deposit), nil
//}
}
func (r *dPoolResolver) Funders(ctx context.Context, obj *models.DPool) ([]*models.Funder, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).FunderById.LoadAll(obj.FunderIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.Funder, 0), nil
}
return results.([]*models.Funder), nil
//}
}
func (r *dPoolResolver) Fundings(ctx context.Context, obj *models.DPool) ([]*models.Funding, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).FundingById.LoadAll(obj.FundingIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.Funding, 0), nil
}
return results.([]*models.Funding), nil
//}
}
func (r *dPoolListResolver) Pools(ctx context.Context, obj *models.DPoolList) ([]*models.DPool, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).DPoolById.LoadAll(obj.DPoolIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.DPool, 0), nil
}
return results.([]*models.DPool), nil
//}
}
func (r *depositResolver) User(ctx context.Context, obj *models.Deposit) (*models.User, error) {
result, err := dataloader.For(ctx).UserById.LoadThunk(obj.UserID)()
if err != nil {
return nil, err
}
return result, nil
}
func (r *depositResolver) Pool(ctx context.Context, obj *models.Deposit) (*models.DPool, error) {
result, err := dataloader.For(ctx).DPoolById.LoadThunk(obj.DPoolID)()
if err != nil {
return nil, err
}
return result, nil
}
func (r *funderResolver) Pools(ctx context.Context, obj *models.Funder) ([]*models.DPool, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).DPoolById.LoadAll(obj.DPoolIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.DPool, 0), nil
}
return results.([]*models.DPool), nil
//}
}
func (r *funderResolver) Fundings(ctx context.Context, obj *models.Funder) ([]*models.Funding, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).FundingById.LoadAll(obj.FundingIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.Funding, 0), nil
}
return results.([]*models.Funding), nil
//}
}
func (r *funderResolver) TotalInterestByPool(ctx context.Context, obj *models.Funder) ([]*models.FunderTotalInterest, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).FunderTotalInterestById.LoadAll(obj.FunderTotalInterestIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.FunderTotalInterest, 0), nil
}
return results.([]*models.FunderTotalInterest), nil
//}
}
func (r *funderTotalInterestResolver) Funder(ctx context.Context, obj *models.FunderTotalInterest) (*models.Funder, error) {
result, err := dataloader.For(ctx).FunderById.LoadThunk(obj.FunderID)()
if err != nil {
return nil, err
}
return result, nil
}
func (r *funderTotalInterestResolver) Pool(ctx context.Context, obj *models.FunderTotalInterest) (*models.DPool, error) {
result, err := dataloader.For(ctx).DPoolById.LoadThunk(obj.DPoolID)()
if err != nil {
return nil, err
}
return result, nil
}
func (r *fundingResolver) Funder(ctx context.Context, obj *models.Funding) (*models.Funder, error) {
result, err := dataloader.For(ctx).FunderById.LoadThunk(obj.FunderID)()
if err != nil {
return nil, err
}
return result, nil
}
func (r *fundingResolver) Pool(ctx context.Context, obj *models.Funding) (*models.DPool, error) {
result, err := dataloader.For(ctx).DPoolById.LoadThunk(obj.DPoolID)()
if err != nil {
return nil, err
}
return result, nil
}
func (r *mutationResolver) UpdateDPoolList(ctx context.Context, input models.DPoolListInput) (*bool, error) {
args := DefaultInputs
fmt.Println("input id")
fmt.Println(fmt.Sprintf(*input.ID))
jsonMarshal, marshalErr := json.Marshal(input)
if marshalErr != nil {
fmt.Println("Marhsal Error")
fmt.Println(marshalErr)
}
fmt.Println(string(jsonMarshal))
boolResult := true
table, tableErr := r.db.GetTable("DefaultDB-DPoolLists")
if tableErr != nil || table == nil {
boolResult = false
fmt.Println("Table Error")
fmt.Println(tableErr)
fmt.Println(table)
return &boolResult, tableErr
}
//marshal the input into JSON/clean the input
//json.Marshal(input)
_, err := table.Put(*input.ID, string(jsonMarshal), args["prove"].(bool), args)
if err != nil {
fmt.Println("Error with input")
fmt.Println(err)
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateDPool(ctx context.Context, input models.DPoolInput) (*bool, error) {
args := DefaultInputs
fmt.Println("Input from DPool")
fmt.Println(input)
table, _ := r.db.GetTable("DefaultDB-DPools")
fmt.Println(table)
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateUser(ctx context.Context, input models.UserInput) (*bool, error) {
args := DefaultInputs
table, _ := r.db.GetTable("Users")
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateUserTotalDeposit(ctx context.Context, input models.UserTotalDepositInput) (*bool, error) {
args := DefaultInputs
table, _ := r.db.GetTable("UserTotalDeposits")
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateDeposit(ctx context.Context, input models.DepositInput) (*bool, error) {
args := DefaultInputs
table, _ := r.db.GetTable("Deposits")
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateFunder(ctx context.Context, input models.FunderInput) (*bool, error) {
args := DefaultInputs
table, _ := r.db.GetTable("Funders")
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateFunderTotalInterest(ctx context.Context, input models.FunderTotalInterestInput) (*bool, error) {
args := DefaultInputs
table, _ := r.db.GetTable("FunderTotalInterests")
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateFunding(ctx context.Context, input models.FundingInput) (*bool, error) {
args := DefaultInputs
table, _ := r.db.GetTable("Fundings")
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateMPHHolder(ctx context.Context, input models.MPHHolderInput) (*bool, error) {
args := DefaultInputs
table, _ := r.db.GetTable("MPHHolders")
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *mutationResolver) UpdateMph(ctx context.Context, input models.MPHInput) (*bool, error) {
args := DefaultInputs
table, _ := r.db.GetTable("MPHs")
_, err := table.Put(*input.ID, input, args["prove"].(bool), args)
boolResult := true
if err != nil {
boolResult = false
}
return &boolResult, err
}
func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
table, tableErr := r.db.GetTable("DefaultDB-DPoolLists")
if tableErr != nil || table == nil {
fmt.Println("Table Error")
fmt.Println(tableErr)
return nil, tableErr
}
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
fmt.Println("Result Error")
fmt.Println(err)
return nil, err
}
fmt.Println("Result get ")
fmt.Println(result)
data := result.GetValue()
var val models.DPoolList
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) DPoolLists(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.DPoolList, error) {
// func (r *queryResolver) DPoolLists(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.DPoolList, 0)
for _, dataRow := range result {
var val models.DPoolList
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) DPoolListSearch(ctx context.Context, queryText string, prove *bool) ([]*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.DPoolList, 0)
for _, dataRow := range result {
var val models.DPoolList
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) DPool(ctx context.Context, id string, prove *bool) (*models.DPool, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
fmt.Println(id)
table, e := r.db.GetTable("DPools")
fmt.Println(table)
if e != nil {
fmt.Println(e)
return nil, e
}
result, err := table.Get(id, false)
if err != nil {
fmt.Println(err)
return nil, err
}
data := result.GetValue()
var val models.DPool
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) DPools(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.DPool, error) {
// func (r *queryResolver) DPools(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.DPool, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.DPool, 0)
for _, dataRow := range result {
var val models.DPool
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) DPoolSearch(ctx context.Context, queryText string, prove *bool) ([]*models.DPool, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("DPools")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.DPool, 0)
for _, dataRow := range result {
var val models.DPool
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) User(ctx context.Context, id string, prove *bool) (*models.User, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
fmt.Println("ID")
fmt.Println(id)
args["id"] = id
table, _ := r.db.GetTable("Users")
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
return nil, err
}
data := result.GetValue()
var val models.User
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) Users(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.User, error) {
// func (r *queryResolver) Users(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.User, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.User, 0)
for _, dataRow := range result {
var val models.User
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) UserSearch(ctx context.Context, queryText string, prove *bool) ([]*models.User, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("Users")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.User, 0)
for _, dataRow := range result {
var val models.User
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) UserTotalDeposit(ctx context.Context, id string, prove *bool) (*models.UserTotalDeposit, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
table, _ := r.db.GetTable("UserTotalDeposits")
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
return nil, err
}
data := result.GetValue()
var val models.UserTotalDeposit
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) UserTotalDeposits(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.UserTotalDeposit, error) {
// func (r *queryResolver) UserTotalDeposits(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.UserTotalDeposit, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.UserTotalDeposit, 0)
for _, dataRow := range result {
var val models.UserTotalDeposit
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) UserTotalDepositSearch(ctx context.Context, queryText string, prove *bool) ([]*models.UserTotalDeposit, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("UserTotalDeposits")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.UserTotalDeposit, 0)
for _, dataRow := range result {
var val models.UserTotalDeposit
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) Deposit(ctx context.Context, id string, prove *bool) (*models.Deposit, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
table, _ := r.db.GetTable("Deposits")
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
return nil, err
}
data := result.GetValue()
var val models.Deposit
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) Deposits(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.Deposit, error) {
// func (r *queryResolver) Deposits(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.Deposit, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.Deposit, 0)
for _, dataRow := range result {
var val models.Deposit
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) DepositSearch(ctx context.Context, queryText string, prove *bool) ([]*models.Deposit, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("Deposits")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.Deposit, 0)
for _, dataRow := range result {
var val models.Deposit
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) Funder(ctx context.Context, id string, prove *bool) (*models.Funder, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
table, _ := r.db.GetTable("Funders")
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
return nil, err
}
data := result.GetValue()
var val models.Funder
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) Funders(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.Funder, error) {
// func (r *queryResolver) Funders(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.Funder, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.Funder, 0)
for _, dataRow := range result {
var val models.Funder
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) FunderSearch(ctx context.Context, queryText string, prove *bool) ([]*models.Funder, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("Funders")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.Funder, 0)
for _, dataRow := range result {
var val models.Funder
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) FunderTotalInterest(ctx context.Context, id string, prove *bool) (*models.FunderTotalInterest, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
table, _ := r.db.GetTable("FunderTotalInterests")
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
return nil, err
}
data := result.GetValue()
var val models.FunderTotalInterest
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) FunderTotalInterests(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.FunderTotalInterest, error) {
// func (r *queryResolver) FunderTotalInterests(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.FunderTotalInterest, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.FunderTotalInterest, 0)
for _, dataRow := range result {
var val models.FunderTotalInterest
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) FunderTotalInterestSearch(ctx context.Context, queryText string, prove *bool) ([]*models.FunderTotalInterest, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("FunderTotalInterests")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.FunderTotalInterest, 0)
for _, dataRow := range result {
var val models.FunderTotalInterest
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) Funding(ctx context.Context, id string, prove *bool) (*models.Funding, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
table, _ := r.db.GetTable("Fundings")
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
return nil, err
}
data := result.GetValue()
var val models.Funding
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) Fundings(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.Funding, error) {
// func (r *queryResolver) Fundings(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.Funding, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.Funding, 0)
for _, dataRow := range result {
var val models.Funding
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) FundingSearch(ctx context.Context, queryText string, prove *bool) ([]*models.Funding, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("Fundings")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.Funding, 0)
for _, dataRow := range result {
var val models.Funding
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) MPHHolder(ctx context.Context, id string, prove *bool) (*models.MPHHolder, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
table, _ := r.db.GetTable("MPHHolders")
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
return nil, err
}
data := result.GetValue()
var val models.MPHHolder
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) MPHHolders(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.MPHHolder, error) {
// func (r *queryResolver) MPHHolders(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.MPHHolder, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.MPHHolder, 0)
for _, dataRow := range result {
var val models.MPHHolder
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) MPHHolderSearch(ctx context.Context, queryText string, prove *bool) ([]*models.MPHHolder, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("MPHHolders")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.MPHHolder, 0)
for _, dataRow := range result {
var val models.MPHHolder
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *queryResolver) Mph(ctx context.Context, id string, prove *bool) (*models.Mph, error) {
//func (r *queryResolver) DPoolList(ctx context.Context, id string, prove *bool) (*models.DPoolList, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
args["id"] = id
table, _ := r.db.GetTable("Mphs")
result, err := table.Get(id, args["prove"].(bool))
if err != nil {
return nil, err
}
data := result.GetValue()
var val models.Mph
err = json.Unmarshal(data, &val)
if err != nil {
return nil, err
}
p := GenerateProof(result.GetProof())
val.Proof = &p
return &val, nil
//}
}
func (r *queryResolver) MPHs(ctx context.Context, where *string, orderBy *string, asc *bool, first *int, last *int, limit *int, prove *bool) ([]*models.Mph, error) {
// func (r *queryResolver) Mphs(ctx context.Context, where *string, orderBy *string, direction *bool, first *int, last *int, limit *int, prove *bool) ([]*models.Mph, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
if limit != nil {
args["limit"] = *limit
}
if first != nil {
args["first"] = *first
}
if last != nil {
args["last"] = *last
}
if asc != nil {
args["direction"] = *asc
}
if orderBy != nil {
args["order_by"] = *orderBy
}
if where != nil {
args["where"] = *where
}
table, _ := r.db.GetTable("DPoolLists")
result, err := table.Search(args["where"].(string), args["order_by"].(string), args["direction"].(bool), args["first"].(int), args["last"].(int), args["prove"].(bool), args)
if err != nil {
return nil, err
}
value := make([]*models.Mph, 0)
for _, dataRow := range result {
var val models.Mph
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
//}
}
func (r *queryResolver) MPHSearch(ctx context.Context, queryText string, prove *bool) ([]*models.Mph, error) {
args := DefaultInputs
if prove != nil {
args["prove"] = *prove
}
table, _ := r.db.GetTable("Mphs")
result, err := table.Query(queryText, args["prove"].(bool))
if err != nil {
return nil, err
}
value := make([]*models.Mph, 0)
for _, dataRow := range result {
var val models.Mph
err = json.Unmarshal(dataRow.GetValue(), &val)
if err != nil {
return nil, err
}
p := GenerateProof(dataRow.GetProof())
val.Proof = &p
value = append(value, &val)
}
return value, nil
}
func (r *userResolver) Pools(ctx context.Context, obj *models.User) ([]*models.DPool, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).DPoolById.LoadAll(obj.DPoolIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.DPool, 0), nil
}
return results.([]*models.DPool), nil
//}
}
func (r *userResolver) Deposits(ctx context.Context, obj *models.User) ([]*models.Deposit, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).DepositById.LoadAll(obj.DepositIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.Deposit, 0), nil
}
return results.([]*models.Deposit), nil
//}
}
func (r *userResolver) TotalDepositByPool(ctx context.Context, obj *models.User) ([]*models.UserTotalDeposit, error) {
// func (r *dPoolResolver) $EntityNames(ctx context.Context, obj *models.DPool) ([]*models.User, error) {
//determine which set of ids to get
entities, _ := dataloader.For(ctx).UserTotalDepositById.LoadAll(obj.UserTotalDepositIDs)
var args map[string]interface{} = graphql.GetFieldContext(ctx).Args
//check argument context
//context check the args, where, orderBy, orderDirection, first, last, prove
//getDefaults/getTheContextArgs
//from identifier,
//use to get from context
results, err := proximaIterables.Search(entities, args["where"], args["orderBy"], args["direction"].(bool), args["first"].(int), args["last"].(int), "")
if err != nil {
return make([]*models.UserTotalDeposit, 0), nil
}
return results.([]*models.UserTotalDeposit), nil
//}
}
func (r *userTotalDepositResolver) User(ctx context.Context, obj *models.UserTotalDeposit) (*models.User, error) {
result, err := dataloader.For(ctx).UserById.LoadThunk(obj.UserID)()
if err != nil {
return nil, err
}
return result, nil
}
func (r *userTotalDepositResolver) Pool(ctx context.Context, obj *models.UserTotalDeposit) (*models.DPool, error) {
result, err := dataloader.For(ctx).DPoolById.LoadThunk(obj.DPoolID)()
if err != nil {
return nil, err
}
return result, nil
}
// DPool returns gql.DPoolResolver implementation.
|
package kindergarten
import (
"errors"
"sort"
"strings"
)
// Garden structure
type Garden struct {
diagram string
children []string
sortedChildren []string
}
var (
plantsMap = map[byte]string{
'R': "radishes",
'C': "clover",
'G': "grass",
'V': "violets",
}
)
// NewGarden creates a new Garden object
func NewGarden(diagram string, children []string) (*Garden, error) {
lines := strings.FieldsFunc(diagram, func(r rune) bool {
return r == '\n'
})
numEOL := strings.FieldsFunc(diagram, func(r rune) bool {
return r != '\n'
})
if len(lines) != 2 || len(lines[0]) != 2*len(children) ||
len(numEOL) != 2 || len(lines[0]) != len(lines[1]) {
return nil, errors.New("invalid input1")
}
for i := 0; i < len(lines[0]); i++ {
if _, ok := plantsMap[lines[0][i]]; !ok {
return nil, errors.New("invalid input2")
}
if _, ok := plantsMap[lines[1][i]]; !ok {
return nil, errors.New("invalid input3")
}
}
sortedChildren := append([]string(nil), children...)
sort.Slice(sortedChildren, func(i, j int) bool {
return strings.Compare(sortedChildren[i], sortedChildren[j]) < 0
})
for i := 0; i < len(sortedChildren)-1; i++ {
if strings.Compare(sortedChildren[i], sortedChildren[i+1]) == 0 {
return nil, errors.New("invalid input4")
}
}
return &Garden{
diagram: diagram,
children: children,
sortedChildren: sortedChildren,
}, nil
}
// Plants returns all plants that are planted by a child
func (g *Garden) Plants(child string) ([]string, bool) {
lines := strings.FieldsFunc(g.diagram, func(r rune) bool {
return r == '\n'
})
res := []string{}
pos := -1
for i, v := range g.sortedChildren {
if strings.Compare(v, child) == 0 {
pos = i
break
}
}
if pos == -1 {
return res, false
}
res = append(res, plantsMap[lines[0][2*pos]])
res = append(res, plantsMap[lines[0][2*pos+1]])
res = append(res, plantsMap[lines[1][2*pos]])
res = append(res, plantsMap[lines[1][2*pos+1]])
return res, true
}
|
// Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of
// the License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 secretcache
import (
"sync"
"time"
"github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface"
)
const (
exceptionRetryDelayBase = 1
exceptionRetryGrowthFactor = 2
exceptionRetryDelayMax = 3600
)
// Base cache object for common properties.
type cacheObject struct {
mux sync.Mutex
config CacheConfig
client secretsmanageriface.SecretsManagerAPI
secretId string
err error
errorCount int
refreshNeeded bool
// The time to wait before retrying a failed AWS Secrets Manager request.
nextRetryTime int64
data interface{}
}
// isRefreshNeeded determines if the cached object should be refreshed.
func (o *cacheObject) isRefreshNeeded() bool {
if o.refreshNeeded {
return true
}
if o.err == nil {
return false
}
if o.nextRetryTime == 0 {
return true
}
return o.nextRetryTime <= time.Now().UnixNano()
}
|
package model
import (
"time"
)
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
DisplayName string `json:"display_name"`
Key string `json:"key"`
Email string `json:"email"`
CreateTime int64 `json:"create_ts"`
}
////////////////////////////////////////////////////////////////////////////////
func ListUser(cs []*Condition, o *Order, p *Paging) []*User {
if cs == nil {
cs = make([]*Condition, 0)
}
cs = append(cs, NewCondition("is_active", "=", true))
where, vs := GenerateWhereSql(cs)
order := GenerateOrderSql(o)
limit := GenerateLimitSql(p)
rows, err := db.Query(`
SELECT
id, name, display_name, agent_key, email, create_ts
FROM
user
` + where + order + limit, vs...,
)
if err != nil {
panic(err)
}
defer rows.Close()
l := make([]*User, 0)
for rows.Next() {
u := new(User)
if err := rows.Scan(
&u.Id, &u.Name, &u.DisplayName, &u.Key, &u.Email, &u.CreateTime,
); err != nil {
panic(err)
}
l = append(l, u)
}
return l
}
func GetUserById(id int64) *User {
conditions := make([]*Condition, 0)
conditions = append(conditions, NewCondition("id", "=", id))
l := ListUser(conditions, nil, nil)
if len(l) == 0 {
return nil
}
return l[0]
}
func GetUserByName(name string) *User {
conditions := make([]*Condition, 0)
conditions = append(conditions, NewCondition("name", "=", name))
l := ListUser(conditions, nil, nil)
if len(l) == 0 {
return nil
}
return l[0]
}
func GetUserByAgentkey(key string) *User {
conditions := make([]*Condition, 0)
conditions = append(conditions, NewCondition("agent_key", "=", key))
l := ListUser(conditions, nil, nil)
if len(l) == 0 {
return nil
}
return l[0]
}
func IsAdmin(id int64) bool {
rows, err := db.Query(`
SELECT
is_admin
FROM
user
WHERE
id = ?
`, id,
)
if err != nil {
panic(err)
}
defer rows.Close()
var b bool
for rows.Next() {
if err := rows.Scan(&b); err != nil {
panic(err)
}
}
return b
}
func (u *User) Save() {
stmt, err := db.Prepare(`
INSERT INTO user(
name, display_name, agent_key, email, create_ts, is_active
)
VALUES(?, ?, ?, ?, ?, true)
`)
if err != nil {
panic(err)
}
defer stmt.Close()
u.CreateTime = time.Now().UTC().Unix()
u.Key = generateKey()
result, err := stmt.Exec(
u.Name, u.DisplayName, u.Key, u.Email, u.CreateTime,
)
if err != nil {
panic(err)
}
u.Id, err = result.LastInsertId()
if err != nil {
panic(err)
}
}
func (u *User) Update() {
stmt, err := db.Prepare(`
UPDATE
user
SET
display_name = ?,
email = ?,
WHERE
id = ?
`)
if err != nil {
panic(err)
}
defer stmt.Close()
if _, err := stmt.Exec(
u.DisplayName,
u.Email,
u.Id,
); err != nil {
panic(err)
}
}
func (u *User) Delete() {
stmt, err := db.Prepare(`
UPDATE
user
SET
is_active = false,
WHERE
id = ?
`)
if err != nil {
panic(err)
}
defer stmt.Close()
if _, err := stmt.Exec(u.Id); err != nil {
panic(err)
}
}
////////////////////////////////////////////////////////////////////////////////
func (u *User) VerifyPassword(password string) bool {
rows, err := db.Query(`
SELECT
password
FROM
user
WHERE
name = ?
`, u.Name,
)
if err != nil {
panic(err)
}
defer rows.Close()
var hp string
for rows.Next() {
if err := rows.Scan(&hp); err != nil {
panic(err)
}
}
return hashPassword(password) == hp
}
func (u *User) ResetPassword(password string) {
stmt, err := db.Prepare(`
UPDATE
user
SET
password = ?
WHERE
id = ?
`)
if err != nil {
panic(err)
}
defer stmt.Close()
if _, err := stmt.Exec(
hashPassword(password),
u.Id,
); err != nil {
panic(err)
}
}
func (u *User) ResetKey() {
stmt, err := db.Prepare(`
UPDATE
user
SET
agent_key = ?
WHERE
id = ?
`)
if err != nil {
panic(err)
}
defer stmt.Close()
if _, err := stmt.Exec(
generateKey(),
u.Id,
); err != nil {
panic(err)
}
}
////////////////////////////////////////////////////////////////////////////////
func (u *User) Repos() []*Repo {
conditions := make([]*Condition, 0)
conditions = append(conditions, NewCondition("owner_id", "=", u.Id))
return ListRepo(conditions, nil, nil)
}
func (u *User) Nodes() []*Node {
conditions := make([]*Condition, 0)
conditions = append(conditions, NewCondition("owner_id", "=", u.Id))
return ListNode(conditions, nil, nil)
}
func (u *User) Groups() []*Group {
conditions := make([]*Condition, 0)
conditions = append(conditions, NewCondition("owner_id", "=", u.Id))
return ListGroup(conditions, nil, nil)
}
func (u *User) HasRepo(repo *Repo) bool {
return repo.OwnerId == u.Id
}
func (u *User) CanDeploy(repo *Repo) bool {
return repo.OwnerId == u.Id || repo.IsPublic
}
|
package database
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"net"
"time"
"github.com/golang/glog"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/metrics"
"github.com/prebid/prebid-server/stored_requests/backends/db_provider"
"github.com/prebid/prebid-server/stored_requests/events"
"github.com/prebid/prebid-server/util/timeutil"
)
func bytesNull() []byte {
return []byte{'n', 'u', 'l', 'l'}
}
var storedDataTypeMetricMap = map[config.DataType]metrics.StoredDataType{
config.RequestDataType: metrics.RequestDataType,
config.CategoryDataType: metrics.CategoryDataType,
config.VideoDataType: metrics.VideoDataType,
config.AMPRequestDataType: metrics.AMPDataType,
config.AccountDataType: metrics.AccountDataType,
config.ResponseDataType: metrics.ResponseDataType,
}
type DatabaseEventProducerConfig struct {
Provider db_provider.DbProvider
RequestType config.DataType
CacheInitQuery string
CacheInitTimeout time.Duration
CacheUpdateQuery string
CacheUpdateTimeout time.Duration
MetricsEngine metrics.MetricsEngine
}
type DatabaseEventProducer struct {
cfg DatabaseEventProducerConfig
lastUpdate time.Time
invalidations chan events.Invalidation
saves chan events.Save
time timeutil.Time
}
func NewDatabaseEventProducer(cfg DatabaseEventProducerConfig) (eventProducer *DatabaseEventProducer) {
if cfg.Provider == nil {
glog.Fatalf("The Database Stored %s Loader needs a database connection to work.", cfg.RequestType)
}
return &DatabaseEventProducer{
cfg: cfg,
lastUpdate: time.Time{},
saves: make(chan events.Save, 1),
invalidations: make(chan events.Invalidation, 1),
time: &timeutil.RealTime{},
}
}
func (e *DatabaseEventProducer) Run() error {
if e.lastUpdate.IsZero() {
return e.fetchAll()
}
return e.fetchDelta()
}
func (e *DatabaseEventProducer) Saves() <-chan events.Save {
return e.saves
}
func (e *DatabaseEventProducer) Invalidations() <-chan events.Invalidation {
return e.invalidations
}
func (e *DatabaseEventProducer) fetchAll() (fetchErr error) {
timeout := e.cfg.CacheInitTimeout * time.Millisecond
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
startTime := e.time.Now().UTC()
rows, err := e.cfg.Provider.QueryContext(ctx, e.cfg.CacheInitQuery)
elapsedTime := time.Since(startTime)
e.recordFetchTime(elapsedTime, metrics.FetchAll)
if err != nil {
glog.Warningf("Failed to fetch all Stored %s data from the DB: %v", e.cfg.RequestType, err)
if _, ok := err.(net.Error); ok {
e.recordError(metrics.StoredDataErrorNetwork)
} else {
e.recordError(metrics.StoredDataErrorUndefined)
}
return err
}
defer func() {
if err := rows.Close(); err != nil {
glog.Warningf("Failed to close the Stored %s DB connection: %v", e.cfg.RequestType, err)
e.recordError(metrics.StoredDataErrorUndefined)
fetchErr = err
}
}()
if err := e.sendEvents(rows); err != nil {
glog.Warningf("Failed to load all Stored %s data from the DB: %v", e.cfg.RequestType, err)
e.recordError(metrics.StoredDataErrorUndefined)
return err
}
e.lastUpdate = startTime
return nil
}
func (e *DatabaseEventProducer) fetchDelta() (fetchErr error) {
timeout := e.cfg.CacheUpdateTimeout * time.Millisecond
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
startTime := e.time.Now().UTC()
params := []db_provider.QueryParam{
{Name: "LAST_UPDATED", Value: e.lastUpdate},
}
rows, err := e.cfg.Provider.QueryContext(ctx, e.cfg.CacheUpdateQuery, params...)
elapsedTime := time.Since(startTime)
e.recordFetchTime(elapsedTime, metrics.FetchDelta)
if err != nil {
glog.Warningf("Failed to fetch updated Stored %s data from the DB: %v", e.cfg.RequestType, err)
if _, ok := err.(net.Error); ok {
e.recordError(metrics.StoredDataErrorNetwork)
} else {
e.recordError(metrics.StoredDataErrorUndefined)
}
return err
}
defer func() {
if err := rows.Close(); err != nil {
glog.Warningf("Failed to close the Stored %s DB connection: %v", e.cfg.RequestType, err)
e.recordError(metrics.StoredDataErrorUndefined)
fetchErr = err
}
}()
if err := e.sendEvents(rows); err != nil {
glog.Warningf("Failed to load updated Stored %s data from the DB: %v", e.cfg.RequestType, err)
e.recordError(metrics.StoredDataErrorUndefined)
return err
}
e.lastUpdate = startTime
return nil
}
func (e *DatabaseEventProducer) recordFetchTime(elapsedTime time.Duration, fetchType metrics.StoredDataFetchType) {
e.cfg.MetricsEngine.RecordStoredDataFetchTime(
metrics.StoredDataLabels{
DataType: storedDataTypeMetricMap[e.cfg.RequestType],
DataFetchType: fetchType,
}, elapsedTime)
}
func (e *DatabaseEventProducer) recordError(errorType metrics.StoredDataError) {
e.cfg.MetricsEngine.RecordStoredDataError(
metrics.StoredDataLabels{
DataType: storedDataTypeMetricMap[e.cfg.RequestType],
Error: errorType,
})
}
// sendEvents reads the rows and sends notifications into the channel for any updates.
// If it returns an error, then callers can be certain that no events were sent to the channels.
func (e *DatabaseEventProducer) sendEvents(rows *sql.Rows) (err error) {
storedRequestData := make(map[string]json.RawMessage)
storedImpData := make(map[string]json.RawMessage)
storedRespData := make(map[string]json.RawMessage)
var requestInvalidations []string
var impInvalidations []string
var respInvalidations []string
for rows.Next() {
var id string
var data []byte
var dataType string
// discard corrupted data so it is not saved in the cache
if err := rows.Scan(&id, &data, &dataType); err != nil {
return err
}
switch dataType {
case "request":
if len(data) == 0 || bytes.Equal(data, bytesNull()) {
requestInvalidations = append(requestInvalidations, id)
} else {
storedRequestData[id] = data
}
case "imp":
if len(data) == 0 || bytes.Equal(data, bytesNull()) {
impInvalidations = append(impInvalidations, id)
} else {
storedImpData[id] = data
}
case "response":
if len(data) == 0 || bytes.Equal(data, bytesNull()) {
respInvalidations = append(respInvalidations, id)
} else {
storedRespData[id] = data
}
default:
glog.Warningf("Stored Data with id=%s has invalid type: %s. This will be ignored.", id, dataType)
}
}
// discard corrupted data so it is not saved in the cache
if rows.Err() != nil {
return rows.Err()
}
if len(storedRequestData) > 0 || len(storedImpData) > 0 || len(storedRespData) > 0 {
e.saves <- events.Save{
Requests: storedRequestData,
Imps: storedImpData,
Responses: storedRespData,
}
}
if (len(requestInvalidations) > 0 || len(impInvalidations) > 0 || len(respInvalidations) > 0) && !e.lastUpdate.IsZero() {
e.invalidations <- events.Invalidation{
Requests: requestInvalidations,
Imps: impInvalidations,
Responses: respInvalidations,
}
}
return
}
|
package main
import "fmt"
func main() {
board := [][]byte{{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}
word := "ABCCED"
fmt.Println(exist(board, word))
}
func exist(board [][]byte, word string) bool {
visited := make([][]bool, len(board))
for i := 0; i < len(board); i++ {
visited[i] = make([]bool, len(board[0]))
}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[0]); j++ {
if hasPathCore(board, i, j, word, 0, visited) {
return true
}
}
}
return false
}
func hasPathCore(board [][]byte, i int, j int, word string, length int, visited [][]bool) bool {
if length == len(word) {
return true
}
hasPath := false
if i >= 0 && i < len(board) && j >= 0 && j < len(board[0]) && board[i][j] == word[length] && !visited[i][j] {
length++
visited[i][j] = true
hasPath = hasPathCore(board, i, j-1, word, length, visited) ||
hasPathCore(board, i-1, j, word, length, visited) ||
hasPathCore(board, i, j+1, word, length, visited) ||
hasPathCore(board, i+1, j, word, length, visited)
if !hasPath {
length--
visited[i][j] = false
}
}
return hasPath
}
|
package browsermain
import (
"math"
"capnproto.org/go/capnp/v3"
"zenhack.net/go/tempest/capnp/external"
"zenhack.net/go/tempest/internal/common/types"
"zenhack.net/go/util/exn"
)
var _ pusherHooks[types.ID[external.Package], external.Package] = pkgPusher{}
type pkgPusher struct {
}
func (pp pkgPusher) Upsert(id types.ID[external.Package], pkg external.Package) (Msg, error) {
return exn.Try(func(throw exn.Thrower) Msg {
// Copy over to a new message to avoid early release:
dstPkg, err := cloneStruct(pkg)
throw(err)
return UpsertPackage{
ID: id,
Pkg: dstPkg,
}
})
}
func (pp pkgPusher) Remove(id types.ID[external.Package]) Msg {
return RemovePackage{ID: id}
}
func (pp pkgPusher) Clear() Msg {
return ClearPackages{}
}
// cloneStruct clones the struct src into a new message, and sets the messages read
// limit to math.MaxUint64.
//
// TODO: maybe put this in go-capnp somewhere?
func cloneStruct[T ~capnp.StructKind](src T) (T, error) {
return exn.Try(func(throw exn.Thrower) T {
_, seg := capnp.NewSingleSegmentMessage(nil)
dst, err := capnp.NewRootStruct(seg, capnp.Struct(src).Size())
throw(err)
throw(capnp.Struct(dst).CopyFrom(capnp.Struct(src)))
dst.Message().ResetReadLimit(math.MaxUint64)
return T(dst)
})
}
|
package main
func f() float64 {
}
func main() {
var a int = f()
}
|
package main
import (
"fmt"
"sync"
)
func main() {
// Структура WaitGroup имеет поле noCopy, которое дает понять, что данную структуру не стоит копировать.
// А при передачи аргументов в функцию они как раз и копируются, что недопустимо.
//Структура WaitGroup должна создаваться по указателю
wg := sync.WaitGroup{} // т.е. wg := &sync.WaitGroup{}
for i := 0; i < 5; i++ {
wg.Add(1)
go func(wg sync.WaitGroup, i int) { // и go func(wg *sync.WaitGroup, i int) {
fmt.Println(i)
wg.Done()
}(wg, i)
}
wg.Wait()
fmt.Println("exit")
}
|
package webserver
import (
"net/http"
"os"
"runtime"
"strings"
"time"
"github.com/getsentry/sentry-go"
sentryecho "github.com/getsentry/sentry-go/echo"
promecho "github.com/labstack/echo-contrib/prometheus"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"gopkg.in/segmentio/analytics-go.v3"
"github.com/joostvdg/cmg/cmd/context"
"github.com/joostvdg/cmg/pkg/webserver"
)
const (
envPort = "PORT"
envLogFormatter = "LOG_FORMAT"
envSentry = "SENTRY_DSN"
envLogLevel = "LOG_LEVEL"
envRootPath = "ROOT_PATH"
envAnalyticsEndpoint = "ANALYTICS_API_ENDPOINT"
defaultRootPath = "/"
defaultPort = "8080"
debugLogLevel = "DEBUG"
defaultLogLevel = "INFO"
defaultLogFormatter = "PLAIN"
jsonLogFormatter = "JSON"
prometheusMetricsPath = "metrics"
prometheusEchoSystem = "echo"
prometheusCmgSystem = "cmg"
envSegmentKey = "SEGMENT_KEY"
)
// StartWebserver starts the Echo webserver
// Retrieves environment variable PORT for the server port to listen on
// Retrieves environment variable SENTRY_DSN for exporting Sentry.io events
func StartWebserver() {
port, portOk := os.LookupEnv(envPort)
if !portOk {
port = defaultPort
}
rootPath, rootPathOk := os.LookupEnv(envRootPath)
if !rootPathOk || rootPath == "" {
rootPath = defaultRootPath
}
// ensure we end with a "/" so all derived paths will work
if !strings.HasSuffix(rootPath, "/") {
rootPath += "/"
}
logFormat, logFormatOk := os.LookupEnv(envLogFormatter)
if logFormatOk && logFormat == jsonLogFormatter {
log.SetFormatter(&log.JSONFormatter{})
} else {
logFormat = defaultLogFormatter
}
logLevel, logLevelFormatOk := os.LookupEnv(envLogLevel)
if logLevelFormatOk && logLevel == debugLogLevel {
log.SetLevel(log.DebugLevel)
} else {
logLevel = defaultLogLevel
}
segmentKey, segmentOk := os.LookupEnv(envSegmentKey)
sentryDsn, sentryOk := os.LookupEnv(envSentry)
if sentryOk {
err := sentry.Init(sentry.ClientOptions{
Dsn: sentryDsn,
})
if err != nil {
log.Warnf("Sentry initialization failed: %v\n", err)
sentryOk = false
}
}
cmgAnalyticsEndpoint, cmgAnalyticsEndpointOk := os.LookupEnv(envAnalyticsEndpoint)
if !cmgAnalyticsEndpointOk {
cmgAnalyticsEndpoint = ""
}
// Echo instance
e := echo.New()
log.WithFields(log.Fields{
"RootPath": rootPath,
"Port": port,
"LogFormatter": logFormat,
"LogLevel": logLevel,
"OS": runtime.GOOS,
"ARCH": runtime.GOARCH,
// setting GOMAXPROCS is delegated to
// automaxprocs: runtime.GOMAXPROCS(0)
// done via init in main
"CPUs": runtime.GOMAXPROCS(0),
"Sentry Enabled": sentryOk,
"Segment Enabled": segmentOk,
"Analytics Endpoint": cmgAnalyticsEndpoint,
}).Info("Webserver started")
var segmentClient analytics.Client
if segmentOk {
segmentClient, _ = analytics.NewWithConfig(segmentKey, analytics.Config{
Interval: 5 * time.Second,
BatchSize: 10,
Verbose: true,
})
defer segmentClient.Close()
}
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORS())
e.Use(sentryecho.New(sentryecho.Options{}))
// Enable metrics middleware
p := promecho.NewPrometheus(prometheusEchoSystem, nil)
p.MetricsPath = rootPath + prometheusMetricsPath
p.Use(e)
// Define and Register custom Prometheus Metrics
var mapGenCollector prometheus.Collector = prometheus.NewHistogram(
prometheus.HistogramOpts{
Subsystem: prometheusCmgSystem,
Name: "map_generations",
Help: "Number of map generation attempts it took to generate a valid map (1)",
Buckets: []float64{
1,
10,
25,
50,
100,
250,
500,
1000,
2000,
},
},
)
var mapGenDurationCollector prometheus.Collector = prometheus.NewHistogram(
prometheus.HistogramOpts{
Subsystem: prometheusCmgSystem,
Name: "map_generation_duration",
Help: "Duration of map generation attempts it took to generate a valid map",
},
)
if err := prometheus.Register(mapGenCollector); err != nil {
log.Warnf("Could not register Prometheus Collector for Map Generations: %v", err)
}
if err := prometheus.Register(mapGenDurationCollector); err != nil {
log.Warnf("Could not register Prometheus Collector for Map Generation Duration: %v", err)
}
// Segment for Custom Context
e.Use(func(e echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cmgContext := &context.CMGContext{
Context: c,
MapGenAttempts: mapGenCollector,
MapGenDuration: mapGenDurationCollector,
SegmentClient: segmentClient,
}
return e(cmgContext)
}
})
// Routes
g := e.Group(rootPath)
g.GET("", handleRoutes)
g.GET("routes", handleRoutes)
g.GET("api/map", webserver.GetMap)
g.GET("api/v1/map", webserver.GetMapViaCodeGeneration)
g.GET("api/map/code", webserver.GetMapCode)
g.GET("api/map/code/:code", webserver.GetMapByCode)
g.GET("api/legend", webserver.GetMapLegend)
// Start server
e.Logger.Fatal(e.Start(":" + port))
}
// handleRoutes shows the routes that are handled
func handleRoutes(c echo.Context) error {
content := c.Echo().Routes()
callback := c.QueryParam("callback")
jsonp := c.QueryParam("jsonp")
if jsonp == "true" {
return c.JSONP(http.StatusOK, callback, &content)
}
return c.JSON(http.StatusOK, &content)
}
|
package kruskal
import "github.com/arberiii/Graph-Algorithms/graph"
type edge struct {
u int
v int
weight float64
}
// we suppose that the weight are sorted
func Kruskal(g graph.Graph, w []*edge) graph.Graph {
tree := graph.NewGraph()
components := make(map[int]int)
for v := range g {
tree[v] = []int{}
components[v] = v
}
for i := range w {
if !hasCycle(w[i], components) {
tree[w[i].u] = append(tree[w[i].v])
for key, val := range components {
if val == w[i].v {
components[key] = w[i].u
}
}
tree[w[i].v] = append(tree[w[i].u])
}
}
return tree
}
func hasCycle(e *edge, c map[int]int) bool {
return c[e.u] == c[e.v]
}
|
package requests
import (
"encoding/json"
"fmt"
"net/url"
"strings"
"github.com/google/go-querystring/query"
"github.com/atomicjolt/canvasapi"
)
// FlaggingQuestion Set a flag on a quiz question to indicate that you want to return to it
// later.
// https://canvas.instructure.com/doc/api/quiz_submission_questions.html
//
// Path Parameters:
// # Path.QuizSubmissionID (Required) ID
// # Path.ID (Required) ID
//
// Form Parameters:
// # Form.Attempt (Required) The attempt number of the quiz submission being taken. Note that this
// must be the latest attempt index, as questions for earlier attempts can
// not be modified.
// # Form.ValidationToken (Required) The unique validation token you received when the Quiz Submission was
// created.
// # Form.AccessCode (Optional) Access code for the Quiz, if any.
//
type FlaggingQuestion struct {
Path struct {
QuizSubmissionID string `json:"quiz_submission_id" url:"quiz_submission_id,omitempty"` // (Required)
ID string `json:"id" url:"id,omitempty"` // (Required)
} `json:"path"`
Form struct {
Attempt int64 `json:"attempt" url:"attempt,omitempty"` // (Required)
ValidationToken string `json:"validation_token" url:"validation_token,omitempty"` // (Required)
AccessCode string `json:"access_code" url:"access_code,omitempty"` // (Optional)
} `json:"form"`
}
func (t *FlaggingQuestion) GetMethod() string {
return "PUT"
}
func (t *FlaggingQuestion) GetURLPath() string {
path := "quiz_submissions/{quiz_submission_id}/questions/{id}/flag"
path = strings.ReplaceAll(path, "{quiz_submission_id}", fmt.Sprintf("%v", t.Path.QuizSubmissionID))
path = strings.ReplaceAll(path, "{id}", fmt.Sprintf("%v", t.Path.ID))
return path
}
func (t *FlaggingQuestion) GetQuery() (string, error) {
return "", nil
}
func (t *FlaggingQuestion) GetBody() (url.Values, error) {
return query.Values(t.Form)
}
func (t *FlaggingQuestion) GetJSON() ([]byte, error) {
j, err := json.Marshal(t.Form)
if err != nil {
return nil, nil
}
return j, nil
}
func (t *FlaggingQuestion) HasErrors() error {
errs := []string{}
if t.Path.QuizSubmissionID == "" {
errs = append(errs, "'Path.QuizSubmissionID' is required")
}
if t.Path.ID == "" {
errs = append(errs, "'Path.ID' is required")
}
if t.Form.ValidationToken == "" {
errs = append(errs, "'Form.ValidationToken' is required")
}
if len(errs) > 0 {
return fmt.Errorf(strings.Join(errs, ", "))
}
return nil
}
func (t *FlaggingQuestion) Do(c *canvasapi.Canvas) error {
_, err := c.SendRequest(t)
if err != nil {
return err
}
return nil
}
|
package api
import (
"github.com/jamierocks/gore/models"
)
type ProjectView struct {
ID int64 `json:"id"`
Name string `json:"name"`
SafeName string `json:"safeName"`
Versions []ProjectVersionView `json:"versions"`
}
type ProjectVersionView struct {
Version string `json:"version"`
Channel string `json:"channel"`
}
func GetProjectView(project models.Project) ProjectView {
var versions []ProjectVersionView
for _, version := range project.GetVersions() {
versions = append(versions, getProjectVersionView(version))
}
return ProjectView{
ID: project.ID,
Name: project.Name,
SafeName: project.SafeName,
Versions: versions,
}
}
func getProjectVersionView(version models.ProjectVersion) ProjectVersionView {
return ProjectVersionView{
Version: version.Version,
Channel: version.Channel,
}
}
|
package stack
type Watcher interface {
Watch(killCh <-chan struct{})
}
type Stack []Watcher
func (s Stack) Watch(killCh <-chan struct{}) {
for _, w := range s {
go w.Watch(killCh)
}
}
|
package zorm
import (
"database/sql"
"github.com/ZerQAQ/zorm/set"
"github.com/ZerQAQ/zorm/table"
)
func (d *Driver) Connect (name string, sour string) error {
var err error
d.Database, err = sql.Open(name, sour)
return err
}
func (d *Driver) init (){
d.tableSet = set.MakeSet()
rows, err := d.Database.Query("show tables")
if err != nil {
panic(err)
}
for rows.Next() {
var val interface{}
err := rows.Scan(&val)
if err != nil {panic(err)}
var stringVal = string(val.([]byte))
d.tableSet.Insert(stringVal)
}
d.syncTable = make(map[string]table.Table)
} |
package reports
import (
// mdl "diaria/models"
"fmt"
gr "github.com/mikeshimura/goreport"
"strconv"
)
func Simple1(records []interface{}) string {
r := gr.CreateGoReport()
r.SumWork["amountcum="] = 0.0
font1 := gr.FontMap{
FontName: "IPAexG",
FileName: "ttf//ipaexg.ttf",
}
fonts := []*gr.FontMap{&font1}
r.SetFonts(fonts)
d := new(S1Detail)
r.RegisterBand(gr.Band(*d), gr.Detail)
h := new(S1Header)
r.RegisterBand(gr.Band(*h), gr.PageHeader)
s := new(S1Summary)
r.RegisterBand(gr.Band(*s), gr.Summary)
r.Records = records
fmt.Printf("Records %v \n", r.Records)
r.SetPage("A4", "mm", "L")
r.SetFooterY(190)
r.Execute("report.pdf")
// r.SaveText("report.txt")
return "report.pdf"
}
type S1Detail struct {
}
func (h S1Detail) GetHeight(report gr.GoReport) float64 {
return 10
}
func (h S1Detail) Execute(report gr.GoReport) {
cols := report.Records[report.DataPos].([]string)
report.Font("IPAexG", 9, "")
y := 10.0
report.Cell(10, y, cols[0])
report.Cell(40, y, cols[1])
report.Cell(70, y, cols[2])
report.Cell(90, y, cols[3])
report.Cell(110, y, cols[4])
report.Cell(130, y, cols[5])
report.Cell(180, y, cols[6])
report.Cell(200, y, cols[7])
report.Cell(220, y, cols[8])
report.Cell(240, y, cols[9])
amt := ParseFloatNoError(cols[8])
report.SumWork["amountcum="] += amt
}
func ParseFloatNoError(s string) float64 {
f, _ := strconv.ParseFloat(s, 64)
return f
}
type S1Header struct {
}
func (h S1Header) GetHeight(report gr.GoReport) float64 {
return 30
}
func (h S1Header) Execute(report gr.GoReport) {
report.Font("IPAexG", 14, "")
report.Cell(50, 15, "Refeições dos Últimos 15 dias")
report.Font("IPAexG", 10, "")
report.Cell(240, 20, "Página")
report.Cell(260, 20, strconv.Itoa(report.Page))
y := 30.0
report.Cell(10, y, "Data")
report.Cell(40, y, "Refeição")
report.Cell(70, y, "Início")
report.Cell(90, y, "Término")
report.Cell(110, y, "Bolus")
report.Cell(130, y, "Alimento")
report.Cell(180, y, "Qtd Medida")
report.Cell(200, y, "Qtd")
report.Cell(220, y, "CHO")
report.Cell(240, y, "Kcal")
}
type S1Summary struct {
}
func (h S1Summary) GetHeight(report gr.GoReport) float64 {
return 10
}
func (h S1Summary) Execute(report gr.GoReport) {
report.Cell(160, 10, "Total")
report.CellRight(180, 10, 30, strconv.FormatFloat(
report.SumWork["amountcum="], 'f', 2, 64))
}
|
package auth
import (
"fmt"
log "git.ronaksoftware.com/blip/server/internal/logger"
"git.ronaksoftware.com/blip/server/internal/tools"
"git.ronaksoftware.com/blip/server/pkg/config"
"git.ronaksoftware.com/blip/server/pkg/msg"
"git.ronaksoftware.com/blip/server/pkg/session"
"git.ronaksoftware.com/blip/server/pkg/user"
"git.ronaksoftware.com/blip/server/pkg/vas/saba"
"github.com/kataras/iris/v12"
"github.com/mediocregopher/radix/v3"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
"go.uber.org/zap"
"net/http"
"strings"
"time"
)
/*
Creation Time: 2019 - Sep - 21
Created by: (ehsan)
Maintainers:
1. Ehsan N. Moosa (E2)
Auditor: Ehsan N. Moosa (E2)
Copyright Ronak Software Group 2018
*/
type authLog struct {
Phone string `bson:"phone"`
Action string `bson:"action"`
Date int64 `bson:"date"`
}
func MustHaveAccessKey(ctx iris.Context) {
accessKey := ctx.GetHeader(HdrAccessKey)
authCacheMtx.RLock()
auth, ok := authCache[accessKey]
authCacheMtx.RUnlock()
if !ok {
res := authCol.FindOne(nil, bson.M{"_id": accessKey}, options.FindOne())
if err := res.Decode(&auth); err != nil {
log.Debug("Error On GetAccessKey",
zap.Error(err),
zap.String("AccessKey", accessKey),
)
msg.WriteError(ctx, http.StatusForbidden, msg.ErrAccessTokenInvalid)
return
}
}
if auth.ExpiredOn > 0 && time.Now().Unix() > auth.ExpiredOn {
msg.WriteError(ctx, http.StatusForbidden, msg.ErrAccessTokenExpired)
return
}
authCacheMtx.Lock()
authCache[accessKey] = auth
authCacheMtx.Unlock()
ctx.Values().Save(CtxAuth, auth, true)
ctx.Values().Save(CtxClientName, auth.AppName, true)
ctx.Next()
}
func MustAdmin(ctx iris.Context) {
if !hasAdminAccess(ctx) {
msg.WriteError(ctx, http.StatusForbidden, msg.ErrNoPermission)
return
}
ctx.Next()
}
func hasAdminAccess(ctx iris.Context) bool {
auth, ok := ctx.Values().Get(CtxAuth).(Auth)
if !ok {
return false
}
for _, p := range auth.Permissions {
if p == Admin {
return true
}
}
return false
}
func MustWriteAccess(ctx iris.Context) {
if !hasWriteAccess(ctx) {
msg.WriteError(ctx, http.StatusForbidden, msg.ErrNoPermission)
return
}
ctx.Next()
}
func hasWriteAccess(ctx iris.Context) bool {
auth, ok := ctx.Values().Get(CtxAuth).(Auth)
if !ok {
return false
}
for _, p := range auth.Permissions {
if p == Write || p == Admin {
return true
}
}
return false
}
func MustReadAccess(ctx iris.Context) {
if !hasReadAccess(ctx) {
msg.WriteError(ctx, http.StatusForbidden, msg.ErrNoPermission)
return
}
ctx.Next()
}
func hasReadAccess(ctx iris.Context) bool {
auth, ok := ctx.Values().Get(CtxAuth).(Auth)
if !ok {
return false
}
for _, p := range auth.Permissions {
if p == Read || p == Admin {
return true
}
}
return false
}
func CreateAccessKeyHandler(ctx iris.Context) {
accessToken := tools.RandomID(64)
req := &CreateAccessToken{}
err := ctx.ReadJSON(req)
if err != nil {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrCannotUnmarshalRequest)
return
}
authPerms := make([]Permission, 0, 3)
for _, p := range req.Permissions {
switch strings.ToLower(p) {
case "admin":
authPerms = append(authPerms, Admin)
case "read":
authPerms = append(authPerms, Read)
case "write":
authPerms = append(authPerms, Write)
}
}
if len(authPerms) == 0 {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrPermissionIsNotSet)
return
}
authCreatedOn := time.Now().Unix()
authExpireOn := int64(0)
if req.Period > 0 {
authExpireOn = authCreatedOn + req.Period*86400
}
_, err = authCol.InsertOne(nil, Auth{
ID: accessToken,
Permissions: authPerms,
CreatedOn: authCreatedOn,
ExpiredOn: authExpireOn,
AppName: req.AppName,
})
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrWriteToDb)
return
}
msg.WriteResponse(ctx, CAccessTokenCreated, AccessTokenCreated{
AccessToken: accessToken,
ExpireOn: authExpireOn,
})
}
// LoginHandler is API handler
// API: /auth/send_code
// Http Method: POST
// Inputs: JSON
// phone: string
// Returns: PhoneCodeSent (PHONE_CODE_SENT)
// Possible Errors:
// 1. 500: READ_FROM_CACHE
// 2. 400: CANNOT_UNMARSHAL_JSON
// 2. 400: PHONE_NOT_VALID
func SendCodeHandler(ctx iris.Context) {
req := &SendCodeReq{}
err := ctx.ReadJSON(req)
if err != nil {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrCannotUnmarshalRequest)
return
}
if config.GetBool(config.TestMode) && strings.HasPrefix(req.Phone, config.GetString(config.MagicPhone)) {
sendCodeMagicNumber(ctx, req.Phone)
return
}
if len(req.Phone) < 5 {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrPhoneNotValid)
return
}
v, err := redisCache.GetString(fmt.Sprintf("%s.%s", config.RkPhoneCode, req.Phone))
if err != nil {
log.Warn("Error On ReadFromCache", zap.Error(err))
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrReadFromCache)
return
}
if v != "" {
u, _ := user.GetByPhone(req.Phone)
verifyParams := strings.Split(v, "|")
msg.WriteResponse(ctx, CPhoneCodeSent, PhoneCodeSent{
PhoneCodeHash: verifyParams[0],
Registered: u != nil,
})
return
}
switch ctx.Values().GetString(CtxClientName) {
case AppNameMusicChi:
sendMusicChi(ctx, req.Phone)
default:
sendCode(ctx, req.Phone)
}
}
func sendCode(ctx iris.Context, phone string) {
phoneCodeHash := tools.RandomID(12)
phoneCode := tools.RandomDigit(4)
if config.GetBool(config.TestMode) {
phoneCode = "2374"
}
u, _ := user.GetByPhone(phone)
err := redisCache.Do(radix.FlatCmd(nil, "SETEX",
fmt.Sprintf("%s.%s", config.RkPhoneCode, phone),
600,
fmt.Sprintf("%s|%s|%s", phoneCodeHash, "", phoneCode),
))
if err != nil {
log.Warn("Error On WriteToCache", zap.Error(err))
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrWriteToCache)
return
}
msg.WriteResponse(ctx, CPhoneCodeSent, PhoneCodeSent{
PhoneCodeHash: phoneCodeHash,
Registered: u != nil,
})
}
func sendMusicChi(ctx iris.Context, phone string) {
var phoneCodeHash, otpID, phoneCode string
phoneCodeHash = tools.RandomID(12)
u, _ := user.GetByPhone(phone)
if u != nil && u.VasPaid {
phoneCode = tools.RandomDigit(4)
// User our internal sms provider
if ce := log.Check(log.DebugLevel, "Send Code (MusicChi)"); ce != nil {
ce.Write(
zap.String("Phone", phone),
zap.String("PhoneCode", phoneCode),
)
}
_, err := smsProvider.SendInBackground(phone, fmt.Sprintf("MusicChi Code: %s", phoneCode))
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrNoResponseFromSmsServer)
return
}
} else {
if _, ok := supportedCarriers[phone[:5]]; !ok {
writeLogToDB.Enter(nil, authLog{
Phone: phone,
Action: "sendCodeUnsupported",
Date: time.Now().Unix(),
})
msg.WriteError(ctx, http.StatusNotAcceptable, msg.ErrUnsupportedCarrier)
return
}
res, err := saba.Subscribe(phone)
if err != nil {
writeLogToDB.Enter(nil, authLog{
Phone: phone,
Action: "sendCodeSabaFailed",
Date: time.Now().Unix(),
})
log.Warn("Error On Saba Subscribe", zap.Error(err))
msg.WriteError(ctx, http.StatusInternalServerError, msg.Err3rdParty)
return
}
otpID = res.OtpID
switch res.StatusCode {
case "SC111", "SC000":
default:
writeLogToDB.Enter(nil, authLog{
Phone: phone,
Action: "sendCodeSabaInvalidStatus",
Date: time.Now().Unix(),
})
// If we are here, then it means VAS did not send the sms
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrNoResponseFromVAS)
return
}
}
err := redisCache.Do(radix.FlatCmd(nil, "SETEX",
fmt.Sprintf("%s.%s", config.RkPhoneCode, phone),
600,
fmt.Sprintf("%s|%s|%s", phoneCodeHash, otpID, phoneCode),
))
if err != nil {
log.Warn("Error On WriteToCache", zap.Error(err))
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrWriteToCache)
return
}
writeLogToDB.Enter(nil, authLog{
Phone: phone,
Action: "sendCodeOk",
Date: time.Now().Unix(),
})
msg.WriteResponse(ctx, CPhoneCodeSent, PhoneCodeSent{
PhoneCodeHash: phoneCodeHash,
Registered: u != nil,
})
}
func sendCodeMagicNumber(ctx iris.Context, magicPhone string) {
phoneCode := config.GetString(config.MagicPhoneCode)
phoneCodeHash := tools.RandomID(12)
err := redisCache.Do(radix.FlatCmd(nil, "SETEX",
fmt.Sprintf("%s.%s", config.RkPhoneCode, magicPhone),
600,
fmt.Sprintf("%s|%s|%s", phoneCodeHash, "", phoneCode),
))
if err != nil {
log.Warn("Error On WriteToCache", zap.Error(err))
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrWriteToCache)
return
}
u, _ := user.GetByPhone(magicPhone)
msg.WriteResponse(ctx, CPhoneCodeSent, PhoneCodeSent{
PhoneCodeHash: phoneCodeHash,
Registered: u != nil,
})
}
// LoginHandler is API handler
// API: /auth/login
// Http Method: POST
// Inputs: JSON
// phone_code: string
// phone_code_hash: string
// phone: string
// Returns: Authorization (AUTHORIZATION)
// Possible Errors:
// 1. 500: with error text
// 2. 400: PHONE_NOT_VALID
// 3. 400: PHONE_CODE_NOT_VALID
// 4. 400: PHONE_CODE_HASH_NOT_VALID
func LoginHandler(ctx iris.Context) {
req := &LoginReq{}
err := ctx.ReadJSON(req)
if err != nil {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrCannotUnmarshalRequest)
return
}
u, err := user.GetByPhone(req.Phone)
if err != nil || u == nil {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrPhoneNotValid)
return
}
var otpID, phoneCode, phoneCodeHash string
if v, err := redisCache.GetString(fmt.Sprintf("%s.%s", config.RkPhoneCode, req.Phone)); err != nil {
log.Warn("Error On ReadFromCache", zap.Error(err))
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrReadFromCache)
return
} else {
verifyParams := strings.Split(v, "|")
if len(verifyParams) != 3 {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrCorruptData)
return
}
phoneCodeHash = verifyParams[0]
otpID = verifyParams[1]
phoneCode = verifyParams[2]
}
if req.PhoneCodeHash != phoneCodeHash {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrPhoneCodeHashNotValid)
return
}
if otpID != "" {
vasCode, err := saba.Confirm(req.Phone, req.PhoneCode, otpID)
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.Item(err.Error()))
return
}
switch vasCode {
case saba.SuccessfulCode:
case saba.SubscriptionAlreadyExists:
u.VasPaid = true
_ = user.Save(u)
default:
msg.WriteError(ctx, http.StatusInternalServerError, msg.Item(saba.Codes[vasCode]))
return
}
} else if req.PhoneCode != phoneCode {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrPhoneCodeNotValid)
return
}
appName := ctx.Values().GetString(CtxClientName)
err = session.Remove(u.ID, appName)
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrReadFromDb)
return
}
sessionID := tools.RandomID(64)
timeNow := time.Now().Unix()
err = session.Save(&session.Session{
ID: sessionID,
UserID: u.ID,
CreatedOn: timeNow,
LastAccess: timeNow,
App: appName,
})
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.Item(err.Error()))
return
}
if u.AppKey != ctx.GetHeader(HdrAccessKey) {
u.AppKey = ctx.GetHeader(HdrAccessKey)
_ = user.Save(u)
}
_ = redisCache.Del(fmt.Sprintf("%s.%s", config.RkPhoneCode, req.Phone))
writeLogToDB.Enter(nil, authLog{
Phone: u.Phone,
Action: "login",
Date: time.Now().Unix(),
})
msg.WriteResponse(ctx, CAuthorization, Authorization{
UserID: u.ID,
Phone: u.Phone,
Username: u.Username,
SessionID: sessionID,
})
}
// RegisterHandler is API handler
// API: /auth/register
// Http Method: POST
// Inputs: JSON
// phone_code: string
// phone_code_hash: string
// phone: string
// username: string
// Returns: Authorization (AUTHORIZATION)
// Possible Errors:
// 1. 500: with error text
// 2. 400: PHONE_NOT_VALID
// 3. 400: PHONE_CODE_NOT_VALID
// 4. 400: PHONE_CODE_HASH_NOT_VALID
func RegisterHandler(ctx iris.Context) {
req := &RegisterReq{}
err := ctx.ReadJSON(req)
if err != nil {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrCannotUnmarshalRequest)
return
}
var otpID, phoneCode, phoneCodeHash string
var vasPaid bool
if v, err := redisCache.GetString(fmt.Sprintf("%s.%s", config.RkPhoneCode, req.Phone)); err != nil {
log.Warn("Error On ReadFromCache", zap.Error(err))
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrReadFromCache)
return
} else {
verifyParams := strings.Split(v, "|")
if len(verifyParams) != 3 {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrCorruptData)
return
}
phoneCodeHash = verifyParams[0]
otpID = verifyParams[1]
phoneCode = verifyParams[2]
}
if req.PhoneCodeHash != phoneCodeHash {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrPhoneCodeHashNotValid)
return
}
if otpID != "" {
vasCode, err := saba.Confirm(req.Phone, req.PhoneCode, otpID)
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.Item(err.Error()))
return
}
switch vasCode {
case saba.SuccessfulCode:
vasPaid = true
case saba.SubscriptionAlreadyExists:
vasPaid = true
default:
msg.WriteError(ctx, http.StatusInternalServerError, msg.Item(saba.Codes[vasCode]))
return
}
} else if req.PhoneCode != phoneCode {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrPhoneCodeNotValid)
return
}
_, err = user.GetByPhone(req.Phone)
if err == nil {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrAlreadyRegistered)
return
}
if req.Username == "" {
req.Username = fmt.Sprintf("USER%s", strings.ToUpper(tools.RandomID(12)))
} else if !usernameREGX.Match(tools.StrToByte(req.Username)) {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrUsernameFormat)
return
}
userID := fmt.Sprintf("U%s", tools.RandomID(32))
timeNow := time.Now().Unix()
err = user.Save(&user.User{
ID: userID,
Username: req.Username,
Phone: req.Phone,
Email: "",
CreatedOn: timeNow,
Disabled: false,
VasPaid: vasPaid,
AppKey: ctx.GetHeader(HdrAccessKey),
})
if err != nil {
u, _ := user.GetByPhone(req.Phone)
if u == nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.Item(err.Error()))
return
}
}
sessionID := tools.RandomID(64)
err = session.Save(&session.Session{
ID: sessionID,
UserID: userID,
CreatedOn: timeNow,
LastAccess: timeNow,
App: ctx.Values().GetString(CtxClientName),
})
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.Item(err.Error()))
return
}
_ = redisCache.Del(fmt.Sprintf("%s.%s", config.RkPhoneCode, req.Phone))
writeLogToDB.Enter(nil, authLog{
Phone: req.Phone,
Action: "register",
Date: time.Now().Unix(),
})
msg.WriteResponse(ctx, CAuthorization, Authorization{
UserID: userID,
Phone: req.Phone,
Username: req.Username,
SessionID: sessionID,
})
}
// LogoutHandler is API handler
// API: /auth/logout
// Http Method: POST
// Inputs: JSON
// unsubscribe: bool
// Returns: Bool (BOOL)
// Possible Errors:
func LogoutHandler(ctx iris.Context) {
req := &LogoutReq{}
err := ctx.ReadJSON(req)
if err != nil {
msg.WriteError(ctx, http.StatusBadRequest, msg.ErrCannotUnmarshalRequest)
return
}
s, ok := ctx.Values().Get(session.CtxSession).(session.Session)
if !ok {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrSessionInvalid)
return
}
if req.Unsubscribe {
u, err := user.Get(s.UserID)
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrUserNotFound)
return
}
_, err = saba.Unsubscribe(u.Phone)
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrNoResponseFromVAS)
return
}
}
err = session.Remove(s.UserID, ctx.Values().GetString(CtxClientName))
if err != nil {
msg.WriteError(ctx, http.StatusInternalServerError, msg.ErrWriteToDb)
return
}
msg.WriteResponse(ctx, msg.CBool, msg.Bool{
Success: true,
})
}
|
package main
import (
"fmt"
"github.com/crowdmob/goamz/aws"
"github.com/crowdmob/goamz/ec2"
"github.com/docopt/docopt-go"
"log"
"os"
"regexp"
"strconv"
"time"
)
const version = "0.1"
var usage = `amicleanup: clean up old AWS AMI backups and snapshots
Usage:
amicleanup [options] <ami_name_regex>
amicleanup -h --help
amicleanup --version
Options:
-r, --region=<region> AWS region of running instance [default: us-east-1].
-d, --dry-run Show what would be purged without purging it.
-K, --awskey=<keyid> AWS key ID (or use AWS_ACCESS_KEY_ID environemnt variable).
-S, --awssecret=<secret> AWS secret key (or use AWS_SECRET_ACCESS_KEY environemnt variable).
--version Show version.
-h, --help Show this screen.
AWS Authentication:
Either use the -K and -S flags, or
set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.
`
type session struct {
dryRun bool
nameRegex string
region aws.Region
awsAccessKeyId string
awsSecretAccessKey string
}
var regionMap = map[string]aws.Region{
"us-gov-west-1": aws.USGovWest,
"us-east-1": aws.USEast,
"us-west-1": aws.USWest,
"us-west-2": aws.USWest2,
"eu-west-1": aws.EUWest,
"ap-southeast-1": aws.APSoutheast,
"ap-southeast-2": aws.APSoutheast2,
"ap-northeast-1": aws.APNortheast,
"sa-east-1": aws.SAEast,
}
// time formatting
var timeSecs = fmt.Sprintf("%d", time.Now().Unix())
var timeStamp = time.Now().Format("2006-01-02_15-04-05")
var timeShortFormat = "01/02/2006@15:04:05"
var timeString = time.Now().Format("2006-01-02 15:04:05 -0700")
func main() {
s := &session{}
handleOptions(s)
// connect to AWS
auth := aws.Auth{AccessKey: s.awsAccessKeyId, SecretKey: s.awsSecretAccessKey}
awsec2 := ec2.New(auth, s.region)
// purge old AMIs and snapshots
err := purgeAMIs(awsec2, s)
if err != nil {
log.Printf("Error purging old AMIs: %s", err.Error())
}
log.Printf("Finished puring AMIs and snapshots - exiting")
}
// findSnapshots returns a map of snapshots associated with an AMI
func findSnapshots(amiid string, awsec2 *ec2.EC2) (map[string]string, error) {
snaps := make(map[string]string)
resp, err := awsec2.Images([]string{amiid}, nil)
if err != nil {
return snaps, fmt.Errorf("EC2 API DescribeImages failed: %s", err.Error())
}
for _, image := range resp.Images {
for _, bd := range image.BlockDevices {
if len(bd.SnapshotId) > 0 {
snaps[bd.SnapshotId] = bd.DeviceName
}
}
}
return snaps, nil
}
// purgeAMIs purges AMIs based on name regex
func purgeAMIs(awsec2 *ec2.EC2, s *session) error {
filter := ec2.NewFilter()
filter.Add("is-public", "false")
imageList, err := awsec2.Images(nil, filter)
if err != nil {
return fmt.Errorf("EC2 API Images failed: %s", err.Error())
}
log.Printf("Found %d total images in %s", len(imageList.Images), awsec2.Region.Name)
images := map[string]int{}
r, err := regexp.Compile(s.nameRegex)
if err != nil {
return err
}
for _, image := range imageList.Images {
if r.MatchString(image.Name) {
log.Printf("Found: %s", image.Name)
images[image.Id] = 0
}
}
log.Printf("Found %d matching images in %s", len(images), awsec2.Region.Name)
if s.dryRun {
log.Fatal("dryrun")
}
for id, _ := range images {
// find snapshots associated with this AMI.
snaps, err := findSnapshots(id, awsec2)
if err != nil {
return fmt.Errorf("EC2 API findSnapshots failed for %s: %s", id, err.Error())
}
// deregister the AMI.
resp, err := awsec2.DeregisterImage(id)
if err != nil {
fmt.Printf("EC2 API DeregisterImage failed for %s: %s", id, err.Error())
time.Sleep(time.Second * 3)
continue
}
if resp.Response != true {
return fmt.Errorf("EC2 API DeregisterImage error for %s", id)
}
// delete snapshots associated with this AMI.
for snap, _ := range snaps {
_, err := awsec2.DeleteSnapshots(snap)
if err != nil {
fmt.Printf("EC2 API DeleteSnapshots failed for %s: %s\n", snap, err.Error())
time.Sleep(time.Second * 3)
continue
}
log.Printf("Deleted snapshot: %s (%s)", snap, id)
}
log.Printf("Purged old AMI %s", id)
}
return nil
}
// daysToHours is a helper to support 2d notation
func daysToHours(in string) (string, error) {
r, err := regexp.Compile(`^(\d+)d$`)
if err != nil {
return in, err
}
m := r.FindStringSubmatch(in)
if len(m) > 0 {
num, err := strconv.Atoi(m[1])
if err != nil {
return in, err
}
return fmt.Sprintf("%dh", num*24), nil
}
return in, nil
}
// handleOptions parses CLI options
func handleOptions(s *session) {
var ok bool
arguments, err := docopt.Parse(usage, nil, true, version, false)
if err != nil {
log.Fatalf("Error parsing arguments: %s", err.Error())
}
s.nameRegex = arguments["<ami_name_regex>"].(string)
s.region, ok = regionMap[arguments["--region"].(string)]
if !ok {
log.Fatalf("Bad region: %s", arguments["--region"].(string))
}
if arguments["--dry-run"].(bool) {
s.dryRun = true
}
if arg, ok := arguments["--awskey"].(string); ok {
s.awsAccessKeyId = arg
}
if arg, ok := arguments["--awssecret"].(string); ok {
s.awsSecretAccessKey = arg
}
// parse environment variables
if len(s.awsAccessKeyId) < 1 {
s.awsAccessKeyId = os.Getenv("AWS_ACCESS_KEY_ID")
}
if len(s.awsSecretAccessKey) < 1 {
s.awsSecretAccessKey = os.Getenv("AWS_SECRET_ACCESS_KEY")
}
if len(s.awsAccessKeyId) < 1 || len(s.awsSecretAccessKey) < 1 {
log.Fatal("Must use -K and -S options or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.")
}
}
|
package service
import (
"fmt"
"github.com/qianxunke/ego-shopping/ego-common-protos/go_out/user/user_info"
"github.com/qianxunke/ego-shopping/ego-plugins/db"
"log"
"sync"
)
var (
s *userInfoService
m sync.Mutex
)
//service 服务
type userInfoService struct {
}
func GetService() (*userInfoService, error) {
if s == nil {
return nil, fmt.Errorf("[GetService] GetService 未初始化")
}
return s, nil
}
//初始化用户服务层
func Init() {
m.Lock()
defer m.Unlock()
if s != nil {
return
}
DB := db.MasterEngine()
if DB == nil {
log.Fatal("数据库初始化出错!")
return
}
if !DB.HasTable(&user_info.UserInf{}) {
DB.CreateTable(&user_info.UserInf{})
}
s = &userInfoService{}
}
|
package app
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
_ "github.com/akhettar/rec-engine/docs"
m "github.com/akhettar/rec-engine/model"
"github.com/akhettar/rec-engine/redrec"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
httpswag "github.com/swaggo/http-swagger"
)
// App server instance type
type App struct {
router *mux.Router
eng *redrec.Redrec
}
// InitialiseApp create New APP server
func InitialiseApp(redisURL string) *App {
// 1. Create redis connection
engine, err := redrec.New(redisURL)
if err != nil {
log.Fatalf("failed to intialise recommendation engine %s", err)
}
app := &App{router: mux.NewRouter(), eng: engine}
app.initialiseRoutes()
return app
}
// Run start the server
func (a *App) Run(addr string) {
log.Fatal(http.ListenAndServe(addr, a.router))
}
func (a *App) initialiseRoutes() {
a.router.HandleFunc("/api/rate", a.rate).Methods(http.MethodPost)
a.router.HandleFunc("/api/recommendation/user/{user}", a.recommend).Methods(http.MethodGet)
a.router.HandleFunc("/api/items/user/{user}", a.userItems).Methods(http.MethodGet)
a.router.HandleFunc("/api/items", a.popularItems).Methods(http.MethodGet)
a.router.HandleFunc("/api/probability/user/{user}/item/{item}", a.itemProbability).Methods(http.MethodGet)
a.router.PathPrefix("/swagger/").Handler(httpswag.WrapHandler)
}
// @Summary Create rating for a gien user with an item
// @ID post-rate
// @Description Adds rating for a given user with an item
// @Produce json
// @Param body body model.Rate true "body"
// @Success 201 {object} model.Rate "Rating created"
// @Failure 400 {object} model.ErrResponse "Invalid payload"
// @Failure 500 {object} model.ErrResponse "Internal server error"
// @Router /api/rate [post]
func (a *App) rate(rw http.ResponseWriter, r *http.Request) {
var req m.Rate
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondWithError(rw, http.StatusBadRequest, fmt.Sprintf("Failed to desrialise the payload: %s", err))
return
}
if err := a.eng.Rate(req.Item, req.User, req.Score); err != nil {
respondWithError(rw, http.StatusInternalServerError, err.Error())
return
}
log.Infof("User %s ranked item %s with %f", req.User, req.Item, req.Score)
respondWithJSON(rw, http.StatusCreated, req)
}
// @Summary Get recommendations
// @ID get-recommendations
// @Description Gets recommendations for a given user
// @Produce json
// @Param user path string true "user ID"
// @Success 200 {object} model.Recommendations "Recommendation returned"
// @Failure 400 {object} model.ErrResponse "Invalid payload"
// @Failure 500 {object} model.ErrResponse "Internal server error"
// @Router /api/recommendation/user/{user} [get]
func (a *App) recommend(rw http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
user := vars["user"]
log.WithFields(log.Fields{"User": user}).Info("Received request to retrienve suggestion for user")
// 1. batch upddate DB
if err := a.eng.BatchUpdateSimilarUsers(-1); err != nil {
log.Warnf("failed to update DB with erro %s", err)
}
// 2. Update suggested items
if err := a.eng.UpdateSuggestedItems(user, 10000); err != nil {
respondWithError(rw, http.StatusInternalServerError, err.Error())
return
}
// 2. Get suggestions for a given user
results, err := a.eng.GetUserSuggestions(user, 10000)
if err != nil {
respondWithError(rw, http.StatusInternalServerError, err.Error())
return
}
log.Infof("Got results: %v", results)
respondWithJSON(rw, http.StatusOK, convertToRecommendations(user, results))
}
// @Summary Get probability
// @ID get-probability
// @Description Gets probability for a given user and item
// @Produce json
// @Param user path string true "user ID"
// @Param item path string true "item ID"
// @Success 200 {object} model.ItemProbability "ItemProbability returned"
// @Failure 400 {object} model.ErrResponse "Invalid payload"
// @Failure 500 {object} model.ErrResponse "Internal server error"
// @Router /api/probability/user/{user}/item/{item} [get]
func (a *App) itemProbability(rw http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
user := vars["user"]
item := vars["item"]
log.WithFields(log.Fields{"User": user, "Item": item}).Info("Received request to calculate item probability of given user")
result, err := a.eng.CalcItemProbability(user, item)
if err != nil {
respondWithError(rw, http.StatusInternalServerError, err.Error())
return
}
log.Infof("Got results: %v", m.ItemProbability{User: user, Item: item, Probability: result})
respondWithJSON(rw, http.StatusOK, m.ItemProbability{User: user, Item: item, Probability: result})
}
// @Summary Get User Items
// @ID get-user-item
// @Description Gets user items
// @Produce json
// @Param user path string true "user ID"
// @Success 200 {object} model.Items "Items returned"
// @Failure 400 {object} model.ErrResponse "Invalid payload"
// @Failure 500 {object} model.ErrResponse "Internal server error"
// @Router /api/items/user/{user} [get]
func (a *App) userItems(rw http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
user := vars["user"]
log.WithFields(log.Fields{"User": user}).Info("Received request to calculate item probability of given user")
result, err := a.eng.GetUserItems(user, 10000)
if err != nil {
respondWithError(rw, http.StatusInternalServerError, err.Error())
return
}
log.Infof("Got results: %v", result)
respondWithJSON(rw, http.StatusOK, convertToIterms(user, result))
}
// @Summary Get most popular items
// @ID get-popular-items
// @Description Gets the most popular items
// @Produce json
// @Param size query string false "number of results size"
// @Success 200 {object} model.Items "Items returned"
// @Failure 400 {object} model.ErrResponse "Invalid payload"
// @Failure 500 {object} model.ErrResponse "Internal server error"
// @Router /api/items [get]
func (a *App) popularItems(rw http.ResponseWriter, r *http.Request) {
log.Info("Received request to retrieve the most popular items")
resultSize := -1
if size, err := strconv.Atoi(r.URL.Query().Get("size")); err == nil {
resultSize = size - 1
}
log.Infof("size got: %d", resultSize)
results, err := a.eng.GetPopularItems(resultSize)
if err != nil {
respondWithError(rw, http.StatusInternalServerError, err.Error())
return
}
log.Infof("Got results: %v", results)
respondWithJSON(rw, http.StatusOK, convertToIterms("", results))
}
|
package xxh3
import (
"encoding/binary"
"math/bits"
"unsafe"
)
type (
ptr = unsafe.Pointer
ui = uintptr
u8 = uint8
u32 = uint32
u64 = uint64
)
var le = binary.LittleEndian
func readU8(p ptr, o ui) uint8 { return *(*uint8)(ptr(ui(p) + o)) }
func readU16(p ptr, o ui) uint16 { return le.Uint16((*[2]byte)(ptr(ui(p) + o))[:]) }
func readU32(p ptr, o ui) uint32 { return le.Uint32((*[4]byte)(ptr(ui(p) + o))[:]) }
func readU64(p ptr, o ui) uint64 { return le.Uint64((*[8]byte)(ptr(ui(p) + o))[:]) }
func writeU64(p ptr, o ui, v u64) { le.PutUint64((*[8]byte)(ptr(ui(p) + o))[:], v)}
func xxhAvalancheSmall(x u64) u64 {
x ^= x >> 33
x *= prime64_2
x ^= x >> 29
x *= prime64_3
x ^= x >> 32
return x
}
func xxh3Avalanche(x u64) u64 {
x ^= x >> 37
x *= 0x165667919e3779f9
x ^= x >> 32
return x
}
func rrmxmx(h64 u64, len u64) u64 {
h64 ^= bits.RotateLeft64(h64, 49) ^ bits.RotateLeft64(h64, 24)
h64 *= 0x9fb21c651e98df25
h64 ^= (h64 >> 35) + len
h64 *= 0x9fb21c651e98df25
h64 ^= (h64 >> 28)
return h64
}
func mulFold64(x, y u64) u64 {
hi, lo := bits.Mul64(x, y)
return hi ^ lo
}
|
package core
//go:generate counterfeiter -o ./fakeOpCaller.go --fake-name fakeOpCaller ./ opCaller
import (
"bytes"
"fmt"
"github.com/opspec-io/opctl/util/pubsub"
"github.com/opspec-io/opctl/util/uniquestring"
"github.com/opspec-io/sdk-golang/pkg/managepackages"
"github.com/opspec-io/sdk-golang/pkg/model"
"github.com/opspec-io/sdk-golang/pkg/validate"
"strconv"
"time"
)
type opCaller interface {
// Executes an op call
Call(
inboundScope map[string]*model.Data,
opId string,
pkgRef string,
rootOpId string,
) (
outboundScope map[string]*model.Data,
err error,
)
}
func newOpCaller(
pkg managepackages.ManagePackages,
pubSub pubsub.PubSub,
dcgNodeRepo dcgNodeRepo,
caller caller,
uniqueStringFactory uniquestring.UniqueStringFactory,
validate validate.Validate,
) opCaller {
return _opCaller{
managePackages: pkg,
pubSub: pubSub,
dcgNodeRepo: dcgNodeRepo,
caller: caller,
uniqueStringFactory: uniqueStringFactory,
validate: validate,
}
}
type _opCaller struct {
managePackages managepackages.ManagePackages
pubSub pubsub.PubSub
dcgNodeRepo dcgNodeRepo
caller caller
uniqueStringFactory uniquestring.UniqueStringFactory
validate validate.Validate
}
func (this _opCaller) Call(
inboundScope map[string]*model.Data,
opId string,
pkgRef string,
rootOpId string,
) (
outboundScope map[string]*model.Data,
err error,
) {
defer func() {
// defer must be defined before conditional return statements so it always runs
if nil == this.dcgNodeRepo.GetIfExists(rootOpId) {
// guard: op killed (we got preempted)
this.pubSub.Publish(
&model.Event{
Timestamp: time.Now().UTC(),
OpEnded: &model.OpEndedEvent{
OpId: opId,
Outcome: model.OpOutcomeKilled,
RootOpId: rootOpId,
PkgRef: pkgRef,
},
},
)
return
}
this.dcgNodeRepo.DeleteIfExists(opId)
var opOutcome string
if nil != err {
this.pubSub.Publish(
&model.Event{
Timestamp: time.Now().UTC(),
OpEncounteredError: &model.OpEncounteredErrorEvent{
Msg: err.Error(),
OpId: opId,
PkgRef: pkgRef,
RootOpId: rootOpId,
},
},
)
opOutcome = model.OpOutcomeFailed
} else {
opOutcome = model.OpOutcomeSucceeded
}
this.pubSub.Publish(
&model.Event{
Timestamp: time.Now().UTC(),
OpEnded: &model.OpEndedEvent{
OpId: opId,
PkgRef: pkgRef,
Outcome: opOutcome,
RootOpId: rootOpId,
},
},
)
}()
this.dcgNodeRepo.Add(
&dcgNodeDescriptor{
Id: opId,
PkgRef: pkgRef,
RootOpId: rootOpId,
Op: &dcgOpDescriptor{},
},
)
op, err := this.managePackages.GetPackage(
pkgRef,
)
if nil != err {
return
}
this.applyParamDefaultsToScope(inboundScope, op.Inputs)
// validate inputs
err = this.validateScope("input", inboundScope, op.Inputs)
if nil != err {
return
}
this.pubSub.Publish(
&model.Event{
Timestamp: time.Now().UTC(),
OpStarted: &model.OpStartedEvent{
OpId: opId,
PkgRef: pkgRef,
RootOpId: rootOpId,
},
},
)
outboundScope, err = this.caller.Call(
this.uniqueStringFactory.Construct(),
inboundScope,
op.Run,
pkgRef,
rootOpId,
)
if nil != err {
return
}
this.applyParamDefaultsToScope(outboundScope, op.Outputs)
// validate outputs
err = this.validateScope("output", outboundScope, op.Outputs)
return
}
func (this _opCaller) applyParamDefaultsToScope(
scope map[string]*model.Data,
params map[string]*model.Param,
) {
for paramName, param := range params {
// resolve var for param
var ok bool
switch {
case nil != param.Number:
if _, ok = scope[paramName]; !ok {
// apply default; value not found in scope
scope[paramName] = &model.Data{Number: param.Number.Default}
}
case nil != param.String:
if _, ok = scope[paramName]; !ok {
// apply default; value not found in scope
scope[paramName] = &model.Data{String: param.String.Default}
}
}
}
}
func (this _opCaller) validateScope(
scopeType string,
scope map[string]*model.Data,
params map[string]*model.Param,
) error {
messageBuffer := bytes.NewBufferString(``)
for paramName, param := range params {
varData := scope[paramName]
var (
argDisplayValue string
)
if nil != varData {
switch {
case nil != param.Dir:
argDisplayValue = varData.Dir
case nil != param.File:
argDisplayValue = varData.File
case nil != param.Number:
if param.Number.IsSecret {
argDisplayValue = "************"
} else {
argDisplayValue = strconv.FormatFloat(varData.Number, 'f', -1, 64)
}
case nil != param.Socket:
argDisplayValue = varData.Socket
case nil != param.String:
if param.String.IsSecret {
argDisplayValue = "************"
} else {
argDisplayValue = varData.String
}
}
}
// validate
validationErrors := this.validate.Param(varData, param)
if len(validationErrors) > 0 {
messageBuffer.WriteString(fmt.Sprintf(`
Name: %v
Value: %v
Error(s):`, paramName, argDisplayValue),
)
for _, validationError := range validationErrors {
messageBuffer.WriteString(fmt.Sprintf(`
- %v`, validationError.Error()))
}
messageBuffer.WriteString(`
`)
}
}
if messageBuffer.Len() > 0 {
return fmt.Errorf(`
-
validation of the following op %v(s) failed:
%v
-`, scopeType, messageBuffer.String())
}
return nil
}
|
// Copyright 2021 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.
package main
import (
"context"
"fmt"
"time"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
)
type jobStarter func(c *cluster) (string, error)
// jobSurvivesNodeShutdown is a helper that tests that a given job,
// running on the specified gatewayNode will still complete successfully
// if nodeToShutdown is shutdown partway through execution.
// This helper assumes:
// - That the job is long running and will take a least a minute to complete.
// - That the necessary setup is done (e.g. any data that the job relies on is
// already loaded) so that `query` can be run on its own to kick off the job.
// - That the statement running the job is a detached statement, and does not
// block until the job completes.
func jobSurvivesNodeShutdown(
ctx context.Context, t *test, c *cluster, nodeToShutdown int, startJob jobStarter,
) {
watcherNode := 1 + (nodeToShutdown)%c.spec.NodeCount
target := c.Node(nodeToShutdown)
t.l.Printf("test has chosen shutdown target node %d, and watcher node %d",
nodeToShutdown, watcherNode)
jobIDCh := make(chan string, 1)
m := newMonitor(ctx, c)
m.Go(func(ctx context.Context) error {
defer close(jobIDCh)
t.Status(`running job`)
var jobID string
jobID, err := startJob(c)
if err != nil {
return errors.Wrap(err, "starting the job")
}
t.l.Printf("started running job with ID %s", jobID)
jobIDCh <- jobID
pollInterval := 5 * time.Second
ticker := time.NewTicker(pollInterval)
watcherDB := c.Conn(ctx, watcherNode)
defer watcherDB.Close()
var status string
for {
select {
case <-ticker.C:
err := watcherDB.QueryRowContext(ctx, `SELECT status FROM [SHOW JOBS] WHERE job_id=$1`, jobID).Scan(&status)
if err != nil {
return errors.Wrap(err, "getting the job status")
}
jobStatus := jobs.Status(status)
switch jobStatus {
case jobs.StatusSucceeded:
t.Status("job completed")
return nil
case jobs.StatusRunning:
t.l.Printf("job %s still running, waiting to succeed", jobID)
default:
// Waiting for job to complete.
return errors.Newf("unexpectedly found job %s in state %s", jobID, status)
}
case <-ctx.Done():
return errors.Wrap(ctx.Err(), "context canceled while waiting for job to finish")
}
}
})
m.Go(func(ctx context.Context) error {
jobID, ok := <-jobIDCh
if !ok {
return errors.New("job never created")
}
// Shutdown a node after a bit, and keep it shutdown for the remainder
// of the job.
timeToWait := 10 * time.Second
timer := timeutil.Timer{}
timer.Reset(timeToWait)
select {
case <-ctx.Done():
return errors.Wrapf(ctx.Err(), "stopping test, did not shutdown node")
case <-timer.C:
timer.Read = true
}
// Sanity check that the job is still running.
watcherDB := c.Conn(ctx, watcherNode)
defer watcherDB.Close()
var status string
err := watcherDB.QueryRowContext(ctx, `SELECT status FROM [SHOW JOBS] WHERE job_id=$1`, jobID).Scan(&status)
if err != nil {
return errors.Wrap(err, "getting the job status")
}
jobStatus := jobs.Status(status)
if jobStatus != jobs.StatusRunning {
return errors.Newf("job too fast! job got to state %s before the target node could be shutdown",
status)
}
t.l.Printf(`stopping node %s`, target)
if err := c.StopE(ctx, target); err != nil {
return errors.Wrapf(err, "could not stop node %s", target)
}
t.l.Printf("stopped node %s", target)
return nil
})
// Before calling `m.Wait()`, do some cleanup.
if err := m.g.Wait(); err != nil {
t.Fatal(err)
}
// NB: the roachtest harness checks that at the end of the test, all nodes
// that have data also have a running process.
t.Status(fmt.Sprintf("restarting %s (node restart test is done)\n", target))
if err := c.StartE(ctx, target); err != nil {
t.Fatal(errors.Wrapf(err, "could not restart node %s", target))
}
m.Wait()
}
|
package main
import "fmt"
// 结构体 要 比 map 自由些
// 值类型(int float bool string [x]int struct )赋值后 修改 副本 不影响 源 深cp
// 引用类型 (map slice chan interface)赋值后 修改副本 会引起 源变化,浅cp
// go 中 函数 传参 ,全是 深cp 了一个 过去,如果 &变量,才是 源 修改
type persion struct{
Name string `json:"name"`
Age int `json:"age"`
Gender string `json:"gender"`
Hobby []string `json:"hobby"`
}
func main() {
var p01,p02 persion //声明
// 初始化
p01.Age = 42
p01.Name = "kelvin"
p01.Gender = "男"
p01.Hobby = []string{"篮球","足球"}
fmt.Printf("%T %v \n",p01,p01)
p02.Age =40
p02.Name = "Yuang"
p02.Gender = "男"
p02.Hobby = []string{"排球","足球"}
fmt.Printf("%T %v \n",p02,p02)
// 指针方式 初始化
var s02 = &persion{
Name:"kelvin",
Age:42,
}
fmt.Printf("指针 结构体同时初始化:%T %v \n",s02,s02)
// 匿名结构体(用于临时场景)
var s01 struct{
Name string
Age int
}
s01.Name = "kelvin"
s01.Age = 42
fmt.Printf("匿名函数:%T %v \n",s01,s01)
f1(p01)
fmt.Println(p01.Age) //42 说明传过去 的 和 自己 没关系,函数 的参数 都会得到一个深cp
f2(&p01) //但是 传 指针地址 过去,就不一样了,改的就是 源
fmt.Println(p01.Age)
var p03 = new(persion) //p03 就是 一个指针
fmt.Printf("%T, %v \n",p03,p03)
f2(p03)
fmt.Println(p03.Age)
}
func f2(p *persion){
// (*p).Age = 1
p.Age = 2
}
func f1(p persion){
p.Age = 10
} |
package DB
import (
"RMQ_Project/common"
"RMQ_Project/model"
"database/sql"
"fmt"
)
type OrderInterface interface {
Conn() error
Insert(order *model.Order) (int64, error)
}
type OrderStruct struct {
table string
db *sql.DB
}
func NewOrderManger(table string, sql *sql.DB) OrderInterface {
return &OrderStruct{
table: table,
db: sql,
}
}
func (o *OrderStruct) Conn() (err error) {
if o.db == nil {
mysql, err := common.NewMysqlConn()
if err != nil {
fmt.Print(err)
return err
}
o.db = mysql
}
if o.table == "" {
o.table = "order"
}
return nil
}
func (o OrderStruct) Insert(order *model.Order) (id int64, err error) {
if err = o.Conn(); err != nil {
fmt.Print(err)
return id, err
}
s := fmt.Sprintf("INSERT %v SET userId=?, productId=?, orderStatus=?",o.table)
stmt, err := o.db.Prepare(s)
if err != nil {
return id,err
}
result, err := stmt.Exec(order.UserId, order.ProductId, order.OrderStatus)
if err != nil {
fmt.Print(err)
return id,err
}
return result.LastInsertId()
}
|
package main
import "fmt"
func printEndStart() {
// Printed third
defer fmt.Println("End.")
// Printed second
defer fmt.Println("Do some stuff.")
// Printed first
fmt.Println("Start.")
}
func printNum(num int) {
defer fmt.Printf("This is the number printed in a deferred statement: %v", num)
}
func main() {
printEndStart()
number := 7
/*
This will print the number 9 (not 10) - because the argument number is evaluated (as 7) before it is incremented
on line 31, even though the function printNum contains a deferred Println call.
Execution of print is deffered, but eval of the argument is not.
*/
printNum(number + 2)
number++
fmt.Println(number)
}
|
// declaration of array
// composite literals
package main
import "fmt"
func main() {
var p [10]string
p[0] = "hello" // assign a value
p[1] = "are"
p[2] = "you"
// access the value
loc1 := p[0]
fmt.Println("At p[o]", loc1)
// len of p
fmt.Println("len of p: ", len(p))
fmt.Println("At p[3]", p[3] == "")
}
// At p[o] hello
// len of p: 10
// At p[3] true
//----------------------composite literals
// dwarfs := [5]string{"Ceres", "Pluto", "Haumea", "Makemake", "Eris"}
// planets := [...]string{ 1
// "Mercury",
// "Venus",
// "Earth",
// "Mars",
// "Jupiter",
// "Saturn",
// "Uranus",
// }
|
/*
Copyright 2019 Adobe
All Rights Reserved.
NOTICE: Adobe permits you to use, modify, and distribute this file in
accordance with the terms of the Adobe license agreement accompanying
it. If you have received this file from a source other than Adobe,
then your use, modification, or distribution of it requires the prior
written permission of Adobe.
*/
package maker
import "testing"
func TestResolveTemplateURL(t *testing.T) {
tests := []struct {
input string
url string
}{
{input: "go-scaffolding", url: "https://github.com/go-scaffolding"},
{input: "adobe/go-scaffolding", url: "https://github.com/adobe/go-scaffolding"},
{input: "//github.adobe.com/adobe/go-scaffolding", url: "https://github.adobe.com/adobe/go-scaffolding"},
{input: "git://github.adobe.com/adobe/go-scaffolding", url: "git://github.adobe.com/adobe/go-scaffolding"},
{input: "git@github.adobe.com:adobe/go-scaffolding", url: "git@github.adobe.com:adobe/go-scaffolding"},
}
for _, test := range tests {
t.Run(test.input, func(t *testing.T) {
got := ResolveTemplateURL(test.input)
if want := test.url; got != want {
t.Errorf("Resolved URL does not match, got %#v, want %#v", got, want)
}
})
}
}
|
package main
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/moyen-blog/client-go/client"
)
// printDiff prints the staged actions required to synchronize local with remote files
func printDiff(diff []client.AssetDiff) {
fmt.Printf("%d action(s) staged\n", len(diff))
for _, i := range diff {
switch i.Action {
case client.Create:
fmt.Printf("\033[32mCREATE\033[0m\t%s\n", i.Asset.Path)
case client.Update:
fmt.Printf("\033[33mUPDATE\033[0m\t%s\n", i.Asset.Path)
case client.Delete:
fmt.Printf("\033[31mDELETE\033[0m\t%s\n", i.Asset.Path)
}
}
}
// printProgress is a callback that we'll pass to client.Sync()
// It simply prints the results of an action but does not halt sync
func printProgress(asset client.Asset, err error) error {
if err == nil {
fmt.Printf("\033[32mSUCCESS\033[0m\t%s\n", asset.Path)
}
handleError("Failed to synchronize", err, false)
return nil // Continue with sync regardless of errors
}
// askForConfirmation prompts the user to confirm a proposed action
// Defaults to reading input from stdin
func askForConfirmation(s string, r *bufio.Reader) bool {
if r == nil {
r = bufio.NewReader(os.Stdin)
}
for {
fmt.Printf("%s [y/n]: ", s)
response, err := r.ReadString('\n')
handleError("Failed to read user input", err, true)
response = strings.ToLower(strings.TrimSpace(response))
if response == "y" || response == "yes" {
return true
} else if response == "n" || response == "no" {
return false
}
}
}
// handleError prints an error message of not nil
// If fatal is true, kills process with non-zero error code
func handleError(message string, err error, fatal bool) {
if err != nil {
fmt.Printf("\033[31mERROR\033[0m\t%s \033[2m%s\033[0m\n", message, err.Error())
if fatal {
os.Exit(1)
}
}
}
|
package vsphere
const STATICIP_CUSTOM_SPEC_NAME = "static-ip-libretto"
const XML_STATIC_IP_SPEC = `
<ConfigRoot>
<_type>vim.CustomizationSpecItem</_type>
<info>
<_type>vim.CustomizationSpecInfo</_type>
<changeVersion>1505235815</changeVersion>
<description/>
<lastUpdateTime>2017-09-12T17:03:35Z</lastUpdateTime>
<name>static-ip-libretto</name>
<type>Linux</type>
</info>
<spec>
<_type>vim.vm.customization.Specification</_type>
<globalIPSettings>
<_type>vim.vm.customization.GlobalIPSettings</_type>
<dnsServerList>
<_length>1</_length>
<_type>string[]</_type>
<e id="0">8.8.8.8</e>
</dnsServerList>
<dnsSuffixList>
<_length>1</_length>
<_type>string[]</_type>
<e id="0">gsintlab.com</e>
</dnsSuffixList>
</globalIPSettings>
<identity>
<_type>vim.vm.customization.LinuxPrep</_type>
<domain>gsintlab.com</domain>
<hostName>
<_type>vim.vm.customization.VirtualMachineNameGenerator</_type>
</hostName>
</identity>
<nicSettingMap>
<_length>1</_length>
<_type>vim.vm.customization.AdapterMapping[]</_type>
<e id="0">
<_type>vim.vm.customization.AdapterMapping</_type>
<adapter>
<_type>vim.vm.customization.IPSettings</_type>
<gateway>
<_length>1</_length>
<_type>string[]</_type>
<e id="0">10.10.24.1</e>
</gateway>
<ip>
<_type>vim.vm.customization.FixedIp</_type>
<ipAddress>10.10.24.100</ipAddress>
</ip>
<subnetMask>255.255.255.0</subnetMask>
</adapter>
</e>
</nicSettingMap>
<options>
<_type>vim.vm.customization.LinuxOptions</_type>
</options>
</spec>
</ConfigRoot>
`
|
// Package objects contains object interfaces and concrete object types that can
// reside within an environment.
package objects
|
package networkcrd
const (
GroupName = "networkcrd.k8s.io"
Version = "v1"
)
|
package docker
import (
"mdocker/utils"
"fmt"
"errors"
)
type Images struct {
Manage *DockerManage
}
func NewImages() *Images {
manage := NewDockerManage()
return &Images{manage}
}
func (images *Images) ClearTemp() error {
get_tmp_image_cmd := images.Manage.getCmd("images -q -f dangling=true")
rm_cmd := images.Manage.getCmd(fmt.Sprintf("rmi $(%s)", get_tmp_image_cmd))
if result := utils.OutIsNil(get_tmp_image_cmd); result == false {
return errors.New("no images to clear")
}
_, err := utils.Exec_shell(rm_cmd)
if err != nil {
return err
}
return nil
}
func (Images *Images) Show() error {
show_cmd := Images.Manage.getCmd("images")
if res := utils.OutIsNil(show_cmd); res == false {
return errors.New("no images")
}
out, err := utils.Exec_shell(show_cmd)
if err != nil {
return err
}
fmt.Println(out)
return nil
} |
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package camera
import (
"context"
"regexp"
"time"
"chromiumos/tast/common/media/caps"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/assistant"
"chromiumos/tast/local/camera/cca"
"chromiumos/tast/local/camera/testutil"
"chromiumos/tast/local/chrome"
"chromiumos/tast/testing"
)
type assistantOptions struct {
Query string
Mode cca.Mode
ShouldStartCapture bool
ExpectedFacing cca.Facing
}
func init() {
testing.AddTest(&testing.Test{
Func: CCAUIAssistant,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Tests opening Camera app using an Assistant query",
Contacts: []string{
"pihsun@chromium.org",
"chromeos-camera-eng@google.com",
},
Attr: []string{"group:mainline", "informational"},
SoftwareDeps: []string{"chrome", "chrome_internal", "camera_app", caps.BuiltinOrVividCamera},
Data: []string{"cca_ui.js"},
Fixture: "ccaTestBridgeReady",
})
}
// CCAUIAssistant tests that the Camera app can be opened by the Assistant.
func CCAUIAssistant(ctx context.Context, s *testing.State) {
cr := s.FixtValue().(cca.FixtureData).Chrome
tb := s.FixtValue().(cca.FixtureData).TestBridge()
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Creating test API connection failed: ", err)
}
// Enable the Assistant and wait for the ready signal.
if err := assistant.EnableAndWaitForReady(ctx, tconn); err != nil {
s.Fatal("Failed to enable Assistant: ", err)
}
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 3*time.Second)
defer cancel()
defer func() {
if err := assistant.Cleanup(cleanupCtx, s.HasError, cr, tconn); err != nil {
s.Fatal("Failed to disable Assistant: ", err)
}
}()
scripts := []string{s.DataPath("cca_ui.js")}
outDir := s.OutDir()
for _, tc := range []struct {
name string
Options assistantOptions
}{
{
name: "take_photo",
Options: assistantOptions{
Query: "take a photo",
Mode: cca.Photo,
ShouldStartCapture: true,
},
},
{
name: "take_selfie",
Options: assistantOptions{
Query: "take a selfie",
Mode: cca.Photo,
ShouldStartCapture: true,
ExpectedFacing: cca.FacingFront,
},
},
{
name: "open_cca_photo_mode",
Options: assistantOptions{
Query: "open camera",
Mode: cca.Photo,
ShouldStartCapture: false,
},
},
{
name: "start_record_video",
Options: assistantOptions{
Query: "record video",
Mode: cca.Video,
ShouldStartCapture: true,
},
},
{
name: "open_cca_video_mode",
Options: assistantOptions{
Query: "open video camera",
Mode: cca.Video,
ShouldStartCapture: false,
},
},
} {
s.Run(ctx, tc.name, func(ctx context.Context, s *testing.State) {
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
if err := cca.ClearSavedDir(ctx, cr); err != nil {
s.Fatal("Failed to clear saved directory: ", err)
}
startTime := time.Now()
options := tc.Options
app, err := launchAssistant(ctx, cr, options, scripts, outDir, tb)
if err != nil {
s.Fatal("Failed to launch assistant: ", err)
}
defer func(ctx context.Context) {
if err := app.Close(ctx); err != nil {
s.Fatal("Failed to close CCA: ", err)
}
}(ctx)
if err := app.CheckMode(ctx, options.Mode); err != nil {
s.Fatal("Failed to check mode: ", err)
}
if options.ExpectedFacing != "" {
if err := app.CheckCameraFacing(ctx, options.ExpectedFacing); err != nil {
s.Fatal("Failed to check facing: ", err)
}
}
if options.ShouldStartCapture {
if options.Mode == cca.Video {
if err := app.WaitForState(ctx, "recording", true); err != nil {
s.Fatal("Recording is not started: ", err)
}
// Wait video recording for 1 second to simulate user taking a 1
// second long video.
if err := testing.Sleep(ctx, 1*time.Second); err != nil {
s.Fatal("Failed to sleep for 1 second: ", err)
}
testing.ContextLog(ctx, "Stopping recording")
if err := app.ClickShutter(ctx); err != nil {
s.Fatal("Failed to click shutter button: ", err)
}
}
if err := checkAssistantCaptureResult(ctx, app, options.Mode, startTime); err != nil {
s.Fatal("Failed to check capture result: ", err)
}
}
})
}
}
// launchAssistant launches CCA intent with different options.
func launchAssistant(ctx context.Context, cr *chrome.Chrome, options assistantOptions, scripts []string, outDir string, tb *testutil.TestBridge) (*cca.App, error) {
launchByAssistant := func(ctx context.Context, tconn *chrome.TestConn) error {
_, err := assistant.SendTextQuery(ctx, tconn, options.Query)
return err
}
return cca.Init(ctx, cr, scripts, outDir, testutil.AppLauncher{
LaunchApp: launchByAssistant,
UseSWAWindow: false,
}, tb)
}
func checkAssistantCaptureResult(ctx context.Context, app *cca.App, mode cca.Mode, startTime time.Time) error {
dir, err := app.SavedDir(ctx)
if err != nil {
return errors.Wrap(err, "failed to get CCA default saved path")
}
testing.ContextLog(ctx, "Waiting for capture result")
var filePattern *regexp.Regexp
if mode == cca.Video {
filePattern = cca.VideoPattern
} else {
filePattern = cca.PhotoPattern
}
_, err = app.WaitForFileSaved(ctx, dir, filePattern, startTime)
if err != nil {
return err
}
return nil
}
|
// +build unix linux
package fuse
import (
"testing"
"bazil.org/fuse/fs"
)
func TestHashable(t *testing.T) {
table := make(map[fs.Node]int)
table[root(0)] = 42
table[directory{}] = 57
table[file{}] = 12
}
|
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tshttpproxy
import (
"context"
"encoding/base64"
"fmt"
"log"
"net/http"
"net/url"
"runtime"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"github.com/alexbrainman/sspi/negotiate"
"golang.org/x/sys/windows"
"tailscale.com/types/logger"
)
var (
winHTTP = windows.NewLazySystemDLL("winhttp.dll")
httpOpenProc = winHTTP.NewProc("WinHttpOpen")
closeHandleProc = winHTTP.NewProc("WinHttpCloseHandle")
getProxyForUrlProc = winHTTP.NewProc("WinHttpGetProxyForUrl")
)
func init() {
sysProxyFromEnv = proxyFromWinHTTPOrCache
sysAuthHeader = sysAuthHeaderWindows
}
var cachedProxy struct {
sync.Mutex
val *url.URL
}
// proxyErrorf is a rate-limited logger specifically for errors asking
// WinHTTP for the proxy information. We don't want to log about
// errors often, otherwise the log message itself will generate a new
// HTTP request which ultimately will call back into us to log again,
// forever. So for errors, we only log a bit.
var proxyErrorf = logger.RateLimitedFn(log.Printf, 10*time.Minute, 2 /* burst*/, 10 /* maxCache */)
func proxyFromWinHTTPOrCache(req *http.Request) (*url.URL, error) {
if req.URL == nil {
return nil, nil
}
urlStr := req.URL.String()
ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
defer cancel()
type result struct {
proxy *url.URL
err error
}
resc := make(chan result, 1)
go func() {
proxy, err := proxyFromWinHTTP(ctx, urlStr)
resc <- result{proxy, err}
}()
select {
case res := <-resc:
err := res.err
if err == nil {
cachedProxy.Lock()
defer cachedProxy.Unlock()
if was, now := fmt.Sprint(cachedProxy.val), fmt.Sprint(res.proxy); was != now {
log.Printf("tshttpproxy: winhttp: updating cached proxy setting from %v to %v", was, now)
}
cachedProxy.val = res.proxy
return res.proxy, nil
}
// See https://docs.microsoft.com/en-us/windows/win32/winhttp/error-messages
const (
ERROR_WINHTTP_AUTODETECTION_FAILED = 12180
ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT = 12167
)
if err == syscall.Errno(ERROR_WINHTTP_AUTODETECTION_FAILED) {
setNoProxyUntil(10 * time.Second)
return nil, nil
}
if err == windows.ERROR_INVALID_PARAMETER {
// Seen on Windows 8.1. (https://github.com/tailscale/tailscale/issues/879)
// TODO(bradfitz): figure this out.
setNoProxyUntil(time.Hour)
proxyErrorf("tshttpproxy: winhttp: GetProxyForURL(%q): ERROR_INVALID_PARAMETER [unexpected]", urlStr)
return nil, nil
}
proxyErrorf("tshttpproxy: winhttp: GetProxyForURL(%q): %v/%#v", urlStr, err, err)
if err == syscall.Errno(ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT) {
setNoProxyUntil(10 * time.Second)
return nil, nil
}
return nil, err
case <-ctx.Done():
cachedProxy.Lock()
defer cachedProxy.Unlock()
proxyErrorf("tshttpproxy: winhttp: GetProxyForURL(%q): timeout; using cached proxy %v", urlStr, cachedProxy.val)
return cachedProxy.val, nil
}
}
func proxyFromWinHTTP(ctx context.Context, urlStr string) (proxy *url.URL, err error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
whi, err := winHTTPOpen()
if err != nil {
proxyErrorf("winhttp: Open: %v", err)
return nil, err
}
defer whi.Close()
t0 := time.Now()
v, err := whi.GetProxyForURL(urlStr)
td := time.Since(t0).Round(time.Millisecond)
if err := ctx.Err(); err != nil {
log.Printf("tshttpproxy: winhttp: context canceled, ignoring GetProxyForURL(%q) after %v", urlStr, td)
return nil, err
}
if err != nil {
return nil, err
}
if v == "" {
return nil, nil
}
// Discard all but first proxy value for now.
if i := strings.Index(v, ";"); i != -1 {
v = v[:i]
}
if !strings.HasPrefix(v, "https://") {
v = "http://" + v
}
return url.Parse(v)
}
var userAgent = windows.StringToUTF16Ptr("Tailscale")
const (
winHTTP_ACCESS_TYPE_AUTOMATIC_PROXY = 4
winHTTP_AUTOPROXY_ALLOW_AUTOCONFIG = 0x00000100
winHTTP_AUTOPROXY_AUTO_DETECT = 1
winHTTP_AUTO_DETECT_TYPE_DHCP = 0x00000001
winHTTP_AUTO_DETECT_TYPE_DNS_A = 0x00000002
)
func winHTTPOpen() (winHTTPInternet, error) {
if err := httpOpenProc.Find(); err != nil {
return 0, err
}
r, _, err := httpOpenProc.Call(
uintptr(unsafe.Pointer(userAgent)),
winHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
0, /* WINHTTP_NO_PROXY_NAME */
0, /* WINHTTP_NO_PROXY_BYPASS */
0)
if r == 0 {
return 0, err
}
return winHTTPInternet(r), nil
}
type winHTTPInternet windows.Handle
func (hi winHTTPInternet) Close() error {
if err := closeHandleProc.Find(); err != nil {
return err
}
r, _, err := closeHandleProc.Call(uintptr(hi))
if r == 1 {
return nil
}
return err
}
// WINHTTP_AUTOPROXY_OPTIONS
// https://docs.microsoft.com/en-us/windows/win32/api/winhttp/ns-winhttp-winhttp_autoproxy_options
type autoProxyOptions struct {
DwFlags uint32
DwAutoDetectFlags uint32
AutoConfigUrl *uint16
_ uintptr
_ uint32
FAutoLogonIfChallenged bool
}
// WINHTTP_PROXY_INFO
// https://docs.microsoft.com/en-us/windows/win32/api/winhttp/ns-winhttp-winhttp_proxy_info
type winHTTPProxyInfo struct {
AccessType uint16
Proxy *uint16
ProxyBypass *uint16
}
var proxyForURLOpts = &autoProxyOptions{
DwFlags: winHTTP_AUTOPROXY_ALLOW_AUTOCONFIG | winHTTP_AUTOPROXY_AUTO_DETECT,
DwAutoDetectFlags: winHTTP_AUTO_DETECT_TYPE_DHCP, // | winHTTP_AUTO_DETECT_TYPE_DNS_A,
}
func (hi winHTTPInternet) GetProxyForURL(urlStr string) (string, error) {
if err := getProxyForUrlProc.Find(); err != nil {
return "", err
}
var out winHTTPProxyInfo
r, _, err := getProxyForUrlProc.Call(
uintptr(hi),
uintptr(unsafe.Pointer(windows.StringToUTF16Ptr(urlStr))),
uintptr(unsafe.Pointer(proxyForURLOpts)),
uintptr(unsafe.Pointer(&out)))
if r == 1 {
return windows.UTF16PtrToString(out.Proxy), nil
}
return "", err
}
func sysAuthHeaderWindows(u *url.URL) (string, error) {
spn := "HTTP/" + u.Hostname()
creds, err := negotiate.AcquireCurrentUserCredentials()
if err != nil {
return "", fmt.Errorf("negotiate.AcquireCurrentUserCredentials: %w", err)
}
defer creds.Release()
secCtx, token, err := negotiate.NewClientContext(creds, spn)
if err != nil {
return "", fmt.Errorf("negotiate.NewClientContext: %w", err)
}
defer secCtx.Release()
return "Negotiate " + base64.StdEncoding.EncodeToString(token), nil
}
|
package http_util
type HttpRequest interface {
Path() string
Headers() map[string]string
}
type LazyHttpRequest struct {
tcpRequest string
tcpHttpParser HttpParser
}
func NewLazyHttpRequest(tcpRequest string) HttpRequest {
return &LazyHttpRequest{
tcpRequest: tcpRequest,
tcpHttpParser: NewTcpHttpParser(),
}
}
func (l LazyHttpRequest) Path() string {
return l.tcpHttpParser.ParsePath(l.tcpRequest)
}
func (l LazyHttpRequest) Headers() map[string]string {
return l.tcpHttpParser.ParseHeaders(l.tcpRequest)
}
|
// +build linux
// This program demonstrates how to attach an eBPF program to a tracepoint.
// The program will be attached to the sys_enter_open syscall and print out the integer
// 123 everytime the sycall is used.
package main
import (
"context"
"fmt"
"os"
"runtime"
"time"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/asm"
ringbuffer "github.com/cilium/ebpf/perf"
"golang.org/x/sys/unix"
"github.com/elastic/go-perf"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Increase rlimit so the eBPF map and program can be loaded.
if err := unix.Setrlimit(unix.RLIMIT_MEMLOCK, &unix.Rlimit{
Cur: unix.RLIM_INFINITY,
Max: unix.RLIM_INFINITY,
}); err != nil {
panic(fmt.Errorf("failed to set temporary rlimit: %v", err))
}
events, err := ebpf.NewMap(&ebpf.MapSpec{
Type: ebpf.PerfEventArray,
Name: "pureGo",
})
if err != nil {
panic(fmt.Errorf("could not create event map: %v", err))
}
defer events.Close()
rd, err := ringbuffer.NewReader(events, os.Getpagesize())
if err != nil {
panic(fmt.Errorf("could not create event reader: %v", err))
}
defer rd.Close()
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
record, err := rd.Read()
if err != nil {
if ringbuffer.IsClosed(err) {
return
}
panic(fmt.Errorf("could not read from reader: %v", err))
}
fmt.Println(record)
}
}()
ins := asm.Instructions{
// store the integer 123 at FP[-8]
asm.Mov.Imm(asm.R2, 123),
asm.StoreMem(asm.RFP, -8, asm.R2, asm.Word),
// load registers with arguments for call of FnPerfEventOutput
asm.LoadMapPtr(asm.R2, events.FD()),
asm.LoadImm(asm.R3, 0xffffffff, asm.DWord),
asm.Mov.Reg(asm.R4, asm.RFP),
asm.Add.Imm(asm.R4, -8),
asm.Mov.Imm(asm.R5, 4),
// call FnPerfEventOutput
asm.FnPerfEventOutput.Call(),
// set exit code to 0
asm.Mov.Imm(asm.R0, 0),
asm.Return(),
}
prog, err := ebpf.NewProgram(&ebpf.ProgramSpec{
Name: "trace_open",
Type: ebpf.TracePoint,
License: "GPL",
Instructions: ins,
})
if err != nil {
panic(fmt.Errorf("could not create new ebpf program: %v", err))
}
defer prog.Close()
ga := new(perf.Attr)
gtp := perf.Tracepoint("syscalls", "sys_enter_open")
if err := gtp.Configure(ga); err != nil {
panic(fmt.Errorf("failed to configure tracepoint: %v", err))
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
openTracepoint, err := perf.Open(ga, perf.AllThreads, 0, nil)
if err != nil {
panic(fmt.Errorf("failed to open perf event on tracepoint: %v", err))
}
defer openTracepoint.Close()
if err := openTracepoint.SetBPF(uint32(prog.FD())); err != nil {
panic(fmt.Errorf("failed to attach eBPF to tracepoint: %v", err))
}
if err := openTracepoint.Enable(); err != nil {
panic(fmt.Errorf("failed to enable eBPF to tracepoint: %v", err))
}
<-ctx.Done()
}
|
/*******************************************************************************
* Copyright 2017 Samsung Electronics 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 api/agent provides functionality to handle request related to agent.
package agent
import (
"api/common"
"commons/errors"
"commons/logger"
"commons/results"
URL "commons/url"
"manager/agent"
"net/http"
"strings"
)
const (
GET string = "GET"
PUT string = "PUT"
POST string = "POST"
DELETE string = "DELETE"
)
type _SDAMAgentApisHandler struct{}
type _SDAMAgentApis struct{}
var sdamH _SDAMAgentApisHandler
var sdam _SDAMAgentApis
var sdamAgentController agent.AgentInterface
func init() {
SdamAgentHandle = sdamH
SdamAgent = sdam
sdamAgentController = agent.AgentController{}
}
// Handle calls a proper function according to the url and method received from remote device.
func (sdamH _SDAMAgentApisHandler) Handle(w http.ResponseWriter, req *http.Request) {
url := strings.Replace(req.URL.Path, URL.Base()+URL.Agents(), "", -1)
split := strings.Split(url, "/")
switch len(split) {
case 1:
if req.Method == GET {
SdamAgent.agents(w, req)
} else {
common.WriteError(w, errors.InvalidMethod{req.Method})
}
case 2:
if "/"+split[1] == URL.Register() {
if req.Method == POST {
SdamAgent.agentRegister(w, req)
} else {
common.WriteError(w, errors.InvalidMethod{req.Method})
}
} else {
if req.Method == GET {
agentID := split[1]
SdamAgent.agent(w, req, agentID)
} else {
common.WriteError(w, errors.InvalidMethod{req.Method})
}
}
case 3:
agentID := split[1]
if "/"+split[2] == URL.Deploy() {
if req.Method == POST {
SdamAgent.agentDeployApp(w, req, agentID)
} else {
common.WriteError(w, errors.InvalidMethod{req.Method})
}
} else if "/"+split[2] == URL.Unregister() {
if req.Method == POST {
SdamAgent.agentUnregister(w, req, agentID)
} else {
common.WriteError(w, errors.InvalidMethod{req.Method})
}
} else if "/"+split[2] == URL.Ping() {
if req.Method == POST {
SdamAgent.agentPing(w, req, agentID)
} else {
common.WriteError(w, errors.InvalidMethod{req.Method})
}
} else if "/"+split[2] == URL.Apps() {
if req.Method == GET {
SdamAgent.agentInfoApps(w, req, agentID)
} else {
common.WriteError(w, errors.InvalidMethod{req.Method})
}
} else {
common.WriteError(w, errors.NotFoundURL{})
}
case 4:
if "/"+split[2] == URL.Apps() {
agentID, appID := split[1], split[3]
switch req.Method {
case GET:
SdamAgent.agentInfoApp(w, req, agentID, appID)
case POST:
SdamAgent.agentUpdateAppInfo(w, req, agentID, appID)
case DELETE:
SdamAgent.agentDeleteApp(w, req, agentID, appID)
default:
common.WriteError(w, errors.InvalidMethod{req.Method})
}
} else {
common.WriteError(w, errors.NotFoundURL{})
}
case 5:
if "/"+split[2] == URL.Apps() {
agentID, appID := split[1], split[3]
switch {
case "/"+split[4] == URL.Start() && req.Method == POST:
SdamAgent.agentStartApp(w, req, agentID, appID)
case "/"+split[4] == URL.Stop() && req.Method == POST:
SdamAgent.agentStopApp(w, req, agentID, appID)
case "/"+split[4] == URL.Update() && req.Method == POST:
SdamAgent.agentUpdateApp(w, req, agentID, appID)
default:
common.WriteError(w, errors.InvalidMethod{req.Method})
}
} else {
common.WriteError(w, errors.NotFoundURL{})
}
}
}
// agentRegister handles requests which is used to register agent to a list of agents.
//
// paths: '/api/v1/agents/{agentID}/register'
// method: POST
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentRegister(w http.ResponseWriter, req *http.Request) {
logger.Logging(logger.DEBUG, "[AGENT] Register New Service Deployment Agent")
body, err := common.GetBodyFromReq(req)
if err != nil {
common.MakeResponse(w, results.ERROR, nil, err)
return
}
result, resp, err := sdamAgentController.AddAgent(body)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentUnregister handles requests which is used to unregister agent from a list of agents.
//
// paths: '/api/v1/agents/{agentID}/unregister'
// method: POST
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentUnregister(w http.ResponseWriter, req *http.Request, agentID string) {
logger.Logging(logger.DEBUG, "[AGENT] Unregister New Service Deployment Agent")
result, err := sdamAgentController.DeleteAgent(agentID)
common.MakeResponse(w, result, nil, err)
}
// agentPing handles requests which is used to check whether an agent is up.
//
// paths: '/api/v1/agents/{agentID}/ping'
// method: POST
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentPing(w http.ResponseWriter, req *http.Request, agentID string) {
logger.Logging(logger.DEBUG, "[AGENT] Ping From Service Deployment Agent")
ip := strings.Split(req.RemoteAddr, ":")[0]
body, err := common.GetBodyFromReq(req)
if err != nil {
common.MakeResponse(w, results.ERROR, nil, err)
return
}
result, err := sdamAgentController.PingAgent(agentID, ip, body)
common.MakeResponse(w, result, nil, err)
}
// agents handles requests which is used to get information of agent identified by the given agentID.
//
// paths: '/api/v1/agents/{agentID}'
// method: GET
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agent(w http.ResponseWriter, req *http.Request, agentID string) {
logger.Logging(logger.DEBUG, "[AGENT] Get Service Deployment Agent")
result, resp, err := sdamAgentController.GetAgent(agentID)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agents handles requests which is used to get information of all agents registered.
//
// paths: '/api/v1/agents'
// method: GET
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agents(w http.ResponseWriter, req *http.Request) {
logger.Logging(logger.DEBUG, "[AGENT] Get All Service Deployment Agents")
result, resp, err := sdamAgentController.GetAgents()
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentDeployApp handles requests which is used to deploy new application to agent
// identified by the given agentID.
//
// paths: '/api/v1/agents/{agentID}/deploy'
// method: POST
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentDeployApp(w http.ResponseWriter, req *http.Request, agentID string) {
logger.Logging(logger.DEBUG, "[AGENT] Deploy App")
body, err := common.GetBodyFromReq(req)
if err != nil {
common.MakeResponse(w, results.ERROR, nil, err)
return
}
result, resp, err := sdamAgentController.DeployApp(agentID, body)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentInfoApps handles requests which is used to get information of all applications
// installed on agent identified by the given agentID.
//
// paths: '/api/v1/agents/{agentID}/apps'
// method: GET
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentInfoApps(w http.ResponseWriter, req *http.Request, agentID string) {
logger.Logging(logger.DEBUG, "[AGENT] Get Info Apps")
result, resp, err := sdamAgentController.GetApps(agentID)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentInfoApp handles requests which is used to get information of application
// identified by the given appID.
//
// paths: '/api/v1/agents/{agentID}/apps/{appID}'
// method: GET
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentInfoApp(w http.ResponseWriter, req *http.Request, agentID string, appID string) {
logger.Logging(logger.DEBUG, "[AGENT] Get Info App")
result, resp, err := sdamAgentController.GetApp(agentID, appID)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentUpdateAppInfo handles requests related to updating the application with given yaml in body.
//
// paths: '/api/v1/agents/{agentID}/apps/{appID}'
// method: POST
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentUpdateAppInfo(w http.ResponseWriter, req *http.Request, agentID string, appID string) {
logger.Logging(logger.DEBUG, "[AGENT] Update App Info")
body, err := common.GetBodyFromReq(req)
if err != nil {
common.MakeResponse(w, results.ERROR, nil, err)
return
}
result, resp, err := sdamAgentController.UpdateAppInfo(agentID, appID, body)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentDeleteApp handles requests related to delete application installed on agent
// identified by the given agentID.
//
// paths: '/api/v1/agents/{agentID}/apps/{appID}'
// method: DELETE
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentDeleteApp(w http.ResponseWriter, req *http.Request, agentID string, appID string) {
logger.Logging(logger.DEBUG, "[AGENT] Delete App")
result, resp, err := sdamAgentController.DeleteApp(agentID, appID)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentStartApp handles requests related to start application installed on agent
// identified by the given agentID.
//
// paths: '/api/v1/agents/{agentID}/apps/{appID}/start'
// method: POST
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentStartApp(w http.ResponseWriter, req *http.Request, agentID string, appID string) {
logger.Logging(logger.DEBUG, "[AGENT] Start App")
result, resp, err := sdamAgentController.StartApp(agentID, appID)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentStopApp handles requests related to stop application installed on agent
// identified by the given agentID.
//
// paths: '/api/v1/agents/{agentID}/apps/{appID}/stop'
// method: POST
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentStopApp(w http.ResponseWriter, req *http.Request, agentID string, appID string) {
logger.Logging(logger.DEBUG, "[AGENT] Stop App")
result, resp, err := sdamAgentController.StopApp(agentID, appID)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
// agentUpdateApp handles requests related to updating application installed on agent
// identified by the given agentID.
//
// paths: '/api/v1/agents/{agentID}/apps/{appID}/update'
// method: POST
// responses: if successful, 200 status code will be returned.
func (sdam _SDAMAgentApis) agentUpdateApp(w http.ResponseWriter, req *http.Request, agentID string, appID string) {
logger.Logging(logger.DEBUG, "[AGENT] Update App")
result, resp, err := sdamAgentController.UpdateApp(agentID, appID)
common.MakeResponse(w, result, common.ChangeToJson(resp), err)
}
|
package main
import "fmt"
// SUCCESS string constant for response
const SUCCESS = "success"
// Constant strings for APIs
const (
BASEURL = "http://dummy.restapiexample.com/api/v1/"
GETALLURL = BASEURL + "employees"
GETONEURL = BASEURL + "employee/"
CREATEURL = BASEURL + "create"
DELETEURL = BASEURL + "delete/"
)
// Constant strings for all commands
const (
HELP1 = "help"
HELP2 = "h"
LISTCMD = "list"
CREATECMD = "create"
DELETECMD = "delete"
SHOWCMD = "show"
)
// Constant strings for all flags
const (
HELP3 = "-help"
HELP4 = "-h"
NAMEFLAG = "-name"
SALARYFLAG = "-salary"
AGEFLAG = "-age"
EMPIDFLAG = "-empid"
)
// ErrNotEnoughArguments -> User defined error to explain it to the user tha they have not passed enough arguments // to the command line
var ErrNotEnoughArguments error = fmt.Errorf("Looks like some argument was missed. Please use command `accurics help` to get a better idea")
// ErrWrongArgument -> User defined error to explain it to the user tha they have not passed correct arguments
// to the command line
var ErrWrongArgument error = fmt.Errorf("You may have used wrong argument/flag. Please use command `accurics help` to get a better idea")
// ErrAPICall -> User defined error to explain it to the user that something may have gon wrong with
// the server and that they should try again later
var ErrAPICall error = fmt.Errorf("Something went wrong with the server. Please try again, later")
|
package main
import "fmt"
func main() {
colors := map[string]string{
"red": "#ff0000",
"green": "#dd0000",
"blue": "#cc0000",
}
printMap(colors)
}
func printMap(c map[string]string) {
for _, hex := range c {
fmt.Println(hex)
}
}
|
package payloads
import (
"github.com/gobuffalo/validate/v3"
"github.com/gofrs/uuid"
"github.com/transcom/mymove/pkg/gen/adminmessages"
"github.com/transcom/mymove/pkg/models"
)
// UserModel represents the user
// This does not copy over session IDs to the model
func UserModel(user *adminmessages.UserUpdatePayload, id uuid.UUID) (*models.User, *validate.Errors) {
verrs := validate.NewErrors()
if user == nil {
verrs.Add("User", "payload is nil") // does this make sense
return nil, verrs
}
model := &models.User{
ID: uuid.FromStringOrNil(id.String()),
}
if user.Active != nil {
model.Active = *user.Active
}
return model, nil
}
// WebhookSubscriptionModel converts a webhook subscription payload to a model
func WebhookSubscriptionModel(sub *adminmessages.WebhookSubscription) *models.WebhookSubscription {
model := &models.WebhookSubscription{
ID: uuid.FromStringOrNil(sub.ID.String()),
}
if sub.Severity != nil {
model.Severity = int(*sub.Severity)
}
if sub.CallbackURL != nil {
model.CallbackURL = *sub.CallbackURL
}
if sub.EventKey != nil {
model.EventKey = *sub.EventKey
}
if sub.Status != nil {
model.Status = models.WebhookSubscriptionStatus(*sub.Status)
}
if sub.SubscriberID != nil {
model.SubscriberID = uuid.FromStringOrNil(sub.SubscriberID.String())
}
return model
}
// WebhookSubscriptionModelFromCreate converts a payload for creating a webhook subscription to a model
func WebhookSubscriptionModelFromCreate(sub *adminmessages.CreateWebhookSubscription) *models.WebhookSubscription {
model := &models.WebhookSubscription{
// EventKey and CallbackURL are required fields in the YAML, so we don't have to worry about the potential
// nil dereference errors here:
EventKey: *sub.EventKey,
CallbackURL: *sub.CallbackURL,
SubscriberID: uuid.FromStringOrNil(sub.SubscriberID.String()),
}
if sub.Status != nil {
model.Status = models.WebhookSubscriptionStatus(*sub.Status)
}
return model
}
|
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package mirbft
import (
"bytes"
"fmt"
"math"
pb "github.com/IBM/mirbft/mirbftpb"
"go.uber.org/zap"
)
type stateMachine struct {
myConfig *Config
currentEpoch *epoch
}
func (sm *stateMachine) propose(data []byte) *Actions {
return &Actions{
Preprocess: []Proposal{
{
Source: sm.myConfig.ID,
Data: data,
},
},
}
}
func (sm *stateMachine) step(source NodeID, outerMsg *pb.Msg) *Actions {
switch innerMsg := outerMsg.Type.(type) {
case *pb.Msg_Preprepare:
msg := innerMsg.Preprepare
// TODO check for nil and log oddity
return sm.currentEpoch.Preprepare(source, SeqNo(msg.SeqNo), BucketID(msg.Bucket), msg.Batch)
case *pb.Msg_Prepare:
msg := innerMsg.Prepare
// TODO check for nil and log oddity
return sm.currentEpoch.Prepare(source, SeqNo(msg.SeqNo), BucketID(msg.Bucket), msg.Digest)
case *pb.Msg_Commit:
msg := innerMsg.Commit
// TODO check for nil and log oddity
return sm.currentEpoch.Commit(source, SeqNo(msg.SeqNo), BucketID(msg.Bucket), msg.Digest)
case *pb.Msg_Checkpoint:
msg := innerMsg.Checkpoint
// TODO check for nil and log oddity
return sm.currentEpoch.Checkpoint(source, SeqNo(msg.SeqNo), msg.Value, msg.Attestation)
case *pb.Msg_Forward:
msg := innerMsg.Forward
// TODO check for nil and log oddity
// TODO should we have a separate validate step here? How do we prevent
// forwarded messages with bad data from poisoning our batch?
return &Actions{
Preprocess: []Proposal{
{
Source: uint64(source),
Data: msg.Data,
},
},
}
default:
// TODO mark oddity
return &Actions{}
}
}
func (sm *stateMachine) processResults(results ActionResults) *Actions {
actions := &Actions{}
for i, preprocessResult := range results.Preprocesses {
sm.myConfig.Logger.Debug("applying preprocess result", zap.Int("index", i))
actions.Append(sm.currentEpoch.process(preprocessResult))
}
for i, digestResult := range results.Digests {
sm.myConfig.Logger.Debug("applying digest result", zap.Int("index", i))
actions.Append(sm.currentEpoch.digest(SeqNo(digestResult.Entry.SeqNo), BucketID(digestResult.Entry.BucketID), digestResult.Digest))
}
for i, validateResult := range results.Validations {
sm.myConfig.Logger.Debug("applying validate result", zap.Int("index", i))
actions.Append(sm.currentEpoch.validate(SeqNo(validateResult.Entry.SeqNo), BucketID(validateResult.Entry.BucketID), validateResult.Valid))
}
for i, checkpointResult := range results.Checkpoints {
sm.myConfig.Logger.Debug("applying checkpoint result", zap.Int("index", i))
actions.Append(sm.currentEpoch.checkpointResult(SeqNo(checkpointResult.SeqNo), checkpointResult.Value, checkpointResult.Attestation))
}
return actions
}
func (sm *stateMachine) tick() *Actions {
return sm.currentEpoch.Tick()
}
func (sm *stateMachine) status() *Status {
epochConfig := sm.currentEpoch.epochConfig
nodes := make([]*NodeStatus, len(sm.currentEpoch.epochConfig.nodes))
for i, nodeID := range epochConfig.nodes {
nodes[i] = sm.currentEpoch.nodeMsgs[nodeID].status()
}
buckets := make([]*BucketStatus, len(sm.currentEpoch.buckets))
for i := BucketID(0); i < BucketID(len(sm.currentEpoch.buckets)); i++ {
buckets[int(i)] = sm.currentEpoch.buckets[i].status()
}
checkpoints := []*CheckpointStatus{}
for seqNo := epochConfig.lowWatermark + epochConfig.checkpointInterval; seqNo <= epochConfig.highWatermark; seqNo += epochConfig.checkpointInterval {
checkpoints = append(checkpoints, sm.currentEpoch.checkpointWindows[seqNo].status())
}
return &Status{
LowWatermark: epochConfig.lowWatermark,
HighWatermark: epochConfig.highWatermark,
EpochNumber: epochConfig.number,
Nodes: nodes,
Buckets: buckets,
Checkpoints: checkpoints,
}
}
type Status struct {
LowWatermark SeqNo
HighWatermark SeqNo
EpochNumber uint64
Nodes []*NodeStatus
Buckets []*BucketStatus
Checkpoints []*CheckpointStatus
}
func (s *Status) Pretty() string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("LowWatermark=%d, HighWatermark=%d, Epoch=%d\n\n", s.LowWatermark, s.HighWatermark, s.EpochNumber))
hRule := func() {
for seqNo := s.LowWatermark; seqNo <= s.HighWatermark; seqNo++ {
buffer.WriteString("--")
}
}
for i := len(fmt.Sprintf("%d", s.HighWatermark)); i > 0; i-- {
magnitude := SeqNo(math.Pow10(i - 1))
for seqNo := s.LowWatermark; seqNo <= s.HighWatermark; seqNo++ {
buffer.WriteString(fmt.Sprintf(" %d", seqNo/magnitude%10))
}
buffer.WriteString("\n")
}
for _, nodeStatus := range s.Nodes {
hRule()
buffer.WriteString(fmt.Sprintf("- === Node %d === \n", nodeStatus.ID))
for bucket, bucketStatus := range nodeStatus.BucketStatuses {
for seqNo := s.LowWatermark; seqNo <= s.HighWatermark; seqNo++ {
if seqNo == SeqNo(bucketStatus.LastCheckpoint) {
buffer.WriteString("|X")
continue
}
if seqNo == SeqNo(bucketStatus.LastCommit) {
buffer.WriteString("|C")
continue
}
if seqNo == SeqNo(bucketStatus.LastPrepare) {
if bucketStatus.IsLeader {
buffer.WriteString("|Q")
} else {
buffer.WriteString("|P")
}
continue
}
buffer.WriteString("| ")
}
if bucketStatus.IsLeader {
buffer.WriteString(fmt.Sprintf("| Bucket=%d (Leader)\n", bucket))
} else {
buffer.WriteString(fmt.Sprintf("| Bucket=%d\n", bucket))
}
}
}
hRule()
buffer.WriteString("- === Buckets ===\n")
for _, bucketStatus := range s.Buckets {
for _, state := range bucketStatus.Sequences {
switch state {
case Uninitialized:
buffer.WriteString("| ")
case Preprepared:
buffer.WriteString("|Q")
case Digested:
buffer.WriteString("|D")
case InvalidBatch:
buffer.WriteString("|I")
case Validated:
buffer.WriteString("|V")
case Prepared:
buffer.WriteString("|P")
case Committed:
buffer.WriteString("|C")
}
}
if bucketStatus.Leader {
buffer.WriteString(fmt.Sprintf("| Bucket=%d (LocalLeader)\n", bucketStatus.ID))
} else {
buffer.WriteString(fmt.Sprintf("| Bucket=%d\n", bucketStatus.ID))
}
}
hRule()
buffer.WriteString("- === Checkpoints ===\n")
i := 0
for seqNo := s.LowWatermark; seqNo <= s.HighWatermark; seqNo++ {
checkpoint := s.Checkpoints[i]
if seqNo == SeqNo(checkpoint.SeqNo) {
buffer.WriteString(fmt.Sprintf("|%d", checkpoint.PendingCommits))
i++
continue
}
buffer.WriteString("| ")
}
buffer.WriteString("| Pending Commits\n")
i = 0
for seqNo := s.LowWatermark; seqNo <= s.HighWatermark; seqNo++ {
checkpoint := s.Checkpoints[i]
if seqNo == SeqNo(s.Checkpoints[i].SeqNo) {
switch {
case checkpoint.NetQuorum && !checkpoint.LocalAgreement:
buffer.WriteString("|N")
case checkpoint.NetQuorum && checkpoint.LocalAgreement:
buffer.WriteString("|G")
default:
buffer.WriteString("|P")
}
i++
continue
}
buffer.WriteString("| ")
}
buffer.WriteString("| Status\n")
hRule()
buffer.WriteString("-\n")
return buffer.String()
}
|
package solutions
func removeInvalidParentheses(s string) []string {
var result []string
left, right := 0, 0
for _, value := range s {
if value == '(' {
left++
} else if value == ')' {
if left == 0 {
right++
} else {
left--
}
}
}
removeParentheses(s, 0, left, right, &result)
return result
}
func removeParentheses(s string, start, left, right int, result *[]string) {
if left == 0 && right == 0 {
if isValidParentheses(s) {
*result = append(*result, s)
}
return
}
for i := start; i < len(s); i++ {
if i != start && s[i] == s[i - 1] {
continue
}
if s[i] == ')' && right > 0 {
current := s
current = current[:i] + current[i + 1:]
removeParentheses(current, i, left, right - 1, result)
} else if s[i] == '(' && left > 0 {
current := s
current = current[:i] + current[i + 1:]
removeParentheses(current, i, left - 1, right, result)
}
}
}
func isValidParentheses(s string) bool {
count := 0
for _, value := range s {
if value == '(' {
count++
}
if value == ')' {
count--
}
if count < 0 {
return false
}
}
return count == 0
}
|
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/cheggaaa/pb"
)
// a compound word
type Compound struct {
word string
originalWords []string
}
func (c *Compound) String() string {
return fmt.Sprintf("%s {%v}", c.word, c.originalWords)
}
// a list of compound words, and the index of the longest one
type CompoundList struct {
longestIdx int
compoundWords []Compound
}
func (r *CompoundList) GetLongest() Compound {
return r.compoundWords[r.longestIdx]
}
// from a given list of words, find all the words that are a compound of at least
// least two other words in the list, and determine which one is the longest.
func FindCompoundWords(words []string, includeProgressBar bool) (result *CompoundList) {
result = &CompoundList{0, make([]Compound, 0, 128)}
// this slice stores words that have appeared as sub-words before
likelySubWords := make([]string, 0, 128)
var bar *pb.ProgressBar
if includeProgressBar {
bar = pb.StartNew(len(words))
}
for _, currentWord := range words {
if len(currentWord) == 0 {
continue
}
subWords := make([]string, 0, 2)
w := currentWord
// first check the list of words that have already appeared as sub-words
for _, subWord := range likelySubWords {
if currentWord != subWord && strings.Contains(w, subWord) {
w = strings.Replace(w, subWord, "", 1)
subWords = append(subWords, subWord)
}
if len(subWords) >= 2 {
break
}
}
if len(subWords) < 2 {
// fall back to searching the full list
for _, subWord := range words {
if currentWord != subWord && strings.Contains(w, subWord) {
w = strings.Replace(w, subWord, "", 1)
subWords = append(subWords, subWord)
likelySubWords = append(likelySubWords, subWord)
}
if len(subWords) >= 2 {
break
}
}
}
if len(subWords) >= 2 {
c := Compound{currentWord, subWords}
result.compoundWords = append(result.compoundWords, c)
if len(currentWord) > len(result.GetLongest().word) {
result.longestIdx = len(result.compoundWords) - 1
}
}
if includeProgressBar {
bar.Increment()
}
}
if includeProgressBar {
bar.FinishPrint(fmt.Sprintf("Processed %d words.", len(words)))
}
return result
}
// take a string and transform it into a list of words with whitespace trimmed
// and any empty elements removed
func wordsFromString(str string) (words []string) {
words = strings.Split(str, "\n")
toDelete := make([]int, 0, 8)
for i, word := range words {
word = strings.TrimSpace(word)
if len(word) == 0 {
toDelete = append(toDelete, i)
}
}
for _, target := range toDelete {
words = append(words[:target], words[target+1:]...)
}
return words
}
func main() {
var inputFile string
flag.StringVar(&inputFile, "file", "", "the file to parse")
var includeProgressBar bool
flag.BoolVar(&includeProgressBar, "progress", false, "show progress bar")
flag.Parse()
if len(inputFile) < 1 {
flag.PrintDefaults()
os.Exit(1)
}
data, err := ioutil.ReadFile(inputFile)
if err != nil {
panic(err)
}
words := wordsFromString(string(data))
compounds := FindCompoundWords(words, includeProgressBar)
fmt.Println("Longest word was", compounds.GetLongest(), "with length", len(compounds.GetLongest().word))
}
|
package main
import "fmt"
//func main() {
// if true {
// defer fmt.Printf("a")
// }else {
// defer fmt.Printf("b")
// }
//
// fmt.Printf("c")
//}
const (
a = iota
b = iota
)
const (
name = "name" //iota已经开始计数,const每一行iota计数一次
c = iota //const关键词出现就会被重置
d = iota
)
func main() {
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package guestos provides VM guest OS related primitives.
package guestos
import (
"context"
"chromiumos/tast/common/testexec"
"chromiumos/tast/local/vm"
)
// CrostiniGuestOS is an implementation of IGuestOS interface for Crostini
type CrostiniGuestOS struct {
VMInstance *vm.Container
}
// Command returns a testexec.Cmd with a vsh command that will run in the guest.
func (c CrostiniGuestOS) Command(ctx context.Context, vshArgs ...string) *testexec.Cmd {
return c.VMInstance.Command(ctx, vshArgs...)
}
// GetBinPath returns the recommended binaries path in the guest OS.
// The trace_replay binary will be uploaded into this directory.
func (c CrostiniGuestOS) GetBinPath() string {
return "/tmp/trace_replay/bin"
}
// GetTempPath returns the recommended temp path in the guest OS. This directory
// can be used to store downloaded artifacts and other temp files.
func (c CrostiniGuestOS) GetTempPath() string {
return "/tmp/trace_replay"
}
|
package extension
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/tilt-dev/tilt/internal/analytics"
"github.com/tilt-dev/tilt/internal/controllers/apicmp"
"github.com/tilt-dev/tilt/internal/controllers/indexer"
"github.com/tilt-dev/tilt/internal/ospath"
"github.com/tilt-dev/tilt/pkg/apis/core/v1alpha1"
"github.com/tilt-dev/tilt/pkg/logger"
)
type Reconciler struct {
ctrlClient ctrlclient.Client
indexer *indexer.Indexer
mu sync.Mutex
analytics *analytics.TiltAnalytics
}
func (r *Reconciler) CreateBuilder(mgr ctrl.Manager) (*builder.Builder, error) {
b := ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.Extension{}).
Watches(&v1alpha1.ExtensionRepo{},
handler.EnqueueRequestsFromMapFunc(r.indexer.Enqueue))
return b, nil
}
func NewReconciler(ctrlClient ctrlclient.Client, scheme *runtime.Scheme, analytics *analytics.TiltAnalytics) *Reconciler {
return &Reconciler{
ctrlClient: ctrlClient,
indexer: indexer.NewIndexer(scheme, indexExtension),
analytics: analytics,
}
}
// Verifies extension paths.
func (r *Reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
r.mu.Lock()
defer r.mu.Unlock()
nn := request.NamespacedName
var ext v1alpha1.Extension
err := r.ctrlClient.Get(ctx, nn, &ext)
r.indexer.OnReconcile(nn, &ext)
if err != nil && !apierrors.IsNotFound(err) {
return ctrl.Result{}, err
}
// Cleanup tiltfile loads if an extension is deleted.
if apierrors.IsNotFound(err) || !ext.ObjectMeta.DeletionTimestamp.IsZero() {
err := r.manageOwnedTiltfile(ctx, nn, nil)
if err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
var repo v1alpha1.ExtensionRepo
err = r.ctrlClient.Get(ctx, types.NamespacedName{Name: ext.Spec.RepoName}, &repo)
if err != nil && !apierrors.IsNotFound(err) {
return ctrl.Result{}, err
}
newStatus := r.apply(&ext, &repo)
update, changed, err := r.maybeUpdateStatus(ctx, &ext, newStatus)
if err != nil {
return ctrl.Result{}, err
}
// Always manage the child objects, even if the user-visible status didn't change,
// because there might be internal state we need to propagate.
err = r.manageOwnedTiltfile(ctx, types.NamespacedName{Name: ext.Name}, update)
if err != nil {
return ctrl.Result{}, err
}
if changed && update.Status.Error == "" {
repoType := "http"
if strings.HasPrefix(repo.Spec.URL, "file://") {
repoType = "file"
}
r.analytics.Incr("api.extension.load", map[string]string{
"ext_path": ext.Spec.RepoPath,
"repo_url_hash": analytics.HashSHA1(repo.Spec.URL),
"repo_type": repoType,
})
}
return ctrl.Result{}, nil
}
// Reconciles the extension without reading or writing from the API server.
// Returns the resolved status.
// Exposed for outside callers.
func (r *Reconciler) ForceApply(ext *v1alpha1.Extension, repo *v1alpha1.ExtensionRepo) v1alpha1.ExtensionStatus {
r.mu.Lock()
defer r.mu.Unlock()
return r.apply(ext, repo)
}
func (r *Reconciler) apply(ext *v1alpha1.Extension, repo *v1alpha1.ExtensionRepo) v1alpha1.ExtensionStatus {
if repo.Name == "" {
return v1alpha1.ExtensionStatus{Error: fmt.Sprintf("extension repo not found: %s", ext.Spec.RepoName)}
}
if repo.Status.Path == "" {
return v1alpha1.ExtensionStatus{Error: fmt.Sprintf("extension repo not loaded: %s", ext.Spec.RepoName)}
}
absPath := filepath.Join(repo.Status.Path, ext.Spec.RepoPath, "Tiltfile")
// Make sure the user isn't trying to use path tricks to "escape" the repo.
if !ospath.IsChild(repo.Status.Path, absPath) {
return v1alpha1.ExtensionStatus{Error: fmt.Sprintf("invalid repo path: %s", ext.Spec.RepoPath)}
}
info, err := os.Stat(absPath)
if err != nil || !info.Mode().IsRegular() {
return v1alpha1.ExtensionStatus{Error: fmt.Sprintf("no extension tiltfile found at %s", absPath)}
}
return v1alpha1.ExtensionStatus{Path: absPath}
}
// Update the status. Returns true if the status changed.
func (r *Reconciler) maybeUpdateStatus(ctx context.Context, obj *v1alpha1.Extension, newStatus v1alpha1.ExtensionStatus) (*v1alpha1.Extension, bool, error) {
if apicmp.DeepEqual(obj.Status, newStatus) {
return obj, false, nil
}
oldError := obj.Status.Error
newError := newStatus.Error
update := obj.DeepCopy()
update.Status = *(newStatus.DeepCopy())
err := r.ctrlClient.Status().Update(ctx, update)
if err != nil {
return obj, false, err
}
isLoggedError := newError != "" &&
!strings.HasPrefix(newError, "extension repo not loaded") &&
!strings.HasPrefix(newError, "extension repo not found")
if isLoggedError && oldError != newError {
logger.Get(ctx).Errorf("extension %s: %s", obj.Name, newError)
}
return update, true, err
}
// Find all the objects we need to watch based on the extension spec.
func indexExtension(obj client.Object) []indexer.Key {
result := []indexer.Key{}
ext := obj.(*v1alpha1.Extension)
if ext.Spec.RepoName != "" {
repoGVK := v1alpha1.SchemeGroupVersion.WithKind("ExtensionRepo")
result = append(result, indexer.Key{
Name: types.NamespacedName{Name: ext.Spec.RepoName},
GVK: repoGVK,
})
}
return result
}
|
package main
import (
"flag"
"time"
"github.com/gin-gonic/gin"
"github.com/new-adventure-areolite/grpc-app-server/pd/auth"
"github.com/new-adventure-areolite/grpc-app-server/pd/fight"
auth_middle_ware "github.com/new-adventure-areolite/grpc-app-server/pkg/auth"
"github.com/new-adventure-areolite/grpc-app-server/pkg/handler"
"github.com/new-adventure-areolite/grpc-app-server/pkg/istio"
"github.com/new-adventure-areolite/grpc-app-server/pkg/jaeger_service"
"github.com/new-adventure-areolite/grpc-app-server/pkg/middleware/jaegerMiddleware"
"google.golang.org/grpc"
"k8s.io/klog"
)
var (
port string
addr string
authServerAddr string
tlsCert string
tlsKey string
)
func init() {
flag.StringVar(&port, "port", "8000", "listen port")
flag.StringVar(&addr, "addr", "127.0.0.1:8001", "fight svc addr")
flag.StringVar(&authServerAddr, "auth-server-addr", "127.0.0.1:6666", "auth svc addr")
flag.StringVar(&tlsCert, "tls-cert", "", "tls cert")
flag.StringVar(&tlsKey, "tls-key", "", "tls key")
}
func main() {
flag.Parse()
proxy := istio.New(10, 10*time.Second, 30*time.Second)
if err := proxy.Wait(); err != nil {
klog.Fatal(err)
}
defer func() {
if err := proxy.Close(); err != nil {
klog.Error(err)
}
}()
gin.DisableConsoleColor()
r := gin.Default()
gin.SetMode(gin.DebugMode)
// new jaeger tracer
tracer, _, err := jaeger_service.NewJaegerTracer("app-server", "jaeger-collector.istio-system.svc.cluster.local:14268")
if err != nil {
klog.Fatal(err)
}
// add openTracing middleware
r.Use(jaegerMiddleware.OpenTracingMiddleware())
// r.Use(jaegerMiddleware.AfterOpenTracingMiddleware(tracer))
// trace on grpc client
dialOpts := []grpc.DialOption{grpc.WithInsecure()}
if tracer != nil {
dialOpts = append(dialOpts, grpc.WithUnaryInterceptor(jaeger_service.ClientInterceptor(tracer, "call fight gRPC client")))
} else {
klog.Fatal("tracer is nil, exist")
}
// create fight connection
conn, err := grpc.Dial(addr, dialOpts...)
if err != nil {
klog.Fatal(err)
}
fightSvcClient := fight.NewFightSvcClient(conn)
// create auth connection
authConn, err := grpc.Dial(authServerAddr, grpc.WithInsecure(), grpc.WithUnaryInterceptor(jaeger_service.ClientInterceptor(tracer, "call auth gRPC client")))
if err != nil {
klog.Fatal(err)
}
authSvcClient := auth.NewAuthServiceClient(authConn)
authClient := auth_middle_ware.New(authSvcClient)
r.Use(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT")
c.Writer.Header().Set("Access-Control-Allow-Headers",
"Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Authorization, Access-Control-Request-Method, Access-Control-Request-Headers")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(200)
}
c.Next()
})
group := r.Group("/", auth_middle_ware.AuthMiddleWare(authClient))
group.GET("/heros", handler.GetAllHeros(fightSvcClient))
group.GET("/session", handler.LoadSession(fightSvcClient))
group.PUT("/session", handler.SelectHero(fightSvcClient))
group.PUT("/session/fight", handler.Fight(fightSvcClient))
group.POST("/session/archive", handler.Archive(fightSvcClient))
group.POST("/session/level", handler.Level(fightSvcClient))
group.POST("/session/quit", handler.Quit(fightSvcClient))
group.POST("/session/clear", handler.ClearSession(fightSvcClient))
go func() {
if err := handler.InitTop10Client(fightSvcClient); err != nil {
klog.Warning(err)
}
}()
r.GET("/top10", handler.Top10())
// Admin rest api
go func() {
if err := handler.InitAdminClient(fightSvcClient); err != nil {
klog.Warning(err)
}
}()
adminGroup := r.Group("/admin", auth_middle_ware.AdminAuthMiddleWare(authClient))
adminGroup.POST("/hero", handler.CreateHero())
adminGroup.PUT("/hero", handler.AdjustHero())
if tlsCert != "" && tlsKey != "" {
r.RunTLS(":"+port, tlsCert, tlsKey)
} else {
r.Run(":" + port)
}
}
|
package leetcode
func singleNonDuplicate(nums []int) int {
l, m, r := 0, 0, len(nums)-1
for l < r {
m = (r-l)/2 + l
if m%2 == 1 {
m--
}
if nums[m] == nums[m+1] {
l = m + 2
} else {
r = m
}
}
return nums[r]
}
func singleNonDuplicate1(nums []int) int {
low, high := 0, len(nums)-1
for low <= high {
mid := low + (high-low)/2
if mid-1 >= 0 && nums[mid] == nums[mid-1] {
mid--
} else if mid+1 < len(nums) && nums[mid] == nums[mid+1] {
} else {
return nums[mid]
}
if (mid-low)%2 == 1 {
high = mid - 1
} else {
low = mid + 2
}
}
return -1
}
func singleNonDuplicate3(nums []int) int {
n := len(nums)
for i := 0; i < n-1; i = i + 2 {
if nums[i] != nums[i+1] {
return nums[i]
}
}
return nums[n-1]
}
|
package writer
import (
"bytes"
"io/ioutil"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestWriteTrigger(t *testing.T) {
buf := new(bytes.Buffer)
if err := WriteTrigger("./testdata/spec-full.yaml", buf); err != nil {
t.Fatalf("error from 'WriteTrigger': %v", err)
}
got := buf.Bytes()
path := "./testdata/config.yaml"
want, err := ioutil.ReadFile(path)
if err != nil {
t.Fatalf("fail to read file %s: %v", path, err)
}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("WriteTrigger mismatch (-want +got):\n %s", diff)
}
}
func TestWritePipelineRun(t *testing.T) {
buf := new(bytes.Buffer)
if err := WritePipelineRun("./testdata/spec-full.yaml", buf); err != nil {
t.Fatalf("error from 'WritePipelineRun': %v", err)
}
got := buf.Bytes()
path := "./testdata/run.yaml"
want, err := ioutil.ReadFile(path)
if err != nil {
t.Fatalf("fail to read file %s: %v", path, err)
}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("WritePipelineRun mismatch (-want +got):\n %s", diff)
}
}
|
// MoreXmlParser project main.go
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
)
const url = "https://www.washingtonpost.com/news-technology-sitemap.xml"
type News struct {
Locations []string `xml:"url>loc"`
Titles []string `xml:"url>news>title"`
Keywords []string `xml:"url>news>keywords"`
}
type NewsMap struct {
Keyword string
Location string
}
func main() {
resp, _ := http.Get(url)
bContent, _ := ioutil.ReadAll(resp.Body)
// content := string(bContent)
// fmt.Println(content)
var news News
xml.Unmarshal(bContent, &news)
fmt.Println(news)
for i := 0; i < len(news.Locations); i++ {
fmt.Println(news.Locations[i], news.Titles[i], news.Keywords[i])
}
newsMap := make(map[string]NewsMap)
for idx, _ := range news.Titles {
newsMap[news.Titles[idx]] = NewsMap{news.Keywords[idx], news.Locations[idx]}
}
for k, v := range newsMap {
fmt.Println("Title: ", k)
fmt.Println("Keyword: ", v.Keyword)
fmt.Println("Location: ", v.Location)
fmt.Println("-------------------")
}
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
var (
httpClient = http.Client{
Timeout: time.Second * 3,
}
)
func GetCurrentWeatherForCity(cityName string) map[string]interface{} {
configuration := GetDevelopmentConfiguration()
url := fmt.Sprintf("%s/data/2.5/weather?q=%s&APPID=%s", configuration.OpenWeather.Url, cityName, configuration.OpenWeather.Key)
openWeatherResponse, clientError := httpClient.Get(url)
if clientError != nil {
log.Fatal(clientError)
}
var openWeatherResponseDecoded map[string]interface{}
json.NewDecoder(openWeatherResponse.Body).Decode(&openWeatherResponseDecoded)
return openWeatherResponseDecoded
}
func GetCurrentWeatherForAllCitiesOfCountryInJson(countryName string) []map[string]interface{} {
configuration := GetDevelopmentConfiguration()
cities := getCitiesFromCountry(countryName)
citiesToBeUsed := cities[:10]
response := make([]map[string]interface{}, 0)
for _, city := range citiesToBeUsed {
url := fmt.Sprintf("%s/data/2.5/weather?q=%s&APPID=%s", configuration.OpenWeather.Url, city.Name, configuration.OpenWeather.Key)
openWeatherReponse, _ := httpClient.Get(url)
var responseDecoded map[string]interface{}
json.NewDecoder(openWeatherReponse.Body).Decode(&responseDecoded)
response = append(response, responseDecoded)
}
return response
}
func GetCurrentWeatherForCitysInCountry(country string, mainChannel chan CurrentWeatherData) {
defer close(mainChannel)
configuration := GetDevelopmentConfiguration()
cities := getCitiesFromCountry(country)
citiesToBeUsed := cities[:50]
var requestChannels = []chan CurrentWeatherData{}
for i, city := range citiesToBeUsed {
requestChannels = append(requestChannels, make(chan CurrentWeatherData))
go GetCurrentWeatherDataForCityRoutine(&configuration, city, requestChannels[i])
}
for i := range requestChannels {
for channel := range requestChannels[i] {
mainChannel <- channel
}
}
}
func GetCurrentWeatherDataForCityRoutine(configuration *Config, city City, openWeatherRequestChannel chan CurrentWeatherData) {
defer close(openWeatherRequestChannel)
url := fmt.Sprintf("%s/data/2.5/weather?q=%s&APPID=%s", configuration.OpenWeather.Url, city.Name, configuration.OpenWeather.Key)
openWeatherResponse, clientError := httpClient.Get(url)
if clientError != nil {
log.Fatal(clientError)
}
var openWeatherResponseDecoded map[string]interface{}
json.NewDecoder(openWeatherResponse.Body).Decode(&openWeatherResponseDecoded)
currentWeatherData := CurrentWeatherDataOf(openWeatherResponseDecoded)
openWeatherRequestChannel <- currentWeatherData
}
func getCitiesFromCountry(country string) (citiesResponse []City) {
cities := loadCitiesFromJson()
for _, city := range cities {
if city.Country == country {
citiesResponse = append(citiesResponse, city)
}
}
return
}
func loadCitiesFromJson() (cities []City) {
file, err := ioutil.ReadFile("./city.list.json")
if err != nil {
log.Fatal("File not found")
return nil
}
err = json.Unmarshal([]byte(file), &cities)
if err != nil {
log.Fatal("Fail to unmarshall")
return nil
}
return
}
|
package main
import "strings"
// match("abba", "Beijing Hangzhou Hangzhou Beijing") -- true
// match("aabb", "Beijing Hangzhou Hangzhou Beijing") -- false
// match("baab", "Beijing Hangzhou Hangzhou Beijing") -- true
func simplePatternMatch(pattern, s string) bool {
m := make(map[byte]string)
strs := strings.Split(s, " ")
if len(pattern) != len(strs) {
return false
}
for i := range pattern {
if str, ok := m[pattern[i]]; ok {
if str != strs[i] {
return false
}
} else {
m[pattern[i]] = strs[i]
}
}
return true
}
|
package main
import (
"context"
"time"
)
const timeout = time.Second * 2
func main() {
// TODO: код писать здесь
}
func realMain(ctx context.Context, num int) {
// TODO: код писать здесь
}
// TODO: код писать здесь
|
/**********************************************************************
* @Author: Eiger (201820114847@mail.scut.edu.cn)
* @Date: 2020/4/23 8:55
* @Description: The file is for
***********************************************************************/
package main
import (
"fmt"
"strings"
)
const mdFormat1 = `
## %s
**作者:** %s
**摘要:** %s
**关键词:** %s
**引用格式:** %s
**全文链接:** <%s>
`
const mdFormat2 = `
## %s
**作者** %s
**摘要** %s
**关键词** %s
**引用格式** %s
**全文链接** <%s>
`
type Paper struct {
AbstractUrl string
Title string
Authors []string
Abstract string
Keywords string
Position string // 第几卷第几期
Reference string // 引用格式按规则拼接
PdfUrl string
}
func (p *Paper) MDString() string {
// 检查引用格式是否设置
if p.Reference == "" {
// 拼接引用格式
p.setReference()
}
return fmt.Sprintf(mdFormat2, p.Title, strings.Join(p.Authors, ", "), p.Abstract, p.Keywords, p.Reference, p.PdfUrl)
}
// 设置标题
func (p *Paper) setTitle(content string) {
matched := titleRegexp.FindAllStringSubmatch(content, -1)
if len(matched) > 0 {
p.Title = matched[0][1]
}
}
// 设置作者
func (p *Paper) setAuthors(content string) {
matched := authorRegexp.FindAllStringSubmatch(content, -1)
authors := make([]string, 0)
if len(matched) > 0 {
for _, v := range matched {
// 对于中文名,希望把中文名间的空格去掉,而英文名的空格则保留
// 中文名一般就全是中文,英文名则是英文字母
// 这里简单按照第一个rune去判断是否是中英字符
name := []rune(v[1])
if (name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z') {
// 英文名不作处理
authors = append(authors, v[1])
} else { // 视作中文名,要去除空格
tmp := strings.Split(v[1], " ")
authors = append(authors, strings.Join(tmp, ""))
}
}
}
p.Authors = authors
}
// 设置摘要
func (p *Paper) setAbstract(content string) {
matched := abstractRegexp.FindAllStringSubmatch(content, -1)
if len(matched) == 1 {
p.Abstract = CheckSpaces(Period2Dot(DBC2SBC(matched[0][1])))
}
}
// 设置关键词
func (p *Paper) setKeywords(content string) {
matched := keywordsRegexp.FindAllStringSubmatch(content, -1)
if len(matched) == 1 {
p.Keywords = matched[0][1]
}
}
// 设置pdf链接
func (p *Paper) setPDFLink(content string) {
matched := pdflinkRegexp.FindAllStringSubmatch(content, -1)
if len(matched) == 1 {
p.PdfUrl = pdfPagePrefix + matched[0][1]
}
}
// 设置引用格式
func (p *Paper) setPosition(content string) {
matched := positionRegexp.FindAllStringSubmatch(content, -1)
if len(matched) == 1 {
p.Position = matched[0][1]
}
}
// 设置引用格式
func (p *Paper) setReference() {
var authors string
if len(p.Authors) > 3 {
authors = strings.Join(p.Authors[:3], ", ") + ", 等. "
} else {
authors = strings.Join(p.Authors, ", ") + ". "
}
p.Reference = authors + p.Title + ". " + journal + ", " + p.Position
}
|
package rewrite
import (
"bytes"
"go/ast"
"go/format"
"go/parser"
"go/token"
)
import "strconv"
import "hw2/expr"
import "hw2/simplify"
// rewriteCalls should modify the passed AST
func rewriteCalls(node ast.Node) {
//TODO Write the rewriteCalls function
ast.Inspect(node, func (node ast.Node) bool {
switch v := node.(type) {
//Find CallExpr
case *ast.CallExpr:
switch fun := v.Fun.(type) {
//Find the Selector Expr since expr.ParseAndEval
case *ast.SelectorExpr:
if fun.Sel.Name == "ParseAndEval" {
//fmt.Println(len(v.Args))
//Make sure the CallExpr has the two arguments
if len(v.Args) != 2 {
return false
}
//v.Args[0] is first argument
lit, ok := v.Args[0].(*ast.BasicLit)
//IF first argument is a BasicLit and is a String Literal
if ok && lit.Kind == token.STRING {
//lit = type of BasicLit
u := lit.Value
//Unquote the arguments value
u, _ = strconv.Unquote(u)
// a is now an expr after the parse
a, error := expr.Parse(u)
// if no errors in the parsing
if error == nil {
//Simplify a using the simplify created earlier
a = simplify.Simplify(a, expr.Env{})
//a is equal to the resulting expr.Expr
// Need to change a from expr.Expr back to a string
c := expr.Format(a)
// c is now the string
//Put Quotes back onto the string
c = strconv.Quote(c)
//Change the argument value to the simplified string
lit.Value = c
//return true since we successfully changed the argument
return true
}
return false
}
}
}
}
return true
})
}
func SimplifyParseAndEval(src string) string {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "src.go", src, 0)
if err != nil {
panic(err)
}
rewriteCalls(f)
var buf bytes.Buffer
format.Node(&buf, fset, f)
return buf.String()
}
|
package config
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
)
// 日志文件
type LogConfig struct {
Access string `json:"access"`
Error string `json:"error"`
}
type HttpConfig struct {
Listen string `json:"listen"`
Secret string `json:"secret"`
}
type RpcConfig struct {
Listen string `json:"listen"`
}
type MysqlConfig struct {
Addr string `json:"addr"`
Idle int `json:"idle"`
Max int `json:"max"`
ShowSQL bool `json:"sql"`
}
type TimeoutConfig struct {
Conn int64 `json:"conn"`
Read int64 `json:"read"`
Write int64 `json:"write"`
}
type RedisConfig struct {
Addr string `json:"addr"`
Idle int `json:"idle"`
Max int `json:"max"`
Timeout *TimeoutConfig `json:"timeout"`
}
type ConfigMsql struct {
Addr string `json:"addr"`
}
type Limit struct {
TypeNub int64 `json:"typenub"` // 限制用户可以创建的主分类数量
Mode int64 `json:"mode"` // 限制用户可以创建的模型的数量
}
type UpdateRate struct {
Status bool `json:"status"` // 是否开启限制
RateTime int64 `json:"rate_time"` // 频率,默认是秒
}
type GlobalConfig struct {
Debug bool `json:"debug"` //
Init bool `json:"init"` //是否初始化,
Version float64 `json:"version"`
UpdateRate *UpdateRate `json:"update_rate"` // 更新频率,按分钟
Request string `json:"request"` // 是否使用https
Salt string `json:"salt"` // 验证key
Log *LogConfig `json:"log"`
LimitNub *Limit `json:"limit"`
Http *HttpConfig `json:"http"`
Rpc *RpcConfig `json:"rpc"`
Mysql *MysqlConfig `json:"mysql"`
ConfMysql *ConfigMsql `json:"confmysql"`
Redis *RedisConfig `json:"redis"`
Backend map[string][]string `json:"backend"`
}
var (
File string
G *GlobalConfig
)
func Parse(cfg string) error {
if cfg == "" {
return fmt.Errorf("无配置文件,请使用 -c 配置文件 启动")
}
if !fileExists(cfg) {
return fmt.Errorf("配置文件 %s 不存在", cfg)
}
File = cfg
configContent, err := ioutil.ReadFile(cfg)
if err != nil {
return fmt.Errorf("read configuration file %s fail %s", cfg, err.Error())
}
var c GlobalConfig
err = json.Unmarshal(configContent, &c)
if err != nil {
return fmt.Errorf("parse configuration file %s fail %s", cfg, err.Error())
}
G = &c
log.Println("load configuration file", cfg, "successfully")
return nil
}
func fileExists(fp string) bool {
_, err := os.Stat(fp)
return err == nil || os.IsExist(err)
}
|
package internal
import (
"github.com/ionous/sashimi/util/ident"
)
//
// PendingInstance records all of the classes which use an instance
//
type PendingInstance struct {
id ident.Id
name string
longName string
classes ClassReferences
}
|
package day9
import (
"log"
"regexp"
"sort"
"strconv"
)
type Place struct {
Name string
Distances map[string]int
}
type Places map[string]*Place
func (ps Places) ParseLines(lines []string) {
rx := regexp.MustCompile(`^(\w+) to (\w+) = (\d+)$`)
for i, line := range lines {
result := rx.FindStringSubmatch(line)
if result == nil {
log.Fatal("Unable to parse line %d: %s", i, line)
}
names := result[1:3]
sort.Strings(names)
dist, err := strconv.Atoi(result[3])
if err != nil {
log.Fatal("Unable to parse distance on line %d: %s", i, result[3])
}
ps.add(names, dist)
}
}
func (ps Places) add(names []string, dist int) (*Place, *Place) {
p1 := ps.add1(names[0], names[1], dist)
p2 := ps.add1(names[1], names[0], dist)
return p1, p2
}
func (ps Places) add1(local, remote string, dist int) *Place {
p, ok := ps[local]
if !ok {
p = &Place{Name: local}
p.Distances = make(map[string]int)
ps[local] = p
}
p.Distances[remote] = dist
return p
}
func (ps Places) names() []string {
var places []string
for name, _ := range ps {
places = append(places, name)
}
sort.Strings(places)
return places
}
|
package main
import (
"fmt"
"github.com/codegangsta/cli"
"io/ioutil"
"log"
"os"
"os/exec"
"regexp"
)
var commandInit = cli.Command{
Name: "init",
Usage: "copy template directory and run \"lime.sh\" in template directory",
Description: "",
Action: doInit,
}
func doInit(c *cli.Context) {
home := os.Getenv("HOME")
switch {
case len(c.Args()) == 1:
source := home + "/.lime/init-templates/" + c.Args()[0]
if shell(c.Args()[0]) {
copy744(source, "./"+c.Args()[0])
out, err := exec.Command("./" + c.Args()[0]).Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", out)
removeFile(c.Args()[0])
} else {
files, _ := ioutil.ReadDir(source)
for _, f := range files {
if f.Name() == "lime.sh" {
copy744(source+"/"+f.Name(), "./lime.sh")
} else {
copyFile(source + "/" + f.Name())
}
}
if exist("lime.sh") {
out, err := exec.Command("./lime.sh").Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", out)
removeFile("lime.sh")
}
}
case len(c.Args()) > 1:
println("Error: Unknown command", c.Args()[0])
default:
doHelp(c)
}
}
func shell(name string) bool {
if m, _ := regexp.MatchString(".sh$", name); !m {
return false
}
return true
}
func copyFile(src string) {
cmd := exec.Command("cp", "-r", src, ".")
_, err := cmd.Output()
if err != nil {
println(err.Error())
return
}
}
func copy744(src string, dst string) {
data, err := ioutil.ReadFile(src)
checkErr(err)
err = ioutil.WriteFile(dst, data, 0744)
checkErr(err)
}
func checkErr(err error) {
if err != nil {
log.Fatal(err)
}
}
func exist(filename string) bool {
_, err := os.Stat(filename)
return err == nil
}
func removeFile(file string) {
cmd := exec.Command("rm", "-f", "./lime.sh")
_, err := cmd.Output()
if err != nil {
println(err.Error())
return
}
}
|
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/johnantonusmaximus/grpc-golang/long_greet_stream/greetstreampb"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("Connection to GRPC failed: %v", err)
}
defer conn.Close()
c := greetstreampb.NewGreetServiceClient(conn)
doClientStream(c)
}
func doClientStream(c greetstreampb.GreetServiceClient) {
fmt.Println("Starting to do a client streaming RPC...")
ctx := context.Background()
requests := []*greetstreampb.LongGreetRequest{
&greetstreampb.LongGreetRequest{
Greeting: &greetstreampb.Greeting{
FirstName: "Stephanie",
},
},
&greetstreampb.LongGreetRequest{
Greeting: &greetstreampb.Greeting{
FirstName: "Mark",
},
},
&greetstreampb.LongGreetRequest{
Greeting: &greetstreampb.Greeting{
FirstName: "Peter",
},
},
&greetstreampb.LongGreetRequest{
Greeting: &greetstreampb.Greeting{
FirstName: "Harold",
},
},
&greetstreampb.LongGreetRequest{
Greeting: &greetstreampb.Greeting{
FirstName: "John",
},
},
&greetstreampb.LongGreetRequest{
Greeting: &greetstreampb.Greeting{
FirstName: "Chris",
},
},
}
stream, err := c.LongGreetStream(ctx)
if err != nil {
log.Fatalf("Error while calling long greet: %v\n", err)
}
for _, req := range requests {
stream.Send(req)
time.Sleep(time.Second * 1)
}
resp, err := stream.CloseAndRecv()
if err != nil {
log.Fatalf("Error while receiving response: %v\n", err)
}
log.Printf("Response: %v\n", resp)
}
|
package main
import (
"flag"
"fmt"
"log"
"net/http"
)
func main() {
var (
addr = flag.String("addr", "0.0.0.0:6789", "listening address")
dir = flag.String("dir", ".", "the folder to serve")
link = flag.String("link", "123456789", "the access link")
)
flag.Parse()
*link = fmt.Sprintf("/%s/", *link)
fs := http.FileServer(http.Dir(*dir))
http.Handle(*link, http.StripPrefix(*link, fs))
log.Printf("serving %s on %s%s", *dir, *addr, *link)
log.Fatalln(http.ListenAndServe(*addr, nil))
}
|
// Copyright 2019 - 2022 The Samply Community
//
// 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 fhir
import "encoding/json"
// THIS FILE IS GENERATED BY https://github.com/samply/golang-fhir-models
// PLEASE DO NOT EDIT BY HAND
// MedicinalProductAuthorization is documented here http://hl7.org/fhir/StructureDefinition/MedicinalProductAuthorization
type MedicinalProductAuthorization struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Meta *Meta `bson:"meta,omitempty" json:"meta,omitempty"`
ImplicitRules *string `bson:"implicitRules,omitempty" json:"implicitRules,omitempty"`
Language *string `bson:"language,omitempty" json:"language,omitempty"`
Text *Narrative `bson:"text,omitempty" json:"text,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Identifier []Identifier `bson:"identifier,omitempty" json:"identifier,omitempty"`
Subject *Reference `bson:"subject,omitempty" json:"subject,omitempty"`
Country []CodeableConcept `bson:"country,omitempty" json:"country,omitempty"`
Jurisdiction []CodeableConcept `bson:"jurisdiction,omitempty" json:"jurisdiction,omitempty"`
Status *CodeableConcept `bson:"status,omitempty" json:"status,omitempty"`
StatusDate *string `bson:"statusDate,omitempty" json:"statusDate,omitempty"`
RestoreDate *string `bson:"restoreDate,omitempty" json:"restoreDate,omitempty"`
ValidityPeriod *Period `bson:"validityPeriod,omitempty" json:"validityPeriod,omitempty"`
DataExclusivityPeriod *Period `bson:"dataExclusivityPeriod,omitempty" json:"dataExclusivityPeriod,omitempty"`
DateOfFirstAuthorization *string `bson:"dateOfFirstAuthorization,omitempty" json:"dateOfFirstAuthorization,omitempty"`
InternationalBirthDate *string `bson:"internationalBirthDate,omitempty" json:"internationalBirthDate,omitempty"`
LegalBasis *CodeableConcept `bson:"legalBasis,omitempty" json:"legalBasis,omitempty"`
JurisdictionalAuthorization []MedicinalProductAuthorizationJurisdictionalAuthorization `bson:"jurisdictionalAuthorization,omitempty" json:"jurisdictionalAuthorization,omitempty"`
Holder *Reference `bson:"holder,omitempty" json:"holder,omitempty"`
Regulator *Reference `bson:"regulator,omitempty" json:"regulator,omitempty"`
Procedure *MedicinalProductAuthorizationProcedure `bson:"procedure,omitempty" json:"procedure,omitempty"`
}
type MedicinalProductAuthorizationJurisdictionalAuthorization struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Identifier []Identifier `bson:"identifier,omitempty" json:"identifier,omitempty"`
Country *CodeableConcept `bson:"country,omitempty" json:"country,omitempty"`
Jurisdiction []CodeableConcept `bson:"jurisdiction,omitempty" json:"jurisdiction,omitempty"`
LegalStatusOfSupply *CodeableConcept `bson:"legalStatusOfSupply,omitempty" json:"legalStatusOfSupply,omitempty"`
ValidityPeriod *Period `bson:"validityPeriod,omitempty" json:"validityPeriod,omitempty"`
}
type MedicinalProductAuthorizationProcedure struct {
Id *string `bson:"id,omitempty" json:"id,omitempty"`
Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"`
ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"`
Identifier *Identifier `bson:"identifier,omitempty" json:"identifier,omitempty"`
Type CodeableConcept `bson:"type" json:"type"`
DatePeriod *Period `bson:"datePeriod,omitempty" json:"datePeriod,omitempty"`
DateDateTime *string `bson:"dateDateTime,omitempty" json:"dateDateTime,omitempty"`
Application []MedicinalProductAuthorizationProcedure `bson:"application,omitempty" json:"application,omitempty"`
}
type OtherMedicinalProductAuthorization MedicinalProductAuthorization
// MarshalJSON marshals the given MedicinalProductAuthorization as JSON into a byte slice
func (r MedicinalProductAuthorization) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
OtherMedicinalProductAuthorization
ResourceType string `json:"resourceType"`
}{
OtherMedicinalProductAuthorization: OtherMedicinalProductAuthorization(r),
ResourceType: "MedicinalProductAuthorization",
})
}
// UnmarshalMedicinalProductAuthorization unmarshals a MedicinalProductAuthorization.
func UnmarshalMedicinalProductAuthorization(b []byte) (MedicinalProductAuthorization, error) {
var medicinalProductAuthorization MedicinalProductAuthorization
if err := json.Unmarshal(b, &medicinalProductAuthorization); err != nil {
return medicinalProductAuthorization, err
}
return medicinalProductAuthorization, nil
}
|
package domain
type User struct {
UserID uint64
Username string
Password string
FirstName string
LastName string
Email string
}
|
package internal
import (
"log"
"net"
"os"
"strings"
"strconv"
"errors"
"io"
)
var Source string
var Target string
var openConnections int = 0
var MaxConnections int = 20
type Host struct {
address net.IP
port int
}
func (h *Host) getEndpoint() string {
return h.address.String() + ":" + strconv.Itoa(h.port)
}
func getHost(endpoint string) (Host, error) {
host := Host{}
parts := strings.Split(endpoint, ":")
if len(parts) != 2 {
return host, errors.New("Malformed endpoint, it must be in the form of <bind address>:<port>, eg: 0.0.0.0:80")
}
host.address = net.ParseIP(parts[0])
if host.address == nil {
return host, errors.New("Malformed IP address" + parts[0])
}
i, err := strconv.Atoi(parts[1])
if err != nil {
return host, err
}
if i <0 || i > 65535 {
return host, errors.New("Malformed port, it must be in [0, 65535]")
}
host.port = i
return host, nil
}
func loop(sourceConn net.Conn, targetConn net.Conn) {
for {
_, err := io.Copy(sourceConn, targetConn)
if err != nil {
log.Fatal(err)
log.Println("Closing channel due error in communication between source to target")
break
}
}
sourceConn.Close()
log.Println("Channel closed")
}
func channel(sourceConn net.Conn, target Host) error {
log.Println("Creating a channel...")
targetConn, err := net.Dial("tcp", target.getEndpoint())
if err != nil {
return err
}
go loop(sourceConn, targetConn)
go loop(targetConn, sourceConn)
return nil
}
func Open() {
log.Println("Starting server...")
log.Println("Number of max connections: ", MaxConnections)
source, err := getHost(Source)
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
target, err2 := getHost(Target)
if err2 != nil {
log.Fatalln(err2)
os.Exit(1)
}
listener, err3 := net.Listen("tcp", source.getEndpoint())
if err3 != nil {
log.Fatalln(err)
os.Exit(1)
}
defer listener.Close()
for {
client, err4 := listener.Accept()
if err4 != nil {
log.Fatalln(err4)
}
if openConnections >= MaxConnections {
log.Println("Maximum connections reached, a new incoming channel has been blocked")
err4 = client.Close()
if err4 != nil {
log.Fatal(err4)
}
} else {
log.Println("Creating a new channel...")
channel(client, target)
openConnections++
log.Println("Open connections -> ", openConnections)
}
}
} |
package titleator
import (
logger "github.com/sirupsen/logrus"
"strings"
"github.com/badoux/goscraper"
"github.com/amcleodca/pretty-pinboard/pin-enricher/enricher"
"github.com/amcleodca/pretty-pinboard/pin-enricher/pin"
)
type Titleator struct {
log logger.FieldLogger
}
const maxRedirects = 10
func init() {
enricher.Register(NewTitleator)
}
func NewTitleator() (enricher.Enricher, error) {
return &Titleator{
log: logger.WithFields(logger.Fields{"module": "titleator"}),
}, nil
}
func (ta *Titleator) Enrich(pin *pin.Pin) error {
log := ta.log.WithFields(logger.Fields{"url": pin.Post.URL})
log.Debug("start")
defer log.Debug("end")
if pin.HasTag(ta.GetName()) {
log.Info("Already enriched.")
return nil
}
// Title's not empty, but it's just (part of) the URL?
if pin.Post.Title != "" && !strings.Contains(pin.Post.URL, pin.Post.Title) {
return nil
}
page, err := goscraper.Scrape(pin.Post.URL, maxRedirects)
if err != nil {
log.WithError(err).Error("Failed to scrape page.")
return err
}
pin.Modified = true
pin.AddTag(ta.GetName())
pin.Post.Title = page.Preview.Title
log.WithFields(logger.Fields{"title": pin.Post.Title}).Info("Updated")
return nil
}
func (ta *Titleator) GetName() string {
return "titleator"
}
func (ta *Titleator) GetPriority() int {
return 99
}
|
package main
import "context"
func main() {
println("usage: go test -v")
ACLData := `{
"logger": ["/main.Admin/Logging"],
"stat": ["/main.Admin/Statistics"],
"biz_user": ["/main.Biz/Check", "/main.Biz/Add"],
"biz_admin": ["/main.Biz/*"]
}`
listenAddr := "127.0.0.1:8082"
print(StartMyMicroservice(context.Background(), listenAddr, ACLData))
}
|
/*
* Flow CLI
*
* Copyright 2019-2021 Dapper Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tests
import (
"github.com/onflow/cadence"
"github.com/onflow/flow-go-sdk"
"github.com/onflow/flow-go-sdk/client"
"github.com/onflow/flow-cli/pkg/flowcli/gateway"
"github.com/onflow/flow-cli/pkg/flowcli/project"
)
type MockGateway struct {
GetAccountMock func(address flow.Address) (*flow.Account, error)
SendTransactionMock func(tx *flow.Transaction, signer *project.Account) (*flow.Transaction, error)
GetTransactionResultMock func(tx *flow.Transaction) (*flow.TransactionResult, error)
GetTransactionMock func(id flow.Identifier) (*flow.Transaction, error)
ExecuteScriptMock func(script []byte, arguments []cadence.Value) (cadence.Value, error)
GetLatestBlockMock func() (*flow.Block, error)
GetEventsMock func(string, uint64, uint64) ([]client.BlockEvents, error)
GetCollectionMock func(id flow.Identifier) (*flow.Collection, error)
GetBlockByHeightMock func(uint64) (*flow.Block, error)
GetBlockByIDMock func(flow.Identifier) (*flow.Block, error)
}
func NewMockGateway() gateway.Gateway {
return &MockGateway{}
}
func (g *MockGateway) GetAccount(address flow.Address) (*flow.Account, error) {
return g.GetAccountMock(address)
}
func (g *MockGateway) SendTransaction(tx *flow.Transaction, signer *project.Account) (*flow.Transaction, error) {
return g.SendTransactionMock(tx, signer)
}
func (g *MockGateway) GetTransactionResult(tx *flow.Transaction, waitSeal bool) (*flow.TransactionResult, error) {
return g.GetTransactionResultMock(tx)
}
func (g *MockGateway) GetTransaction(id flow.Identifier) (*flow.Transaction, error) {
return g.GetTransactionMock(id)
}
func (g *MockGateway) ExecuteScript(script []byte, arguments []cadence.Value) (cadence.Value, error) {
return g.ExecuteScriptMock(script, arguments)
}
func (g *MockGateway) GetLatestBlock() (*flow.Block, error) {
return g.GetLatestBlockMock()
}
func (g *MockGateway) GetBlockByID(id flow.Identifier) (*flow.Block, error) {
return g.GetBlockByIDMock(id)
}
func (g *MockGateway) GetBlockByHeight(height uint64) (*flow.Block, error) {
return g.GetBlockByHeightMock(height)
}
func (g *MockGateway) GetEvents(name string, start uint64, end uint64) ([]client.BlockEvents, error) {
return g.GetEventsMock(name, start, end)
}
func (g *MockGateway) GetCollection(id flow.Identifier) (*flow.Collection, error) {
return g.GetCollectionMock(id)
}
|
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"Assignment/models"
"Assignment/repository"
"github.com/sirupsen/logrus"
)
type GitUserController struct {
uow *repository.UnitOfWork
gitUserRepo repository.GitUserRepository
userRepo repository.UserRepository
Logger *logrus.Logger
}
func NewGitUserController(uow *repository.UnitOfWork, gitUserRepo repository.GitUserRepository, userRepo repository.UserRepository, Logger *logrus.Logger) *GitUserController {
return &GitUserController{
uow: uow,
gitUserRepo: gitUserRepo,
userRepo: userRepo,
Logger: Logger,
}
}
type gitUserDTO struct {
Username string `json:"username"`
}
// CreateUserGithub creates a new user on github
func (controller *GitUserController) CreateGithubUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
var requestDto gitUserDTO
err := json.NewDecoder(r.Body).Decode(&requestDto)
if err != nil {
controller.Logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
user, err := models.NewGitUser(controller.Logger, requestDto.Username)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = controller.gitUserRepo.CreateGitUser(controller.uow, user)
if err != nil {
controller.Logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
err = json.NewEncoder(w).Encode(user)
if err != nil {
controller.Logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
// get github details of the current logged in user
func (controller *GitUserController) GetUserGithubDetails(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
auth := r.Header.Get("Authorization")
//get authenticated from the request context
token := r.Context().Value("userId").(Token)
userId := token.UserId
tk, err := controller.userRepo.GetToken(controller.uow, userId)
if err != nil {
controller.Logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
exists, err := models.CheckTokenValidation(auth, tk.Token)
if err != nil {
controller.Logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
return
}
if exists {
fmt.Println("userId", userId)
gituser, err := controller.gitUserRepo.GetGitUser(controller.uow, userId)
if err != nil {
controller.Logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
err = json.NewEncoder(w).Encode(gituser)
if err != nil {
controller.Logger.Error(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusBadRequest)
}
|
package main
import (
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
)
func GetRequestHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("GET request: hello, world!"))
}
func PostRequestHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("POST request: hello, world!"))
}
func PathVariableHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
name := vars["name"]
w.Write([]byte("hi " + name))
}
func main() {
var GetRequestHandler = http.HandlerFunc(GetRequestHandler)
var PostRequestHandler = http.HandlerFunc(PostRequestHandler)
var PathVariableHandler = http.HandlerFunc(PathVariableHandler)
router := mux.NewRouter()
logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
router.Handle("/", GetRequestHandler).Methods("GET")
router.Handle("/post", handlers.LoggingHandler(logFile, PostRequestHandler)).Methods("POST")
router.Handle("/hello/{name}", PathVariableHandler).Methods("GET", "PUT")
http.ListenAndServe("localhost:8080", router)
}
|
package main
import (
"bytes"
"crypto/aes"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
aesCMAC "github.com/aead/cmac/aes"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
)
const (
toggleCommand = "88"
lockCommand = "82"
unlockCommand = "83"
)
var applicationName = base64.StdEncoding.EncodeToString([]byte("sesame3-proxy"))
func main() {
godotenv.Load()
port := os.Getenv("PORT")
apiKey := os.Getenv("API_KEY")
uuid1 := os.Getenv("SESAME3_UUID1")
uuid2 := os.Getenv("SESAME3_UUID2")
secretKey1 := os.Getenv("SESAME3_SECRET_KEY1")
secretKey2 := os.Getenv("SESAME3_SECRET_KEY2")
engine := gin.Default()
engine.POST("/lock", func(c *gin.Context) {
sign1, err := calculateSign(secretKey1)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
sign2, err := calculateSign(secretKey2)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
requestCommand(apiKey, uuid1, lockCommand, sign1)
requestCommand(apiKey, uuid2, lockCommand, sign2)
c.String(http.StatusOK, "OK")
})
engine.POST("/unlock", func(c *gin.Context) {
sign1, err := calculateSign(secretKey1)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
sign2, err := calculateSign(secretKey2)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
requestCommand(apiKey, uuid1, unlockCommand, sign1)
requestCommand(apiKey, uuid2, unlockCommand, sign2)
c.String(http.StatusOK, "OK")
})
engine.Run("0.0.0.0:" + port)
}
func calculateSign(secretKey string) ([]byte, error) {
key, err := hex.DecodeString(secretKey)
if err != nil {
return nil, fmt.Errorf("failed to decode secret key: %w", err)
}
messageBuffer := make([]byte, 4)
binary.LittleEndian.PutUint32(messageBuffer, uint32(time.Now().Unix()))
sign, err := aesCMAC.Sum(messageBuffer[1:4], key, aes.BlockSize)
if err != nil {
return nil, fmt.Errorf("failed to calculate sign: %w", err)
}
return sign, nil
}
func requestCommand(apiKey, uuid, command string, sign []byte) error {
data, err := json.Marshal(map[string]string{
"cmd": command,
"history": applicationName,
"sign": hex.EncodeToString(sign),
})
if err != nil {
return fmt.Errorf("failed to marshal data: %w", err)
}
request, _ := http.NewRequest(http.MethodPost, "https://app.candyhouse.co/api/sesame2/"+uuid+"/cmd", bytes.NewBuffer(data))
request.Header.Set("x-api-key", apiKey)
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer response.Body.Close()
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.