text stringlengths 11 4.05M |
|---|
/*
File describe gateway for working with track data in database.
Author: Igor Kuznetsov
Email: me@swe-notes.ru
(c) Copyright by Igor Kuznetsov.
*/
package models
import "time"
type TrackGateway interface {
GetTrackByClient(client uint32, dateStart, dateEnd time.Time) (Track, error)
}
type Track [][]float64
func (db *DB) GetTrackByClient(clientId uint32, dateStart, dateEnd time.Time) (Track, error) {
result := Track{}
rows, err := db.Query(`select ST_X(ST_Transform(geom, 3857)), ST_Y(ST_Transform(geom, 3857))
from vts.track
where client = $1 and navigate_date between $2 and $3
and longitude between 37.32660 and 37.380005
and latitude between 55.675275 and 55.71167
order by navigate_date`,
clientId, dateStart, dateEnd)
if err != nil {
return result, err
}
defer rows.Close()
for rows.Next() {
r := make([]float64, 2)
if err := rows.Scan(&r[0], &r[1]); err != nil {
return result, err
}
result = append(result, r)
}
err = rows.Err()
return result, err
}
|
package main
import (
"os"
"gopkg.in/yaml.v2"
log "github.com/sirupsen/logrus"
)
// Exists reports whether the named file or directory exists.
func Exists(name string) bool {
result := false
log.Debug("We have been asked to check if this exists: ", name)
file, err := os.Stat(name)
if err == nil {
if os.IsNotExist(err) {
log.Warn("File doesn't exist: ", file)
} else {
isFile := checkType(file)
log.Debug("Is it a file: ", *isFile)
if *isFile == 2 {
result = true
}
}
}
return result
}
func checkType(fi os.FileInfo) *int {
format := 0
switch mode := fi.Mode(); {
case mode.IsDir():
format = 1
case mode.IsRegular():
format = 2
}
return &format
}
func GetData(cfg *ConfigTypes, file string) bool {
validConfig := false
f, err := os.Open(file)
if err != nil {
log.Warn("Failed to open file err: ", err)
} else {
decoder := yaml.NewDecoder(f)
err = decoder.Decode(&cfg)
if err != nil {
log.Warn("Couldn't edit file: ", err, f)
} else {
validConfig = true
}
}
return validConfig
}
|
package mocks
import (
"errors"
"github.com/ariel17/railgun/api/entities"
"github.com/ariel17/railgun/api/repositories"
"github.com/ariel17/railgun/api/services"
)
func DomainExists() {
dr := &repositories.MockDBRepository{}
services.DomainsRepository = dr
domain := entities.Domain{
ID: int64(10),
UserID: "test-123",
URL: "ariel17.com.ar",
Code: "code-123",
Verified: false,
}
dr.Domain = &domain
}
func DomainNotExists() {
services.DomainsRepository = &repositories.MockDBRepository{}
}
func DomainOperationFails() {
services.DomainsRepository = &repositories.MockDBRepository{
Err: errors.New("mocked error :D"),
}
}
func DomainAlreadyExists() {
services.DomainsRepository = &repositories.MockDBRepository{
Err: errors.New("domain already exists"),
}
} |
package replaytutorial
import (
"context"
"testing"
"time"
"github.com/luno/jettison/jtest"
"github.com/stretchr/testify/require"
)
func TestTimestamps(t *testing.T) {
*dbRestart = true
*dbName = "tut_test"
Main(func(ctx context.Context, state State) error {
dbc := state.DBC
_, err := dbc.ExecContext(ctx, "create table testtime (id bigint auto_increment, ts datetime(3) not null, primary key (id))")
jtest.RequireNil(t, err)
t0 := time.Now()
_, err = dbc.ExecContext(ctx, "insert into testtime set ts=now(3)")
jtest.RequireNil(t, err)
var ts time.Time
err = dbc.QueryRowContext(ctx, "select ts from testtime where id=1").Scan(&ts)
jtest.RequireNil(t, err)
require.InDelta(t, t0.UnixNano(), ts.UnixNano(), 1e9) // Within 1 sec
t0 = time.Now()
_, err = dbc.ExecContext(ctx, "insert into testtime set ts=?", t0)
jtest.RequireNil(t, err)
err = dbc.QueryRowContext(ctx, "select ts from testtime where id=2").Scan(&ts)
jtest.RequireNil(t, err)
require.InDelta(t, t0.UnixNano(), ts.UnixNano(), 1e9) // Within 1 sec
return nil
})
}
|
package models
// Todo is the basic type to hold a todo item
type Todo struct {
ID string `json:"ID"`
ParentID string `json:"ParentID"`
Desc string `json:"Desc"`
Complete bool `json:"Complete"`
} |
package errors
import (
"encoding/json"
"fmt"
"net/http"
"github.com/doniacld/outdoorsight/internal/endpointdef"
)
// ODSError represents the format of a returned HTTP error
type ODSError struct {
HTTPCode int `json:"HTTPCode"`
Message string `json:"message"`
}
// Error returns the message of the error
func (err *ODSError) Error() string {
return err.Message
}
func New(errorType int, message string) *ODSError {
return &ODSError{HTTPCode: errorType, Message: message}
}
func NewFromError(errorType int, err error, message string) *ODSError {
return &ODSError{HTTPCode: errorType, Message: fmt.Sprintf("%s, %s", message, err.Error())}
}
func (err *ODSError) Wrap(message string) *ODSError {
return &ODSError{HTTPCode: err.HTTPCode, Message: fmt.Sprintf("%s: %s", message, err.Message)}
}
// HTTPError encodes the http error into a JSON file
func (err *ODSError) HTTPError(w http.ResponseWriter) {
// write header should be done first to be taken into account
w.WriteHeader(err.HTTPCode)
w.Header().Set(endpointdef.ContentType, endpointdef.MimeTypeJSON)
if jsonErr := json.NewEncoder(w).Encode(&err); jsonErr != nil {
err.Message = jsonErr.Error()
}
}
|
//go:generate jsonconst -w=c -type=CodedError ./cerr
//go:generate jsonconst -w=u -type=TradeState,UserCashType,OrderState,BillboardType,VipRebateType,VpnType ./front
//go:generate mapconst -type=TradeState,UserCashType,OrderState ./front
package esecend
|
package main
import (
"flag"
"fmt"
htmlt "html/template"
"io"
"io/ioutil"
"os"
textt "text/template"
"github.com/AstromechZA/godork"
)
func OutputModeTemplate(pkg *godork.PackageDoc, w io.Writer) error {
// parse some options from the command line
fs := flag.NewFlagSet("t", flag.ExitOnError)
templateFileFlag := fs.String("template", "", "Comma separated list of paths to Golang style templates for interpreting the structured object")
ignoreErrFlag := fs.Bool("missingkey-ignore", false, "Ignore missingkey errors in the template")
htmlModeFlag := fs.Bool("html-mode", false, "Interpret the template in html mode and use escape characters")
if err := fs.Parse(os.Args[1:]); err != nil {
return err
}
// read list of file paths
if *templateFileFlag == "" {
return fmt.Errorf("--template option is required")
}
mk := "missingkey=error"
if *ignoreErrFlag {
mk = "missingkey=default"
}
tcontent, err := ioutil.ReadFile(*templateFileFlag)
if err != nil {
return err
}
if *htmlModeFlag {
t := htmlt.New("")
t = t.Funcs(map[string]interface{}{
"to_text": ToText,
"to_html": ToHTML,
"highlight_html": HighlightHTML,
})
t, terr := t.Parse(string(tcontent))
if terr != nil {
return terr
}
return t.Option(mk).Execute(w, pkg)
}
t := textt.New("")
t = t.Funcs(map[string]interface{}{
"to_text": ToText,
"to_html": ToHTML,
})
t, terr := t.Parse(string(tcontent))
if terr != nil {
return terr
}
return t.Option(mk).Execute(w, pkg)
}
|
package main
var result [][]int
func subsets(nums []int) [][]int {
result = make([][]int, 0)
solve(nums, 0, []int{})
return result
}
func solve(nums []int, idx int, tmp []int) {
result = append(result, NewSlice(tmp))
for i := idx; i < len(nums); i++ {
solve(nums, i+1, append(tmp, nums[i]))
}
}
func NewSlice(old []int) []int {
newSlice := make([]int, len(old))
copy(newSlice, old)
return newSlice
}
/*
总结
1. 这题考查全排列 0.0..
*/
|
/*
* Copyright 2018, CS Systemes d'Information, http://www.c-s.fr
*
* 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 providers_test
import (
"fmt"
"github.com/CS-SI/SafeScale/providers/cloudferro"
"testing"
"github.com/CS-SI/SafeScale/providers/cloudwatt"
"github.com/CS-SI/SafeScale/providers/flexibleengine"
"github.com/CS-SI/SafeScale/providers/opentelekom"
"github.com/CS-SI/SafeScale/providers/ovh"
"github.com/stretchr/testify/require"
"github.com/CS-SI/SafeScale/providers"
)
func TestCompare(t *testing.T) {
s1 := providers.SimilarityScore("16.04", "ubuntu-xenial-16.04-amd64-server-20170329")
fmt.Println(s1)
}
func TestParameters(t *testing.T) {
p := make(map[string]interface{})
p["String"] = "fkldkjfkdl"
s := p["String"].(string)
fmt.Println(s)
s, _ = p["String2"].(string)
fmt.Println(s)
}
func TestGetService(t *testing.T) {
providers.Register("ovh", &ovh.Client{})
providers.Register("cloudwatt", &cloudwatt.Client{})
providers.Register("flexibleEngine", &flexibleengine.Client{})
providers.Register("opentelekom", &opentelekom.Client{})
providers.Register("cloudferro", &cloudferro.Client{})
ovh, err := providers.GetService("TestOvh")
require.Nil(t, err)
_, err = providers.GetService("TestCloudwatt")
require.Nil(t, err)
_, err = providers.GetService("TestFlexibleEngine")
require.Nil(t, err)
_, err = providers.GetService("TestOpenTelekom")
require.Nil(t, err)
imgs, err := ovh.ListImages(false)
require.Nil(t, err)
require.True(t, len(imgs) > 3)
//_, err = providers.GetService("TestCloudwatt")
//require.Nil(t, err)
}
func TestGetServiceErr(t *testing.T) {
createTenantFile()
defer deleteTenantFile()
providers.Register("ovh", &ovh.Client{})
providers.Register("cloudwatt", &cloudwatt.Client{})
providers.Register("cloudferro", &cloudferro.Client{})
_, err := providers.GetService("TestOhvehache")
require.Error(t, err)
_, err = providers.GetService("UnknownService")
require.Error(t, err)
}
|
package dropbox
import (
"encoding/json"
"errors"
"github.com/DennisDenuto/property-price-collector/data"
"github.com/DennisDenuto/property-price-collector/data/training/dropbox/dropboxfakes"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"io/ioutil"
)
var _ = Describe("DomaincomuaHistoryTrainingRepo", func() {
var repo DomainComAuHistoryDataRepo
var fakeClient *dropboxfakes.FakeClient
BeforeEach(func() {
fakeClient = &dropboxfakes.FakeClient{}
repo = DomainComAuHistoryDataRepo{
dropboxClient: fakeClient,
}
})
Describe("Add", func() {
It("should add to dropbox", func() {
propertyHistoryData := data.DomainComAuPropertyListWrapper{
PropertyObject: data.DomainComAuPropertyHistory{
Suburb: "North Sydney",
State: "NSW",
Address: "1 123-124 fake street, North Sydney NSW 2000",
StreetAddress: "1 123-124 fake street",
},
}
propertyHistoryDataJson, err := json.Marshal(propertyHistoryData)
Expect(err).ToNot(HaveOccurred())
err = repo.Add(&propertyHistoryData)
Expect(err).NotTo(HaveOccurred())
Expect(fakeClient.UploadCallCount()).To(Equal(1))
commitInfo, content := fakeClient.UploadArgsForCall(0)
Expect(commitInfo.Path).To(Equal("/domaincomau/nsw/north_sydney/1_123-124_fake_street"))
contents, err := ioutil.ReadAll(content)
Expect(err).NotTo(HaveOccurred())
Expect(contents).To(MatchJSON(propertyHistoryDataJson))
})
Context("when dropbox fails to upload", func() {
It("should return an error", func() {
propertyHistoryData := &data.DomainComAuPropertyListWrapper{
PropertyObject: data.DomainComAuPropertyHistory{
Suburb: "North Sydney",
State: "NSW",
Address: "1 123-124 fake street, North Sydney NSW 2000",
StreetAddress: "1 123-124 fake street",
},
}
fakeClient.UploadReturns(nil, errors.New("some dropbox error"))
err := repo.Add(propertyHistoryData)
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError("some dropbox error"))
})
})
})
})
|
package router
import (
"github.com/gin-gonic/gin"
"nginx-manager/controllers/oauth"
"nginx-manager/controllers/process"
)
func SetupRouter() *gin.Engine {
// Disable Console Color
// gin.DisableConsoleColor()
r := gin.Default()
instance := r.Group("/process/instance")
{
instance.GET("/start", oauth.ParseToken, process.Start)
instance.GET("/stop", process.Stop)
instance.GET("/reload", process.Reload)
instance.GET("/check", process.Check)
}
conf := r.Group("/process/config")
{
conf.POST("/upload", process.Upload)
conf.GET("/download", process.Download)
}
authorize := r.Group("/oauth")
{
authorize.POST("/login", oauth.Login)
}
return r
}
|
/*
* KSQL
*
* This is a swagger spec for ksqldb
*
* API version: 1.0.0
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package swagger
type ShowListResponse struct {
Tables []ShowListResponseTables `json:"tables,omitempty"`
Streams []ShowListResponseStreams `json:"streams,omitempty"`
Queries []ShowListResponseQueries `json:"queries,omitempty"`
Properties *interface{} `json:"properties,omitempty"`
}
|
package filesystem
import (
"bytes"
"io/ioutil"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_readDir(t *testing.T) {
t.Parallel()
tests := []struct {
name string
body string
want []file
wantErr bool
}{
{
name: "directory",
body: `<html>
<head><title>Index of /a/</title></head>
<body bgcolor="white">
<h1>Index of /a/</h1><hr><pre><a href="../">../</a>
<a href="c/">c/</a> 18-Jan-2018 23:32 -
<a href="xxx">xxx</a> 18-Jan-2018 23:32 17
<a href="yyy">yyy</a> 18-Jan-2018 23:32 0
</pre><hr></body>
</html>
`,
want: []file{
{name: "c", isDir: true, time: time.Date(2018, time.January, 18, 23, 32, 0, 0, time.UTC)},
{name: "xxx", isDir: false, size: 17, time: time.Date(2018, time.January, 18, 23, 32, 0, 0, time.UTC)},
{name: "yyy", isDir: false, size: 0, time: time.Date(2018, time.January, 18, 23, 32, 0, 0, time.UTC)},
},
},
{
name: "bad time format",
body: `<html>
<head><title>Index of /a/</title></head>
<body bgcolor="white">
<h1>Index of /a/</h1><hr><pre><a href="../">../</a>
<a href="c/">c/</a> 18-Jan-2018 23:32 -
<a href="xxx">xxx</a> 181-Jan-2018 23:32 17
<a href="yyy">yyy</a> 18-Jan-2018 23:32 0
</pre><hr></body>
</html>
`,
want: []file{
{name: "c", isDir: true, time: time.Date(2018, time.January, 18, 23, 32, 0, 0, time.UTC)},
{name: "yyy", isDir: false, size: 0, time: time.Date(2018, time.January, 18, 23, 32, 0, 0, time.UTC)},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := bytes.NewBufferString(tt.body)
got, err := parseDirectoryHTML(ioutil.NopCloser(body))
if tt.wantErr {
assert.NotNil(t, err)
return
}
require.Nil(t, err)
require.Equal(t, len(tt.want), len(got))
for i := 0; i < len(tt.want); i++ {
assert.Equal(t, tt.want[i].name, got[i].Name())
assert.Equal(t, tt.want[i].isDir, got[i].IsDir())
assert.Equal(t, tt.want[i].time, got[i].ModTime())
assert.Equal(t, tt.want[i].size, got[i].Size())
}
})
}
}
|
package cmd
import (
"github.com/Files-com/files-cli/lib"
"github.com/spf13/cobra"
"fmt"
"os"
files_sdk "github.com/Files-com/files-sdk-go"
"github.com/Files-com/files-sdk-go/notification"
)
var (
Notifications = &cobra.Command{
Use: "notifications [command]",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {},
}
)
func NotificationsInit() {
var fieldsList string
paramsNotificationList := files_sdk.NotificationListParams{}
var MaxPagesList int
cmdList := &cobra.Command{
Use: "list",
Short: "list",
Long: `list`,
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
params := paramsNotificationList
params.MaxPages = MaxPagesList
it, err := notification.List(params)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lib.JsonMarshalIter(it, fieldsList)
},
}
cmdList.Flags().Int64VarP(¶msNotificationList.UserId, "user-id", "u", 0, "DEPRECATED: Show notifications for this User ID. Use `filter[user_id]` instead.")
cmdList.Flags().StringVarP(¶msNotificationList.Cursor, "cursor", "c", "", "Used for pagination. Send a cursor value to resume an existing list from the point at which you left off. Get a cursor from an existing list via the X-Files-Cursor-Next header.")
cmdList.Flags().IntVarP(¶msNotificationList.PerPage, "per-page", "a", 0, "Number of records to show per page. (Max: 10,000, 1,000 or less is recommended).")
cmdList.Flags().Int64VarP(¶msNotificationList.GroupId, "group-id", "r", 0, "DEPRECATED: Show notifications for this Group ID. Use `filter[group_id]` instead.")
cmdList.Flags().StringVarP(¶msNotificationList.Path, "path", "p", "", "Show notifications for this Path.")
cmdList.Flags().IntVarP(&MaxPagesList, "max-pages", "m", 1, "When per-page is set max-pages limits the total number of pages requested")
cmdList.Flags().StringVarP(&fieldsList, "fields", "", "", "comma separated list of field names to include in response")
Notifications.AddCommand(cmdList)
var fieldsFind string
paramsNotificationFind := files_sdk.NotificationFindParams{}
cmdFind := &cobra.Command{
Use: "find",
Run: func(cmd *cobra.Command, args []string) {
result, err := notification.Find(paramsNotificationFind)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lib.JsonMarshal(result, fieldsFind)
},
}
cmdFind.Flags().Int64VarP(¶msNotificationFind.Id, "id", "i", 0, "Notification ID.")
cmdFind.Flags().StringVarP(&fieldsFind, "fields", "", "", "comma separated list of field names")
Notifications.AddCommand(cmdFind)
var fieldsCreate string
paramsNotificationCreate := files_sdk.NotificationCreateParams{}
cmdCreate := &cobra.Command{
Use: "create",
Run: func(cmd *cobra.Command, args []string) {
result, err := notification.Create(paramsNotificationCreate)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lib.JsonMarshal(result, fieldsCreate)
},
}
cmdCreate.Flags().Int64VarP(¶msNotificationCreate.UserId, "user-id", "u", 0, "The id of the user to notify. Provide `user_id`, `username` or `group_id`.")
cmdCreate.Flags().StringVarP(¶msNotificationCreate.SendInterval, "send-interval", "s", "", "The time interval that notifications are aggregated by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`.")
cmdCreate.Flags().Int64VarP(¶msNotificationCreate.GroupId, "group-id", "g", 0, "The ID of the group to notify. Provide `user_id`, `username` or `group_id`.")
cmdCreate.Flags().StringVarP(¶msNotificationCreate.Path, "path", "p", "", "Path")
cmdCreate.Flags().StringVarP(¶msNotificationCreate.Username, "username", "e", "", "The username of the user to notify. Provide `user_id`, `username` or `group_id`.")
cmdCreate.Flags().StringVarP(&fieldsCreate, "fields", "", "", "comma separated list of field names")
Notifications.AddCommand(cmdCreate)
var fieldsUpdate string
paramsNotificationUpdate := files_sdk.NotificationUpdateParams{}
cmdUpdate := &cobra.Command{
Use: "update",
Run: func(cmd *cobra.Command, args []string) {
result, err := notification.Update(paramsNotificationUpdate)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lib.JsonMarshal(result, fieldsUpdate)
},
}
cmdUpdate.Flags().Int64VarP(¶msNotificationUpdate.Id, "id", "i", 0, "Notification ID.")
cmdUpdate.Flags().StringVarP(¶msNotificationUpdate.SendInterval, "send-interval", "s", "", "The time interval that notifications are aggregated by. Can be `five_minutes`, `fifteen_minutes`, `hourly`, or `daily`.")
cmdUpdate.Flags().StringVarP(&fieldsUpdate, "fields", "", "", "comma separated list of field names")
Notifications.AddCommand(cmdUpdate)
var fieldsDelete string
paramsNotificationDelete := files_sdk.NotificationDeleteParams{}
cmdDelete := &cobra.Command{
Use: "delete",
Run: func(cmd *cobra.Command, args []string) {
result, err := notification.Delete(paramsNotificationDelete)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lib.JsonMarshal(result, fieldsDelete)
},
}
cmdDelete.Flags().Int64VarP(¶msNotificationDelete.Id, "id", "i", 0, "Notification ID.")
cmdDelete.Flags().StringVarP(&fieldsDelete, "fields", "", "", "comma separated list of field names")
Notifications.AddCommand(cmdDelete)
}
|
package leetcode
import "testing"
func Test_KMP(t *testing.T) {
model := "bdaba"
t.Log(getNext(model))
t.Log(KMP(model, "abdabac"))
}
|
package db
// import (
// "errors"
// )
// // Summary contains information about the user's analysis.
// type Summary struct {
// UserID string `json:"id",sql:"type:uuid; primary key"`
// PortfolioGrowth
// }
|
package iproto
import (
"errors"
"fmt"
"testing"
cli2 "github.com/DmiAS/cube_cli/internal/app/cli"
"github.com/DmiAS/cube_cli/internal/app/connection"
"github.com/DmiAS/cube_cli/internal/app/mocks"
"github.com/DmiAS/cube_cli/internal/app/models"
)
func closeFunc(err error) mocks.ErrFn {
return func() error {
return err
}
}
func writeFunc(withError bool) mocks.WriteFn {
return func([]byte) (int, error) {
var err error = nil
if withError {
err = errors.New("new error")
}
return 0, err
}
}
func dialFunc(conn connection.Connection, err error) mocks.DialFn {
return func() (connection.Connection, error) {
return conn, err
}
}
func compareResponseOk(a, b models.ResponseOk) bool {
return a.UserID == b.UserID && a.ExpiresIn == b.ExpiresIn &&
a.UserName == b.UserName && a.ClientType == b.ClientType &&
a.ClientID == b.ClientID && a.ReturnCode == b.ReturnCode
}
func TestClientInvalidDial(t *testing.T) {
dialFn := dialFunc(nil, errors.New("can't connect to server"))
connector := mocks.NewConnector(dialFn)
proto := NewClient(connector)
cli := cli2.NewCubeClient(proto)
if _, err := cli.Send("token", "scope"); err == nil {
t.Fatalf("err = %v", err)
}
}
func TestClientInvalidWrite(t *testing.T) {
writeFn := writeFunc(true)
closeFn := closeFunc(nil)
conn := &mocks.Connection{
CloseWriteFn: closeFn,
WriteFn: writeFn,
}
dialFn := dialFunc(conn, nil)
connector := mocks.NewConnector(dialFn)
proto := NewClient(connector)
cli := cli2.NewCubeClient(proto)
if _, err := cli.Send("token", "scope"); err == nil {
t.Fatalf("err = %v", err)
}
}
func TestClientInvalidCloseWrite(t *testing.T) {
writeFn := writeFunc(false)
closeFn := closeFunc(errors.New("can't close connection"))
conn := &mocks.Connection{
CloseWriteFn: closeFn,
WriteFn: writeFn,
}
dialFn := dialFunc(conn, nil)
connector := mocks.NewConnector(dialFn)
proto := NewClient(connector)
cli := cli2.NewCubeClient(proto)
if _, err := cli.Send("token", "scope"); err == nil {
t.Fatalf("err = %v", err)
}
}
func TestClientReadErr(t *testing.T) {
writeFn := writeFunc(false)
closeFn := closeFunc(nil)
errString := "bad scope"
readFn := func(_ []byte) ([]byte, error) {
resp := models.ResponsePacket{
Header: models.Header{},
Body: models.ResponseBody{
ReturnCode: 1,
ErrorString: strToProtoString(errString),
},
}
return resp.Marshal()
}
conn := &mocks.Connection{
CloseWriteFn: closeFn,
ReadFn: readFn,
WriteFn: writeFn,
}
dialFn := dialFunc(conn, nil)
connector := mocks.NewConnector(dialFn)
proto := NewClient(connector)
cli := cli2.NewCubeClient(proto)
resp, err := cli.Send("token", "scope")
if err != nil {
t.Fatalf("err = %v", err)
}
respErr, ok := resp.(models.ResponseErr)
if !ok {
t.Fatal("invalid type of struct, expected ResponseErr")
}
if respErr.ErrorString != errString {
t.Fatalf("err string = %s", respErr.ErrorString)
}
}
func TestClientReadOk(t *testing.T) {
ans := models.ResponseOk{
ReturnCode: 0,
ClientID: "test_client_id",
ClientType: 2002,
UserName: "testuser@mail.ru",
ExpiresIn: 3600,
UserID: 101010,
}
readFn := func(_ []byte) ([]byte, error) {
resp := models.ResponsePacket{
Header: models.Header{},
Body: models.ResponseBody{
ReturnCode: ans.ReturnCode,
ClientID: strToProtoString(ans.ClientID),
ClientType: ans.ClientType,
UserName: strToProtoString(ans.UserName),
ExpiresIn: ans.ExpiresIn,
UserID: ans.UserID,
},
}
return resp.Marshal()
}
conn := &mocks.Connection{
CloseWriteFn: closeFunc(nil),
ReadFn: readFn,
WriteFn: writeFunc(false),
}
dialFn := dialFunc(conn, nil)
connector := mocks.NewConnector(dialFn)
proto := NewClient(connector)
cli := cli2.NewCubeClient(proto)
resp, err := cli.Send("token", "scope")
if err != nil {
t.Fatalf("err = %v", err)
}
respOk, ok := resp.(models.ResponseOk)
if !ok {
t.Fatal("invalid type of struct, expected ResponseOk")
}
if !compareResponseOk(respOk, ans) {
t.Fatalf("%v != %v", respOk, ans)
}
}
func TestClientWriteFields(t *testing.T) {
token, scope := "abracadabra", "test"
// здесь проверяю правильно упаковались данные или нет
readFn := func(data []byte) ([]byte, error) {
req := &models.RequestPacket{}
if err := req.UnMarshal(data); err != nil {
return nil, err
}
tokenR, err := req.Body.Token.ToString()
if err != nil {
return nil, err
}
scopeR, err := req.Body.Scope.ToString()
if err != nil {
return nil, err
}
if tokenR != token {
return nil, fmt.Errorf("request token(%s) != token(%s)", tokenR, token)
}
if scope != scopeR {
return nil, fmt.Errorf("request token(%s) != token(%s)", tokenR, token)
}
return data, nil
}
conn := &mocks.Connection{
CloseWriteFn: closeFunc(errors.New("can't close connection")),
ReadFn: readFn,
}
dialFn := dialFunc(conn, nil)
connector := mocks.NewConnector(dialFn)
proto := NewClient(connector)
cli := cli2.NewCubeClient(proto)
if _, err := cli.Send(token, scope); err == nil {
t.Fatalf("err = %v", err)
}
}
func TestClientRequestHeader(t *testing.T) {
token, scope := "abracadabra", "test"
// здесь проверяю правильно упаковались данные или нет
readFn := func(data []byte) ([]byte, error) {
req := &models.RequestPacket{}
length := req.Header.BodyLength
body, _ := req.Body.Marshal()
bodyLength := int32(len(body))
if length != bodyLength {
return nil, fmt.Errorf("header length(%d) != body length(%d)", length, bodyLength)
}
return data, nil
}
conn := &mocks.Connection{
CloseWriteFn: closeFunc(errors.New("can't close connection")),
ReadFn: readFn,
}
dialFn := dialFunc(conn, nil)
connector := mocks.NewConnector(dialFn)
proto := NewClient(connector)
cli := cli2.NewCubeClient(proto)
if _, err := cli.Send(token, scope); err == nil {
t.Fatalf("err = %v", err)
}
}
|
package mock
import (
"github.com/shharn/blog/model"
"github.com/shharn/blog/repository"
"github.com/stretchr/testify/mock"
)
type MockArticleRepository struct {
mock.Mock
}
func (mr *MockArticleRepository) Context() interface{} {
ret := mr.Called()
return ret.Get(0).(repository.Disposable)
}
func (mr *MockArticleRepository) HottestArticles(ctx interface{}, offset, count string) ([]model.Article, error) {
ret := mr.Called(ctx, offset, count)
return ret.Get(0).([]model.Article), ret.Error(1)
}
func (mr *MockArticleRepository) ArticlesOnMenu(ctx interface{}, mid, offset, count string) ([]model.Article, error) {
ret := mr.Called(ctx, mid, offset, count)
return ret.Get(0).([]model.Article), ret.Error(1)
}
func (mr *MockArticleRepository) Create(ctx interface{}, article model.Article) error {
ret := mr.Called(ctx, article)
return ret.Error(0)
}
func (mr *MockArticleRepository) Get(ctx interface{}, id string) (model.Article, error) {
ret := mr.Called(ctx, id)
return ret.Get(0).(model.Article), ret.Error(1)
}
func (mr *MockArticleRepository) Delete(ctx interface{}, id string) error {
ret:= mr.Called(ctx, id)
return ret.Error(0)
}
func (mr *MockArticleRepository) Update(ctx interface{}, article model.Article) error {
ret := mr.Called(ctx, article)
return ret.Error(0)
}
func (mr *MockArticleRepository) GetByTitle(ctx interface{}, title string) (model.Article, error) {
ret := mr.Called(ctx, title)
return ret.Get(0).(model.Article), ret.Error(1)
} |
package collector
import (
"context"
"fmt"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
)
func dockerCollector(ctx context.Context, name, url string, stream chan DockerMetrics, errors chan error, filters filters.Args, refreshInterval time.Duration) {
cli, err := client.NewClient(url, "v1.24", nil, nil)
if err != nil {
errors <- err
return
}
for {
list, err := cli.ContainerList(ctx, types.ContainerListOptions{
Quiet: false,
Size: false,
All: true,
Latest: false,
Since: "",
Before: "",
Limit: 0,
Filters: filters,
})
if err != nil {
errors <- err
} else {
var running = 0
var paused = 0
var total = 0
var state = make([]int8,0)
for _, container := range list {
var val int8 = 0
switch status := container.State; status {
case "running":
val = 2
running++
case "paused":
val =1
paused++
}
total++
state = append(state,val)
}
stream <- DockerMetrics{
name: name,
Running: running,
Paused: paused,
Total: total,
State: state,
}
}
select {
case _ = <-time.After(refreshInterval):
//nothing
case _ = <-ctx.Done():
fmt.Printf("[%s] cacneld", name)
return
}
}
}
|
package controllers
import (
"OnlineShop/models"
)
// 这里为了偷懒使用了指针类型,作为一个事件消息来说,
// 应该具备跨进程和跨机器的能力, 因为变量类型应该只能是基本类型
// 因为beego框架的限制,没有统一处理 controller的地方
// 也就是说在当前 `请求生命周期` 内,在任意地方应该可以获取当前`controller` 指针的能力,
// 如果具备了这样的能力,那么很容易在任意地方去 `make_response` (思想来源skynet框架中)。
type ShopEvent struct {
//购物事件
User *models.User
GoodDetail *models.GoodDetail
Num int
// 当购物事件处理完成之后进行回调
Controller *IndexController
}
func(shop_event *ShopEvent)LoadUser(){
// 模型定义应该是UserId
//通过LoadUser来实现user_id => UserInstance的转化
} |
// Copyright 2022 PingCAP, Inc. Licensed under Apache-2.0.
package streamhelper
import (
"context"
"github.com/google/uuid"
"github.com/pingcap/tidb/br/pkg/utils"
"github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/owner"
clientv3 "go.etcd.io/etcd/client/v3"
)
const (
ownerPrompt = "log-backup"
ownerPath = "/tidb/br-stream/owner"
)
// OnTick advances the inner logic clock for the advancer.
// It's synchronous: this would only return after the events triggered by the clock has all been done.
// It's generally panic-free, you may not need to trying recover a panic here.
func (c *CheckpointAdvancer) OnTick(ctx context.Context) (err error) {
defer c.recordTimeCost("tick")()
defer utils.PanicToErr(&err)
return c.tick(ctx)
}
// OnStart implements daemon.Interface, which will be called when log backup service starts.
func (c *CheckpointAdvancer) OnStart(ctx context.Context) {
c.StartTaskListener(ctx)
}
// OnBecomeOwner implements daemon.Interface. If the tidb-server become owner, this function will be called.
func (c *CheckpointAdvancer) OnBecomeOwner(ctx context.Context) {
metrics.AdvancerOwner.Set(1.0)
c.spawnSubscriptionHandler(ctx)
go func() {
<-ctx.Done()
c.onStop()
}()
}
// Name implements daemon.Interface.
func (c *CheckpointAdvancer) Name() string {
return "LogBackup::Advancer"
}
func (c *CheckpointAdvancer) onStop() {
metrics.AdvancerOwner.Set(0.0)
c.stopSubscriber()
}
func OwnerManagerForLogBackup(ctx context.Context, etcdCli *clientv3.Client) owner.Manager {
id := uuid.New()
return owner.NewOwnerManager(ctx, etcdCli, ownerPrompt, id.String(), ownerPath)
}
|
package main
import (
"context"
"fmt"
"net/http"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var client *mongo.Client
func welcomeHandler(response http.ResponseWriter, request *http.Request) {
response.Write([]byte("welcome"))
}
func main() {
clientOptions := options.Client().
ApplyURI("mongodb+srv://abcd:abcd@cluster0.u7fpe.mongodb.net/appointee?retryWrites=true&w=majority")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, _ = mongo.Connect(ctx, clientOptions)
http.Handle("/users", http.HandlerFunc(userHandler))
http.Handle("/posts", http.HandlerFunc(postHandler))
http.Handle("/posts/user", http.HandlerFunc(GetPostsByUser))
http.Handle("/", http.HandlerFunc(welcomeHandler))
fmt.Println("Listening")
http.ListenAndServe("localhost:3000", nil)
} |
// Copyright © 2020 Attestant Limited.
// 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 standard
import (
"context"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/pkg/errors"
e2types "github.com/wealdtech/go-eth2-types/v2"
e2wtypes "github.com/wealdtech/go-eth2-wallet-types/v2"
)
// sign signs a root, using protected methods if possible.
func (s *Service) sign(ctx context.Context,
account e2wtypes.Account,
root phase0.Root,
domain phase0.Domain,
) (
phase0.BLSSignature,
error,
) {
var sig e2types.Signature
if protectingSigner, isProtectingSigner := account.(e2wtypes.AccountProtectingSigner); isProtectingSigner {
var err error
sig, err = protectingSigner.SignGeneric(ctx, root[:], domain[:])
if err != nil {
return phase0.BLSSignature{}, err
}
} else {
container := phase0.SigningData{
ObjectRoot: root,
Domain: domain,
}
root, err := container.HashTreeRoot()
if err != nil {
return phase0.BLSSignature{}, errors.Wrap(err, "failed to generate hash tree root")
}
sig, err = account.(e2wtypes.AccountSigner).Sign(ctx, root[:])
if err != nil {
return phase0.BLSSignature{}, err
}
}
var signature phase0.BLSSignature
copy(signature[:], sig.Marshal())
return signature, nil
}
|
package openid
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
const wellKnownOpenIDConfiguration = "/.well-known/openid-configuration"
type configurationGetter interface {
get(r *http.Request, url string) (configuration, error)
}
type configurationDecoder interface {
decode(io.Reader) (configuration, error)
}
type httpGetter interface {
get(r *http.Request, url string) (*http.Response, error)
}
func (f HTTPGetFunc) get(r *http.Request, url string) (*http.Response, error) {
return f(r, url)
}
type httpConfigurationProvider struct {
getter httpGetter
decoder configurationDecoder
}
func newHTTPConfigurationProvider(gc HTTPGetFunc, dc configurationDecoder) *httpConfigurationProvider {
return &httpConfigurationProvider{gc, dc}
}
func (httpProv *httpConfigurationProvider) get(r *http.Request, issuer string) (configuration, error) {
// Workaround for tokens issued by google
if issuer == "accounts.google.com" {
issuer = "https://" + issuer
}
configurationURI := issuer + wellKnownOpenIDConfiguration
var config configuration
resp, err := httpProv.getter.get(r, configurationURI)
if err != nil {
return config, &ValidationError{
Code: ValidationErrorGetOpenIdConfigurationFailure,
Message: fmt.Sprintf("Failure while contacting the configuration endpoint %v.", configurationURI),
Err: err,
HTTPStatus: http.StatusUnauthorized,
}
}
defer resp.Body.Close()
if config, err = httpProv.decoder.decode(resp.Body); err != nil {
return config, &ValidationError{
Code: ValidationErrorDecodeOpenIdConfigurationFailure,
Message: fmt.Sprintf("Failure while decoding the configuration retrived from endpoint %v.", configurationURI),
Err: err,
HTTPStatus: http.StatusUnauthorized,
}
}
return config, nil
}
func jsonDecodeResponse(r io.Reader, v interface{}) error {
return json.NewDecoder(r).Decode(v)
}
type jsonConfigurationDecoder struct {
}
func (d *jsonConfigurationDecoder) decode(r io.Reader) (configuration, error) {
var config configuration
err := jsonDecodeResponse(r, &config)
return config, err
}
|
/*
* @lc app=leetcode.cn id=383 lang=golang
*
* [383] 赎金信
*/
// @lc code=start
package main
// import "strings"
import "fmt"
func canConstruct(ransomNote string, magazine string) bool {
// for _, c := range ransomNote {
// cc := string(c)
// if strings.Contains(magazine, cc) {
// magazine = strings.Replace(magazine, cc, "", 1)
// } else {
// return false
// }
// }
// return true
// if len(ransomNote) > len(magazine) {
// return false
// }
// indexArray := make(map[rune]int)
// for _, c := range magazine {
// if _, ok := indexArray[c] ; ok {
// indexArray[c] += 1
// } else {
// indexArray[c] = 1
// }
// }
// for _, d := range ransomNote {
// if value, ok := indexArray[d] ; ok {
// tmp := value - 1
// if tmp < 0 {
// return false
// } else {
// indexArray[d] = tmp
// }
// } else {
// return false
// }
// }
// return true
if len(ransomNote) > len(magazine) {
return false
}
indexArray := map[rune]int{}
for _, v := range ransomNote {
index, _ := indexArray[v]
index = strings.Index(magazine[index:], string(v))
if index == -1 {
return false
}
indexArray[v] += index + 1
}
return true
}
// @lc code=end
func main() {
fmt.Printf("%t\n", canConstruct("aa", "ab"))
fmt.Printf("%t\n", canConstruct("a", "b"))
fmt.Printf("%t\n", canConstruct("aa", "aab"))
}
|
// Copyright 2015 Walter Schulze
//
// 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 combinator provides a user friendly way of constructing a relapse abstract syntax tree.
//
//TODO: Review this API of this package, especially the Array methods.
package combinator
import (
"github.com/katydid/katydid/relapse/ast"
)
//G represents the relapse Grammar.
//This consists of a "main" map key with the main pattern value and any other references.
type G map[string]*ast.Pattern
//Grammar returns G as a proper relapse.Grammar
func (g G) Grammar() *ast.Grammar {
return ast.NewGrammar(g)
}
//Any represents a zero or more of anything pattern.
func Any() *ast.Pattern {
return ast.NewZAny()
}
func concat(p *ast.Pattern, ps ...*ast.Pattern) *ast.Pattern {
if len(ps) == 0 {
return p
}
pss := append([]*ast.Pattern{p}, ps...)
return ast.NewConcat(pss...)
}
//InPath represents an ordered list of patterns in a field path.
func InPath(name string, child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
return ast.NewContains(ast.NewTreeNode(ast.NewStringName(name), concat(child, children...)))
}
//InAnyPath represents an ordered list of patterns in any path.
func InAnyPath(child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
return ast.NewContains(ast.NewTreeNode(ast.NewAnyName(), concat(child, children...)))
}
//In represents an ordered list of patterns in a field.
func In(name string, child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
return ast.NewTreeNode(ast.NewStringName(name), concat(child, children...))
}
//Elem repesents an ordered list of patterns in an specific array element.
func Elem(index int, child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
return ast.NewTreeNode(ast.NewIntName(int64(index)), concat(child, children...))
}
//InAny represents an ordered list of patterns in any field or index.
func InAny(child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
return ast.NewTreeNode(ast.NewAnyName(), concat(child, children...))
}
//InAnyExcept represents an ordered list of patterns in any field except the specified one.
func InAnyExcept(name string, child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
return ast.NewTreeNode(ast.NewAnyNameExcept(ast.NewStringName(name)), concat(child, children...))
}
func nameChoice(p string, ps ...string) *ast.NameExpr {
if len(ps) == 0 {
return ast.NewStringName(p)
}
return ast.NewNameChoice(ast.NewStringName(p), nameChoice(ps[0], ps[1:]...))
}
//InAnyOf represents an ordered list of patterns in any of the specified fields.
func InAnyOf(names []string, child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
if len(names) < 2 {
panic("less than two names is not really a choice, is it?")
}
return ast.NewTreeNode(nameChoice(names[0], names[1:]...), concat(child, children...))
}
//None represents no possible match.
func None() *ast.Pattern {
return ast.NewNot(ast.NewZAny())
}
//Eval represents the evaluation of a reference name.
func Eval(name string) *ast.Pattern {
return ast.NewReference(name)
}
//InOrder represents an ordered list of patterns.
func InOrder(child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
return concat(child, children...)
}
//AllOf represents an intersection of patterns.
func AllOf(patterns ...*ast.Pattern) *ast.Pattern {
return ast.NewAnd(patterns...)
}
//AnyOf represents a union of patterns.
func AnyOf(patterns ...*ast.Pattern) *ast.Pattern {
return ast.NewOr(patterns...)
}
//OppositeOf represents a compliment of a pattern.
func OppositeOf(p *ast.Pattern) *ast.Pattern {
return ast.NewNot(p)
}
//Many represents zero or more of the input pattern.
func Many(p *ast.Pattern) *ast.Pattern {
return ast.NewZeroOrMore(p)
}
//Maybe represents an optional pattern.
func Maybe(p *ast.Pattern) *ast.Pattern {
return ast.NewOptional(p)
}
func interleave(p *ast.Pattern, ps ...*ast.Pattern) *ast.Pattern {
if len(ps) == 0 {
return p
}
pss := append([]*ast.Pattern{p}, ps...)
return ast.NewInterleave(pss...)
}
//InAnyOrder represents interleaved patterns.
func InAnyOrder(child *ast.Pattern, children ...*ast.Pattern) *ast.Pattern {
return interleave(child, children...)
}
|
package core
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path"
"reflect"
"strings"
jsonpatch "github.com/evanphx/json-patch"
"github.com/gin-gonic/gin"
"github.com/textileio/go-textile/repo/config"
)
func getKeyValue(path string, object interface{}) (interface{}, error) {
keys := strings.Split(path, "/")
v := reflect.ValueOf(object)
for _, key := range keys {
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return nil, fmt.Errorf("unable to parse struct path; ecountered %T", v)
}
v = v.FieldByName(key)
if !v.IsValid() {
return nil, fmt.Errorf("empty struct value")
}
}
return v.Interface(), nil
}
// getConfig godoc
// @Summary Get active config settings
// @Description Report the currently active config settings, which may differ from the values
// @Description specifed when setting/patching values.
// @Tags config
// @Produce application/json
// @Param path path string false "config path (e.g., Addresses/API)"
// @Success 200 {object} mill.Json "new config value"
// @Failure 400 {string} string "Bad Request"
// @Router /config/{path} [get]
func (a *api) getConfig(g *gin.Context) {
pth := g.Param("path")
conf := a.node.Config()
if pth == "" {
g.JSON(http.StatusOK, conf)
} else {
value, err := getKeyValue(pth[1:], conf)
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
g.JSON(http.StatusOK, value)
}
}
// patchConfig godoc
// @Summary Set/update config settings
// @Description When patching config values, valid JSON types must be used. For example, a string
// @Description should be escaped or wrapped in single quotes (e.g., \"127.0.0.1:40600\") and
// @Description arrays and objects work fine (e.g. '{"API": "127.0.0.1:40600"}') but should be
// @Description wrapped in single quotes. Be sure to restart the daemon for changes to take effect.
// @Description See https://tools.ietf.org/html/rfc6902 for details on RFC6902 JSON patch format.
// @Tags config
// @Accept application/json
// @Param patch body mill.Json true "An RFC6902 JSON patch (array of ops)"
// @Success 204 {string} string "No Content"
// @Failure 400 {string} string "Bad Request"
// @Router /config [patch]
func (a *api) patchConfig(g *gin.Context) {
body, err := ioutil.ReadAll(g.Request.Body)
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
defer g.Request.Body.Close()
// decode request body into a RFC 6902 patch (array of ops)
patch, err := jsonpatch.DecodePatch(body)
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
configPath := path.Join(a.node.repoPath, "textile")
original, err := ioutil.ReadFile(configPath)
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
// apply json patch to config
modified, err := patch.Apply(original)
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
// make sure our config is still valid
conf := config.Config{}
err = json.Unmarshal(modified, &conf)
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
jsn, err := json.MarshalIndent(conf, "", " ")
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
if err := ioutil.WriteFile(configPath, jsn, 0666); err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
g.Writer.WriteHeader(http.StatusNoContent)
}
// setConfig godoc
// @Summary Replace config settings.
// @Description Replace entire config file contents. The config command controls configuration
// @Description variables. It works much like 'git config'. The configuration values are stored
// @Description in a config file inside the Textile repository.
// @Tags config
// @Accept application/json
// @Param config body mill.Json true "JSON document"
// @Success 204 {string} string "No Content"
// @Failure 400 {string} string "Bad Request"
// @Router /config [put]
func (a *api) setConfig(g *gin.Context) {
configPath := path.Join(a.node.repoPath, "textile")
body, err := ioutil.ReadAll(g.Request.Body)
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
defer g.Request.Body.Close()
conf := config.Config{}
err = json.Unmarshal(body, &conf)
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
jsn, err := json.MarshalIndent(conf, "", " ")
if err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
if err := ioutil.WriteFile(configPath, jsn, 0666); err != nil {
g.String(http.StatusBadRequest, err.Error())
return
}
g.Writer.WriteHeader(http.StatusNoContent)
}
|
package sigsci
import (
"encoding/json"
"fmt"
"log"
"os"
"reflect"
"testing"
"time"
)
type TestCreds struct {
email string
token string
corp string
site string
}
var testcreds = TestCreds{
email: os.Getenv("SIGSCI_EMAIL"),
token: os.Getenv("SIGSCI_TOKEN"),
corp: os.Getenv("SIGSCI_CORP"),
site: os.Getenv("SIGSCI_SITE"),
}
func ExampleClient_InviteUser() {
email := testcreds.email
password := testcreds.token
sc, err := NewClient(email, password)
if err != nil {
log.Fatal(err)
}
invite := NewCorpUserInvite(RoleCorpUser, []SiteMembership{
NewSiteMembership(testcreds.site, RoleSiteOwner),
})
_, err = sc.InviteUser(testcreds.corp, "test@test.net", invite)
if err != nil {
log.Fatal(err)
}
}
func TestGoUserTokenClient(t *testing.T) {
testCases := []struct {
name string
email string
token string
}{
{
name: "working user pass creds",
email: testcreds.email,
token: testcreds.token,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
sc := NewTokenClient(testCase.email, testCase.token)
if corps, err := sc.ListCorps(); err != nil {
t.Fatal(err)
} else {
if testcreds.corp != corps[0].Name {
t.Errorf("Corp ")
}
}
})
}
}
func TestGoUserTokenClientWithTimeout(t *testing.T) {
testCase := Client{
email: testcreds.email,
token: testcreds.token,
}
timeoutFunc := func(ssclient *Client) {
ssclient.SetTimeout(time.Duration(10) * time.Second)
}
t.Run("test token client with timeout option", func(t *testing.T) {
sc := NewTokenClient(testCase.email, testCase.token, timeoutFunc)
if sc.timeout.Seconds() != 10 {
t.Errorf("Client time got %.0f expected %d", sc.timeout.Seconds(), 10)
}
})
}
func TestGoUserTokenClientWithoutTimeout(t *testing.T) {
testCase := Client{
email: testcreds.email,
token: testcreds.token,
}
t.Run("test token client with timeout option", func(t *testing.T) {
sc := NewTokenClient(testCase.email, testCase.token)
if sc.timeout.Seconds() != 0 {
t.Errorf("Client time got %.0f expected %d", sc.timeout.Seconds(), 0)
}
})
}
func TestCreateUpdateDeleteSite(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
siteBody := CreateSiteBody{
Name: "test-site",
DisplayName: "Test Site",
AgentLevel: "block",
BlockHTTPCode: 406, // TODO test non-default value once api supports it
BlockDurationSeconds: 86400, // TODO test non-default value once api supports it
AgentAnonMode: "",
}
siteresponse, err := sc.CreateSite(corp, siteBody)
if err != nil {
t.Fatal(err)
}
if "Test Site" != siteresponse.DisplayName {
t.Errorf("Displayname got %s expected %s", siteresponse.DisplayName, "Test Site")
}
if "block" != siteresponse.AgentLevel {
t.Errorf("AgentLevel got %s expected %s", siteresponse.AgentLevel, "block")
}
if 406 != siteresponse.BlockHTTPCode {
t.Errorf("BlockHTTPCode got %d expected %d", siteresponse.BlockHTTPCode, 406)
}
if 86400 != siteresponse.BlockDurationSeconds {
t.Errorf("BlockDurationSeconds got %d expected %d", siteresponse.BlockDurationSeconds, 86400)
}
if "" != siteresponse.AgentAnonMode {
t.Errorf("AgentAnonMode got %s expected %s", siteresponse.AgentAnonMode, "")
}
updateSite, err := sc.UpdateSite(corp, siteBody.Name, UpdateSiteBody{
DisplayName: "Test Site 2",
AgentLevel: "off",
BlockDurationSeconds: 86402,
BlockHTTPCode: 406, // TODO increment this value once api supports it
AgentAnonMode: "EU",
})
if "Test Site 2" != updateSite.DisplayName {
t.Errorf("Displayname got %s expected %s", updateSite.DisplayName, "Test Site 2")
}
if "off" != updateSite.AgentLevel {
t.Errorf("AgentLevel got %s expected %s", updateSite.AgentLevel, "off")
}
if 406 != updateSite.BlockHTTPCode {
t.Errorf("BlockHTTPCode got %d expected %d", updateSite.BlockHTTPCode, 406)
}
if 86402 != updateSite.BlockDurationSeconds {
t.Errorf("BlockDurationSeconds got %d expected %d", updateSite.BlockDurationSeconds, 86402)
}
if "EU" != updateSite.AgentAnonMode {
t.Errorf("AgentAnonMode got %s expected %s", updateSite.AgentAnonMode, "EU")
}
err = sc.DeleteSite(corp, siteBody.Name)
if err != nil {
t.Errorf("%#v", err)
}
}
func compareSiteRuleBody(sr1, sr2 CreateSiteRuleBody) bool {
if sr1.Enabled != sr2.Enabled {
return false
}
if sr1.Reason != sr2.Reason {
return false
}
if sr1.Type != sr2.Type {
return false
}
if sr1.Signal != sr2.Signal {
return false
}
if sr1.Expiration != sr2.Expiration {
return false
}
if sr1.GroupOperator != sr2.GroupOperator {
return false
}
return true
}
func TestCreateReadUpdateDeleteSiteRules(t *testing.T) {
createSiteRulesBody := CreateSiteRuleBody{
Type: "signal",
GroupOperator: "all",
Enabled: true,
Reason: "Example site rule",
Signal: "SQLI",
Expiration: "",
Conditions: []Condition{
{
Type: "single",
Field: "ip",
Operator: "equals",
Value: "1.2.3.4",
},
{
Type: "group",
GroupOperator: "any",
Conditions: []Condition{
{
Type: "single",
Field: "ip",
Operator: "equals",
Value: "5.6.7.8",
},
},
},
},
Actions: []Action{
Action{
Type: "excludeSignal",
},
},
}
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createResp, err := sc.CreateSiteRule(corp, site, createSiteRulesBody)
if err != nil {
t.Fatal(err)
}
if !compareSiteRuleBody(createSiteRulesBody, createResp.CreateSiteRuleBody) {
t.Errorf("CreateSiteRulesgot: %v expected %v", createResp, createSiteRulesBody)
}
readResp, err := sc.GetSiteRuleByID(corp, site, createResp.ID)
if err != nil {
t.Fatal(err)
}
if !compareSiteRuleBody(createSiteRulesBody, readResp.CreateSiteRuleBody) {
t.Errorf("CreateSiteRulesgot: %v expected %v", createResp, createSiteRulesBody)
}
updateSiteRuleBody := CreateSiteRuleBody{
Type: "signal",
GroupOperator: "all",
Enabled: true,
Reason: "Example site rule",
Signal: "SQLI",
Expiration: "",
Conditions: []Condition{
{
Type: "single",
Field: "ip",
Operator: "equals",
Value: "1.2.3.4",
},
{
Type: "group",
GroupOperator: "any",
Conditions: []Condition{
{
Type: "single",
Field: "ip",
Operator: "equals",
Value: "9.10.11.12",
},
},
},
},
Actions: []Action{
{
Type: "excludeSignal",
},
},
}
updateResp, err := sc.UpdateSiteRuleByID(corp, site, createResp.ID, updateSiteRuleBody)
if err != nil {
t.Fatal(err)
}
if !compareSiteRuleBody(updateSiteRuleBody, updateResp.CreateSiteRuleBody) {
t.Errorf("CreateSiteRulesgot: %v expected %v", createResp, createSiteRulesBody)
}
readall, err := sc.GetAllSiteRules(corp, site)
if err != nil {
t.Fatal(err)
}
if len(readall.Data) != 1 {
t.Error()
}
if readall.TotalCount != 1 {
t.Error()
}
if !compareSiteRuleBody(updateSiteRuleBody, readall.Data[0].CreateSiteRuleBody) {
}
err = sc.DeleteSiteRuleByID(corp, site, createResp.ID)
if err != nil {
t.Fatal(err)
}
}
func TestUnMarshalListData(t *testing.T) {
resp := []byte(fmt.Sprintf(`{
"totalCount": 1,
"data": [
{
"id": "5e84ec28bf612801c7f0f109",
"siteNames": [
"%s"
],
"type": "signal",
"enabled": true,
"groupOperator": "all",
"conditions": [
{
"type": "single",
"field": "ip",
"operator": "equals",
"value": "1.2.3.4"
}
],
"actions": [
{
"type": "excludeSignal"
}
],
"signal": "SQLI",
"reason": "Example site rule",
"expiration": "",
"createdBy": "test@gmail.com",
"created": "2020-04-01T19:31:52Z",
"updated": "2020-04-01T19:31:52Z"
}
]
}`, testcreds.site))
var responseRulesList ResponseSiteRuleBodyList
err := json.Unmarshal(resp, &responseRulesList)
if err != nil {
t.Fatal(err)
}
if responseRulesList.TotalCount != 1 {
t.Error()
}
if len(responseRulesList.Data) != 1 {
t.Error()
}
if responseRulesList.Data[0].ID != "5e84ec28bf612801c7f0f109" {
t.Error()
}
}
func TestDeleteAllSiteRules(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
respList, err := sc.GetAllSiteRules(corp, site)
if err != nil {
t.Fatal(err)
}
for _, rule := range respList.Data {
sc.DeleteSiteRuleByID(corp, site, rule.ID)
}
respList, err = sc.GetAllSiteRules(corp, site)
if err != nil {
t.Fatal(err)
}
if len(respList.Data) != 0 {
t.Error()
}
}
func compareSiteListBody(sl1, sl2 CreateListBody) bool {
if sl1.Type != sl2.Type {
return false
}
if sl1.Description != sl2.Description {
return false
}
if sl1.Name != sl2.Name {
return false
}
if len(sl1.Entries) != len(sl2.Entries) {
return false
}
return true
}
func TestCreateReadUpdateDeleteSiteList(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createSiteListBody := CreateListBody{
Name: "My new list",
Type: "ip",
Description: "Some IPs we are putting in a list",
Entries: []string{
"4.5.6.7",
"2.3.4.5",
"1.2.3.4",
},
}
createresp, err := sc.CreateSiteList(corp, site, createSiteListBody)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createSiteListBody, createresp.CreateListBody) {
t.Error("Site list body not equal after create")
}
readresp, err := sc.GetSiteListByID(corp, site, createresp.ID)
if !reflect.DeepEqual(createSiteListBody, readresp.CreateListBody) {
t.Error("Site list body not equal after read")
}
updateSiteListBody := UpdateListBody{
Description: "Some IPs we are updating in the list",
Entries: Entries{
Additions: []string{"3.4.5.6"},
Deletions: []string{"4.5.6.7"},
},
}
updateresp, err := sc.UpdateSiteListByID(corp, site, readresp.ID, updateSiteListBody)
if err != nil {
t.Fatal(err)
}
updatedSiteListBody := CreateListBody{
Name: "My new list",
Type: "ip",
Description: "Some IPs we are updating in the list",
Entries: []string{
"2.3.4.5",
"1.2.3.4",
"3.4.5.6",
},
}
if !reflect.DeepEqual(updatedSiteListBody, updateresp.CreateListBody) {
t.Error("Site list body not equal")
}
readall, err := sc.GetAllSiteLists(corp, site)
if len(readall.Data) != 1 {
t.Error()
}
if !reflect.DeepEqual(updatedSiteListBody, readall.Data[0].CreateListBody) {
t.Error("Site list body not equal")
}
err = sc.DeleteSiteListByID(corp, site, readresp.ID)
if err != nil {
t.Fatal(err)
}
}
func TestCreateMultipleRedactions(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createSiteRedactionBody := CreateSiteRedactionBody{
Field: "privatefield",
RedactionType: 2,
}
createresp, err := sc.CreateSiteRedaction(corp, site, createSiteRedactionBody)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createSiteRedactionBody, createresp.CreateSiteRedactionBody) {
t.Error("Site redaction body not equal after create")
}
createSiteRedactionBody2 := CreateSiteRedactionBody{
Field: "cookie",
RedactionType: 2,
}
createresp2, err := sc.CreateSiteRedaction(corp, site, createSiteRedactionBody2)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createSiteRedactionBody2, createresp2.CreateSiteRedactionBody) {
t.Error("Site redaction body not equal after create")
}
createSiteRedactionBody3 := CreateSiteRedactionBody{
Field: "cookie",
RedactionType: 0,
}
createresp3, err := sc.CreateSiteRedaction(corp, site, createSiteRedactionBody3)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createSiteRedactionBody3, createresp3.CreateSiteRedactionBody) {
t.Error("Site redaction body not equal after create")
}
err = sc.DeleteSiteRedactionByID(corp, site, createresp.ID)
if err != nil {
t.Fatal(err)
}
err = sc.DeleteSiteRedactionByID(corp, site, createresp2.ID)
if err != nil {
t.Fatal(err)
}
err = sc.DeleteSiteRedactionByID(corp, site, createresp3.ID)
if err != nil {
t.Fatal(err)
}
}
func TestCreateListUpdateDeleteRedaction(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createSiteRedactionBody := CreateSiteRedactionBody{
Field: "privatefield",
RedactionType: 2,
}
createresp, err := sc.CreateSiteRedaction(corp, site, createSiteRedactionBody)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createSiteRedactionBody, createresp.CreateSiteRedactionBody) {
t.Error("Site redaction body not equal after create")
}
readresp, err := sc.GetSiteRedactionByID(corp, site, createresp.ID)
if !reflect.DeepEqual(createSiteRedactionBody, readresp.CreateSiteRedactionBody) {
t.Error("Site redaction body not equal after read")
}
updateSiteRedactionBody := CreateSiteRedactionBody{
Field: "cookie",
RedactionType: 0,
}
updatedresp, err := sc.UpdateSiteRedactionByID(corp, site, createresp.ID, updateSiteRedactionBody)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(updateSiteRedactionBody, updatedresp.CreateSiteRedactionBody) {
t.Error("Site redaction body not equal after update")
}
readall, err := sc.GetAllSiteRedactions(corp, site)
if len(readall.Data) != 1 {
t.Error("incorrect number of site redactions, make sure you didnt add any manually")
}
if !reflect.DeepEqual(updateSiteRedactionBody, readall.Data[0].CreateSiteRedactionBody) {
t.Error("Site redaction body not equal after update")
}
err = sc.DeleteSiteRedactionByID(corp, site, createresp.ID)
if err != nil {
t.Fatal(err)
}
}
func TestSiteCreateReadUpdateDeleteAlerts(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createCustomAlert := CustomAlertBody{
TagName: "SQLI",
LongName: "Example Alert",
Interval: 1,
Threshold: 10,
Enabled: true,
Action: "flagged",
}
createresp, err := sc.CreateCustomAlert(corp, site, createCustomAlert)
if err != nil {
t.Fatal(err)
}
// set unknown fields just for equality
if createCustomAlert.TagName != createresp.TagName {
t.Error("tag names not equal")
}
if createCustomAlert.LongName != createresp.LongName {
t.Error("tag names not equal")
}
if createCustomAlert.Interval != createresp.Interval {
t.Error("tag names not equal")
}
if createCustomAlert.Threshold != createresp.Threshold {
t.Error("tag names not equal")
}
if createCustomAlert.Enabled != createresp.Enabled {
t.Error("tag names not equal")
}
if createCustomAlert.Action != createresp.Action {
t.Error("tag names not equal")
}
readresp, err := sc.GetCustomAlert(corp, site, createresp.ID)
if err != nil {
t.Fatal(err)
}
if createCustomAlert.TagName != readresp.TagName {
t.Error("tag names not equal")
}
if createCustomAlert.LongName != readresp.LongName {
t.Error("tag names not equal")
}
if createCustomAlert.Interval != readresp.Interval {
t.Error("tag names not equal")
}
if createCustomAlert.Threshold != readresp.Threshold {
t.Error("tag names not equal")
}
if createCustomAlert.Enabled != readresp.Enabled {
t.Error("tag names not equal")
}
if createCustomAlert.Action != readresp.Action {
t.Error("tag names not equal")
}
updateCustomAlert := CustomAlertBody{
TagName: "SQLI",
LongName: "Example Alert Updated",
Interval: 10,
Threshold: 10,
Enabled: true,
Action: "flagged",
}
updateResp, err := sc.UpdateCustomAlert(corp, site, readresp.ID, updateCustomAlert)
if err != nil {
t.Fatal(err)
}
if updateCustomAlert.TagName != updateResp.TagName {
t.Error("tag names not equal")
}
if updateCustomAlert.LongName != updateResp.LongName {
t.Error("tag names not equal")
}
if updateCustomAlert.Interval != updateResp.Interval {
t.Error("tag names not equal")
}
if updateCustomAlert.Threshold != updateResp.Threshold {
t.Error("tag names not equal")
}
if updateCustomAlert.Enabled != updateResp.Enabled {
t.Error("tag names not equal")
}
if updateCustomAlert.Action != updateResp.Action {
t.Error("tag names not equal")
}
allalerts, err := sc.ListCustomAlerts(corp, site)
if err != nil {
t.Fatal(err)
}
if len(allalerts) != 1 {
t.Error("alerts length incorrect. make sure none we added outside")
}
if updateCustomAlert.TagName != allalerts[0].TagName {
t.Error("tag names not equal")
}
if updateCustomAlert.LongName != allalerts[0].LongName {
t.Error("long names not equal")
}
if updateCustomAlert.Interval != allalerts[0].Interval {
t.Error("interval not equal")
}
if updateCustomAlert.Threshold != allalerts[0].Threshold {
t.Error("threshold not equal")
}
if updateCustomAlert.Enabled != allalerts[0].Enabled {
t.Error("enbled not equal")
}
if updateCustomAlert.Action != allalerts[0].Action {
t.Error("action not equal")
}
err = sc.DeleteCustomAlert(corp, site, createresp.ID)
if err != nil {
t.Fatal(err)
}
}
func TestCreateReadUpdateDeleteCorpRule(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
// Get initial counts
initialCorps, err := sc.GetAllCorpRules(corp)
if err != nil {
t.Fatal(err)
}
createCorpRuleBody := CreateCorpRuleBody{
SiteNames: []string{testcreds.site},
Type: "signal",
GroupOperator: "all",
Conditions: []Condition{
{
Type: "single",
Field: "ip",
Operator: "equals",
Value: "1.2.3.4",
},
{
Type: "group",
GroupOperator: "any",
Conditions: []Condition{
{
Type: "single",
Field: "ip",
Operator: "equals",
Value: "5.6.7.8",
},
},
},
},
Actions: []Action{
{
Type: "excludeSignal",
},
},
Enabled: true,
Reason: "test",
Signal: "SQLI",
Expiration: "",
CorpScope: "specificSites",
}
createResp, err := sc.CreateCorpRule(corp, createCorpRuleBody)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createCorpRuleBody, createResp.CreateCorpRuleBody) {
t.Error("Corp rule body not equal after create")
}
readResp, err := sc.GetCorpRuleByID(corp, createResp.ID)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(readResp, createResp) {
t.Error("Corp rule body not equal after read")
}
updateCorpRuleBody := CreateCorpRuleBody{
SiteNames: []string{testcreds.site},
Type: "signal",
GroupOperator: "all",
Conditions: []Condition{
{
Type: "single",
Field: "ip",
Operator: "equals",
Value: "5.6.7.8",
},
{
Type: "group",
GroupOperator: "any",
Conditions: []Condition{
{
Type: "single",
Field: "ip",
Operator: "equals",
Value: "6.7.8.9",
},
},
},
},
Actions: []Action{
{
Type: "excludeSignal",
},
},
Enabled: true,
Reason: "test",
Signal: "SQLI",
Expiration: "",
CorpScope: "specificSites",
}
updateResp, err := sc.UpdateCorpRuleByID(corp, createResp.ID, updateCorpRuleBody)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(updateCorpRuleBody, updateResp.CreateCorpRuleBody) {
t.Error("Corp rule body not equal after update")
}
readall, err := sc.GetAllCorpRules(corp)
if err != nil {
t.Fatal(err)
}
if len(initialCorps.Data)+1 != len(readall.Data) {
t.Error()
}
if initialCorps.TotalCount+1 != readall.TotalCount {
t.Error()
}
if !reflect.DeepEqual(updateCorpRuleBody, readall.Data[0].CreateCorpRuleBody) {
t.Error("Corp rule body not equal after get all. make sure nothing was added externally")
}
err = sc.DeleteCorpRuleByID(corp, createResp.ID)
if err != nil {
t.Fatal(err)
}
readall, err = sc.GetAllCorpRules(corp)
if err != nil {
t.Fatal(err)
}
if len(initialCorps.Data) != len(readall.Data) {
t.Error()
}
if initialCorps.TotalCount != readall.TotalCount {
t.Error()
}
}
func compareCorpListBody(cl1, cl2 CreateListBody) bool {
if cl1.Name != cl2.Name {
return false
}
if cl1.Type != cl2.Type {
return false
}
if cl1.Description != cl2.Description {
return false
}
if len(cl1.Entries) != len(cl2.Entries) {
return false
}
return true
}
func TestCreateReadUpdateDeleteCorpList(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
createCorpListBody := CreateListBody{
Name: "My new List",
Type: "ip",
Description: "Some IPs we are putting in a list",
Entries: []string{
"4.5.6.7",
"2.3.4.5",
"1.2.3.4",
},
}
createresp, err := sc.CreateCorpList(corp, createCorpListBody)
if err != nil {
t.Fatal(err)
}
if !compareCorpListBody(createCorpListBody, createresp.CreateListBody) {
t.Error("corp list not equal after create")
}
now := time.Now()
expectedCreateResponse := ResponseListBody{
CreateListBody: CreateListBody{
Name: "My new List",
Type: "ip",
Description: "Some IPs we are putting in a list",
Entries: []string{
"4.5.6.7",
"2.3.4.5",
"1.2.3.4",
},
},
ID: "corp.my-new-list",
CreatedBy: "",
Created: now,
Updated: now,
}
createresp.Created = now
createresp.Updated = now
createresp.CreatedBy = ""
if !reflect.DeepEqual(expectedCreateResponse, createresp) {
t.Error("corp list not equal after get")
}
readresp, err := sc.GetCorpListByID(corp, createresp.ID)
if err != nil {
t.Fatal(err)
}
if !compareCorpListBody(createCorpListBody, readresp.CreateListBody) {
t.Error("corp list not equal after read")
}
updateCorpListBody := UpdateListBody{
Description: "Some IPs we are updating in the list",
Entries: Entries{
Additions: []string{"3.4.5.6"},
Deletions: []string{"4.5.6.7"},
},
}
updateresp, err := sc.UpdateCorpListByID(corp, readresp.ID, updateCorpListBody)
if err != nil {
t.Error(err)
}
if updateCorpListBody.Description != updateresp.Description {
t.Error("descriptions not equal after update")
}
hasNewEntry := false
for _, e := range updateresp.Entries {
if e == "4.5.6.7" {
t.Fail()
}
if e == "3.4.5.6" {
hasNewEntry = true
}
}
if !hasNewEntry {
t.Error()
}
updatedCorpListBody := CreateListBody{
Name: "My new List",
Type: "ip",
Description: "Some IPs we are updating in the list",
Entries: []string{
"2.3.4.5",
"1.2.3.4",
"3.4.5.6",
},
}
if !compareCorpListBody(updatedCorpListBody, updateresp.CreateListBody) {
t.Error("corp list not equal after update")
}
readall, err := sc.GetAllCorpLists(corp)
if err != nil {
t.Fatal(err)
}
if len(readall.Data) != 1 {
t.Error()
}
if !compareCorpListBody(updatedCorpListBody, readall.Data[0].CreateListBody) {
t.Error("corp list not equal after update")
}
err = sc.DeleteCorpListByID(corp, readresp.ID)
if err != nil {
t.Fatal(err)
}
}
func TestCreateReadUpdateDeleteCorpTag(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
createSignalTagBody := CreateSignalTagBody{
ShortName: "Example Signal Tag 1",
Description: "An example of a custom signal tag",
}
createresp, err := sc.CreateCorpSignalTag(corp, createSignalTagBody)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createSignalTagBody, createresp.CreateSignalTagBody) {
t.Fatal()
}
expectedCreateResponse := ResponseSignalTagBody{
CreateSignalTagBody: CreateSignalTagBody{
ShortName: "Example Signal Tag 1",
Description: "An example of a custom signal tag",
},
TagName: "corp.example-signal-tag-1",
LongName: "Example Signal Tag 1",
Configurable: false,
Informational: false,
NeedsResponse: false,
CreatedBy: "",
Created: time.Time{},
}
createresp.Created = time.Time{}
createresp.CreatedBy = ""
if !reflect.DeepEqual(expectedCreateResponse, createresp) {
t.Fail()
}
readresp, err := sc.GetCorpSignalTagByID(corp, createresp.TagName)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createSignalTagBody, readresp.CreateSignalTagBody) {
t.Fail()
}
updateSignalTagBody := UpdateSignalTagBody{
Description: "An example of a custom signal tag - UPDATE",
}
updateresp, err := sc.UpdateCorpSignalTagByID(corp, createresp.TagName, updateSignalTagBody)
if err != nil {
t.Fatal(err)
}
updatedSignalTagBody := CreateSignalTagBody{
ShortName: "Example Signal Tag 1",
Description: "An example of a custom signal tag - UPDATE",
}
if !reflect.DeepEqual(updatedSignalTagBody, updateresp.CreateSignalTagBody) {
t.Fail()
}
readall, err := sc.GetAllCorpSignalTags(corp)
if err != nil {
t.Fatal(err)
}
if len(readall.Data) != 1 {
t.Fail()
}
if !reflect.DeepEqual(updatedSignalTagBody, readall.Data[0].CreateSignalTagBody) {
t.Fail()
}
err = sc.DeleteCorpSignalTagByID(corp, readresp.TagName)
if err != nil {
t.Fatal(err)
}
}
func TestCreateReadUpdateDeleteSignalTag(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createSignalTagBody := CreateSignalTagBody{
ShortName: "example-signal-tag",
Description: "An example of a custom signal tag",
}
createresp, err := sc.CreateSiteSignalTag(corp, site, createSignalTagBody)
if err != nil {
t.Fatal(err)
}
readresp, err := sc.GetSiteSignalTagByID(corp, site, createresp.TagName)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(createSignalTagBody, readresp.CreateSignalTagBody) {
t.Fail()
}
updateSignalTagBody := UpdateSignalTagBody{
Description: "An example of a custom signal tag - UPDATE",
}
updateresp, err := sc.UpdateSiteSignalTagByID(corp, site, createresp.TagName, updateSignalTagBody)
if err != nil {
t.Fatal(err)
}
updatedSignalTagBody := CreateSignalTagBody{
ShortName: "example-signal-tag",
Description: "An example of a custom signal tag - UPDATE",
}
if !reflect.DeepEqual(updatedSignalTagBody, updateresp.CreateSignalTagBody) {
t.Fail()
}
readall, err := sc.GetAllSiteSignalTags(corp, site)
if err != nil {
t.Fatal(err)
}
if len(readall.Data) != 1 {
t.Fail()
}
if !reflect.DeepEqual(updatedSignalTagBody, readall.Data[0].CreateSignalTagBody) {
t.Fail()
}
err = sc.DeleteSiteSignalTagByID(corp, site, readresp.TagName)
if err != nil {
t.Fatal(err)
}
}
func TestCreateReadUpdateDeleteSiteTemplate(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createresp, err := sc.UpdateSiteTemplateRuleByID(corp, site, "LOGINATTEMPT", SiteTemplateRuleBody{
DetectionAdds: []Detection{
{
DetectionUpdateBody: DetectionUpdateBody{
Name: "path",
Enabled: true,
Fields: []ConfiguredDetectionField{
{
Name: "path",
Value: "/auth/*",
},
},
},
},
},
DetectionUpdates: []Detection{},
DetectionDeletes: []Detection{},
AlertAdds: []Alert{
{
AlertUpdateBody: AlertUpdateBody{
LongName: "LOGINATTEMPT-50-in-1",
Interval: 1,
Threshold: 50,
SkipNotifications: true,
Enabled: true,
Action: "info",
}},
},
AlertUpdates: []Alert{},
AlertDeletes: []Alert{},
})
if err != nil {
t.Fatal(err)
}
readresp, err := sc.GetSiteTemplateRuleByID(corp, site, createresp.Name)
if err != nil {
t.Fatal(err)
}
fmt.Println(createresp)
fmt.Println(readresp)
}
func TestCRUDCorpIntegrations(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
url := "https://www.signalsciences.com"
createResp, err := sc.AddCorpIntegration(corp, IntegrationBody{
URL: url,
Type: "slack",
Events: []string{"webhookEvents"},
})
if err != nil {
t.Fatal(err)
}
readResp, err := sc.GetCorpIntegration(corp, createResp.ID)
if err != nil {
t.Fatal(err)
}
if createResp.ID != readResp.ID {
t.Fail()
}
if createResp.URL != readResp.URL {
t.Fail()
}
if createResp.Type != readResp.Type {
t.Fail()
}
if !reflect.DeepEqual([]string{"webhookEvents"}, readResp.Events) {
t.Fail()
}
newURL := url + "/blah"
err = sc.UpdateCorpIntegration(corp, readResp.ID, UpdateIntegrationBody{
URL: newURL,
Events: []string{"corpUpdated", "listDeleted"},
})
if err != nil {
t.Fatal(err)
}
readResp2, err := sc.GetCorpIntegration(corp, createResp.ID)
if err != nil {
t.Fatal(err)
}
if newURL != readResp2.URL {
t.Fail()
}
if !reflect.DeepEqual([]string{"corpUpdated", "listDeleted"}, readResp2.Events) {
t.Fail()
}
err = sc.DeleteCorpIntegration(corp, readResp2.ID)
if err != nil {
t.Fatal(err)
}
}
func TestCRUDSiteMonitorDashboard(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createResp, err := sc.GenerateSiteMonitorDashboard(corp, site, "000000000000000000000001")
if err != nil {
t.Fatal(err)
}
monitors, err := sc.GetSiteMonitor(corp, site, createResp.ID)
if err != nil {
t.Fatal(err)
}
var monitor SiteMonitor
for _, m := range monitors {
if m.ID == createResp.ID {
monitor = m
}
}
if monitor.ID == "" {
t.Fatal("couldnt find newly created site monitor")
}
if createResp.ID != monitor.ID {
t.Fail()
}
if createResp.URL != monitor.URL {
t.Fail()
}
if createResp.Share != monitor.Share {
t.Fail()
}
err = sc.UpdateSiteMonitor(corp, site, createResp.ID, UpdateSiteMonitorBody{
ID: createResp.ID,
Share: false,
})
if err != nil {
t.Fatal(err)
}
monitors2, err := sc.GetSiteMonitor(corp, site, createResp.ID)
if err != nil {
t.Fatal(err)
}
var monitor2 SiteMonitor
for _, m := range monitors2 {
if m.ID == createResp.ID {
monitor2 = m
}
}
if monitor2.ID == "" {
t.Fatal("couldnt find newly created site monitor")
}
if createResp.ID != monitor2.ID {
t.Fail()
}
if createResp.URL != monitor2.URL {
t.Fail()
}
if monitor2.Share != false {
t.Fail()
}
err = sc.DeleteSiteMonitor(corp, site, createResp.ID)
if err != nil {
t.Fatal(err)
}
}
func TestCRUDSiteMonitor(t *testing.T) {
sc := NewTokenClient(testcreds.email, testcreds.token)
corp := testcreds.corp
site := testcreds.site
createResp, err := sc.GenerateSiteMonitor(corp, site)
if err != nil {
t.Fatal(err)
}
monitors, err := sc.GetSiteMonitor(corp, site, createResp.ID)
if err != nil {
t.Fatal(err)
}
var monitor SiteMonitor
for _, m := range monitors {
if m.ID == createResp.ID {
monitor = m
}
}
if monitor.ID == "" {
t.Fatal("couldnt find newly created site monitor")
}
if createResp.ID != monitor.ID {
t.Fail()
}
if createResp.URL != monitor.URL {
t.Fail()
}
if createResp.Share != monitor.Share {
t.Fail()
}
err = sc.UpdateSiteMonitor(corp, site, createResp.ID, UpdateSiteMonitorBody{
ID: createResp.ID,
Share: false,
})
if err != nil {
t.Fatal(err)
}
monitors2, err := sc.GetSiteMonitor(corp, site, createResp.ID)
if err != nil {
t.Fatal(err)
}
var monitor2 SiteMonitor
for _, m := range monitors2 {
if m.ID == createResp.ID {
monitor2 = m
}
}
if monitor2.ID == "" {
t.Fatal("couldnt find newly created site monitor")
}
if createResp.ID != monitor2.ID {
t.Fail()
}
if createResp.URL != monitor2.URL {
t.Fail()
}
if monitor2.Share != false {
t.Fail()
}
err = sc.DeleteSiteMonitor(corp, site, createResp.ID)
if err != nil {
t.Fatal(err)
}
}
|
// Copyright 2015 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
// 2015 Petar Maymounkov <p@gocircuit.org>
package pool
import (
"github.com/gocircuit/runtime/sys"
"github.com/gocircuit/runtime/sys/pipe"
"time"
)
// Peer is a sys.Peer with pooling and caching of physical connections and
// multiplexed logical connections over physical ones.
type Peer struct {
u *pipe.Peer
ach chan *conn
pool *pool
}
func New(u sys.Peer) *Peer {
p := &Peer{
u: pipe.New(u),
ach: make(chan *conn, 1),
pool: newPool(),
}
go p.accept()
return p
}
func (p *Peer) Addr() sys.Addr {
return p.u.Addr()
}
func (p *Peer) accept() {
for {
c, err := p.u.Accept()
if err != nil {
panic(err)
}
go func() {
defer c.Close()
for {
q, err := c.Accept()
if err != nil {
return
}
p.ach <- newConn(q, c.Addr())
}
}()
}
}
func (p *Peer) Accept() (sys.Conn, error) {
c, ok := <-p.ach
if !ok {
panic(1)
}
return c, nil
}
func (p *Peer) Dial(addr sys.Addr) (r sys.Conn, err error) {
c := p.pool.Get(addr)
for i := 0; i < 2; i++ {
if c == nil { // Create new physical connection
if c, err = p.u.Dial(addr); err != nil {
return nil, err
}
go p.expire(addr, c)
p.pool.Add(addr, c)
}
if r, err = c.Dial(); err != nil { // Create logic pipe connection
c.Close()
p.pool.Remove(addr, c)
continue // If the physical connection is broken, re-attempt once
}
return newConn(r, addr), nil
}
return nil, err
}
func (p *Peer) expire(addr sys.Addr, c *pipe.Conn) {
for {
time.Sleep(time.Second * 10)
if p.pool.RemoveIfUnused(addr, c) {
return
}
}
}
|
package testbed
import (
"context"
"errors"
"fmt"
"os"
"sort"
"strings"
"testing"
"github.com/favclip/testerator/v3"
_ "github.com/favclip/testerator/v3/datastore"
_ "github.com/favclip/testerator/v3/memcache"
netcontext "golang.org/x/net/context"
"google.golang.org/appengine/v2"
"google.golang.org/appengine/v2/datastore"
)
type AEDatastoreStruct struct {
Test string
}
func TestMain(m *testing.M) {
_, _, err := testerator.SpinUp()
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
os.Exit(1)
}
status := m.Run()
err = testerator.SpinDown()
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
os.Exit(1)
}
os.Exit(status)
}
func newContext() (context.Context, func(), error) {
_, ctx, err := testerator.SpinUp()
if err != nil {
return nil, nil, err
}
return ctx, func() { testerator.SpinDown() }, nil
}
func TestAEDatastore_Put(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
key := datastore.NewIncompleteKey(ctx, "AEDatastoreStruct", nil)
key, err = datastore.Put(ctx, key, &AEDatastoreStruct{"Hi!"})
if err != nil {
t.Fatal(err.Error())
}
t.Logf("key: %s", key.String())
}
func TestAEDatastore_GetMulti(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Str string
}
key1, err := datastore.Put(ctx, datastore.NewKey(ctx, "Data", "", 1, nil), &Data{"Data1"})
if err != nil {
t.Fatal(err.Error())
}
key2, err := datastore.Put(ctx, datastore.NewKey(ctx, "Data", "", 2, nil), &Data{"Data2"})
if err != nil {
t.Fatal(err.Error())
}
list := make([]*Data, 2)
err = datastore.GetMulti(ctx, []*datastore.Key{key1, key2}, list)
if err != nil {
t.Fatal(err.Error())
}
if v := len(list); v != 2 {
t.Fatalf("unexpected: %v", v)
}
}
func TestAEDatastore_Transaction(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
key := datastore.NewIncompleteKey(ctx, "AEDatastoreStruct", nil)
key, err = datastore.Put(ctx, key, &AEDatastoreStruct{"Hi!"})
if err != nil {
t.Fatal(err.Error())
}
newTransaction := func(ctx context.Context) (context.Context, func() error, func() error) {
if ctx == nil {
t.Fatal("context is not coming")
}
ctxC := make(chan context.Context)
type transaction struct {
commit bool
rollback bool
}
finishC := make(chan transaction)
resultC := make(chan error)
commit := func() error {
finishC <- transaction{commit: true}
return <-resultC
}
rollback := func() error {
finishC <- transaction{rollback: true}
return <-resultC
}
rollbackErr := errors.New("rollback requested")
go func() {
err := datastore.RunInTransaction(ctx, func(ctx netcontext.Context) error {
t.Logf("into datastore.RunInTransaction")
ctxC <- ctx
t.Logf("send context")
result, ok := <-finishC
t.Logf("receive action: %v, %+v", ok, result)
if !ok {
return errors.New("channel closed")
}
if result.commit {
return nil
} else if result.rollback {
return rollbackErr
}
panic("unexpected state")
}, &datastore.TransactionOptions{XG: true})
if err == rollbackErr {
// This is intended error
err = nil
}
resultC <- err
}()
ctx = <-ctxC
return ctx, commit, rollback
}
{ // Commit
txCtx, commit, _ := newTransaction(ctx)
s := &AEDatastoreStruct{}
err = datastore.Get(txCtx, key, s)
if err != nil {
t.Fatal(err.Error())
}
s.Test = "Updated 1"
_, err := datastore.Put(txCtx, key, s)
if err != nil {
t.Fatal(err.Error())
}
err = commit()
if err != nil {
t.Fatal(err.Error())
}
// should updated
newS := &AEDatastoreStruct{}
err = datastore.Get(ctx, key, newS)
if err != nil {
t.Fatal(err.Error())
}
if v := newS.Test; v != "Updated 1" {
t.Fatalf("unexpected: %+v", v)
}
}
{ // Rollback
txCtx, _, rollback := newTransaction(ctx)
s := &AEDatastoreStruct{}
err = datastore.Get(txCtx, key, s)
if err != nil {
t.Fatal(err.Error())
}
s.Test = "Updated 2"
_, err := datastore.Put(txCtx, key, s)
if err != nil {
t.Fatal(err.Error())
}
err = rollback()
if err != nil {
t.Fatal(err.Error())
}
// should not updated
newS := &AEDatastoreStruct{}
err = datastore.Get(ctx, key, newS)
if err != nil {
t.Fatal(err.Error())
}
if v := newS.Test; v != "Updated 1" {
t.Fatalf("unexpected: %+v", v)
}
}
t.Logf("key: %s", key.String())
}
func TestAEDatastore_TransactionDeleteAndGet(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Str string
}
key, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Data", nil), &Data{"Data"})
if err != nil {
t.Fatal(err.Error())
}
err = datastore.RunInTransaction(ctx, func(ctx netcontext.Context) error {
err := datastore.Delete(ctx, key)
if err != nil {
return err
}
obj := &Data{}
err = datastore.Get(ctx, key, obj)
if err != nil {
t.Fatalf("unexpected: %v", err)
}
return nil
}, nil)
if err != nil {
t.Fatal(err.Error())
}
}
func TestAEDatastore_Query(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Str string
}
_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Data", nil), &Data{"Data1"})
if err != nil {
t.Fatal(err.Error())
}
_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Data", nil), &Data{"Data2"})
if err != nil {
t.Fatal(err.Error())
}
q := datastore.NewQuery("Data").Filter("Str =", "Data2")
{
var list []*Data
_, err = q.GetAll(ctx, &list)
if err != nil {
t.Fatal(err.Error())
}
if v := len(list); v != 1 {
t.Fatalf("unexpected: %v", v)
}
}
{
keys, err := q.KeysOnly().GetAll(ctx, nil)
if err != nil {
t.Fatal(err.Error())
}
if v := len(keys); v != 1 {
t.Fatalf("unexpected: %v", v)
}
}
}
func TestAEDatastore_QueryCursor(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Str string
}
{
var keys []*datastore.Key
var entities []*Data
for i := 0; i < 100; i++ {
keys = append(keys, datastore.NewIncompleteKey(ctx, "Data", nil))
entities = append(entities, &Data{Str: fmt.Sprintf("#%d", i+1)})
}
_, err = datastore.PutMulti(ctx, keys, entities)
if err != nil {
t.Fatal(err)
}
}
var cur datastore.Cursor
var dataList []*Data
const limit = 3
outer:
for {
q := datastore.NewQuery("Data").Order("Str").Limit(limit)
if cur.String() != "" {
q = q.Start(cur)
}
it := q.Run(ctx)
count := 0
for {
obj := &Data{}
_, err := it.Next(obj)
if err == datastore.Done {
break
} else if err != nil {
t.Fatal(err)
}
dataList = append(dataList, obj)
count++
}
if count != limit {
break
}
cur, err = it.Cursor()
if err != nil {
t.Fatal(err)
}
if cur.String() == "" {
break outer
}
}
if v := len(dataList); v != 100 {
t.Errorf("unexpected: %v", v)
}
}
func TestAEDatastore_ErrConcurrentTransaction(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Str string
}
key := datastore.NewKey(ctx, "Data", "a", 0, nil)
_, err = datastore.Put(ctx, key, &Data{})
if err != nil {
t.Fatal(err)
}
// ErrConcurrentTransaction will be occur
err = datastore.RunInTransaction(ctx, func(txCtx1 netcontext.Context) error {
err := datastore.Get(txCtx1, key, &Data{})
if err != nil {
return err
}
err = datastore.RunInTransaction(ctx, func(txCtx2 netcontext.Context) error {
err := datastore.Get(txCtx2, key, &Data{})
if err != nil {
return err
}
_, err = datastore.Put(txCtx2, key, &Data{Str: "#2"})
return err
}, &datastore.TransactionOptions{XG: true})
if err != nil {
return err
}
_, err = datastore.Put(txCtx1, key, &Data{Str: "#1"})
return err
}, &datastore.TransactionOptions{XG: true})
if err != datastore.ErrConcurrentTransaction {
t.Fatal(err)
}
}
func TestAEDatastore_ObjectHasObjectSlice(t *testing.T) {
type Inner struct {
A string
B string
}
type Data struct {
Slice []Inner
}
ps, err := datastore.SaveStruct(&Data{
Slice: []Inner{
{A: "A1", B: "B1"},
{A: "A2", B: "B2"},
{A: "A3", B: "B3"},
},
})
if err != nil {
t.Fatal(err)
}
if v := len(ps); v != 6 {
t.Fatalf("unexpected: %v", v)
}
sort.SliceStable(ps, func(i, j int) bool {
a := ps[i]
b := ps[j]
if v := strings.Compare(a.Name, b.Name); v < 0 {
return true
}
if v := strings.Compare(a.Value.(string), b.Value.(string)); v < 0 {
return true
}
return false
})
expects := []struct {
Name string
Value string
Multiple bool
}{
{"Slice.A", "A1", true},
{"Slice.A", "A2", true},
{"Slice.A", "A3", true},
{"Slice.B", "B1", true},
{"Slice.B", "B2", true},
{"Slice.B", "B3", true},
}
for idx, expect := range expects {
t.Logf("idx: %d", idx)
p := ps[idx]
if v := p.Name; v != expect.Name {
t.Errorf("unexpected: %v", v)
}
if v := p.Value.(string); v != expect.Value {
t.Errorf("unexpected: %v", v)
}
if v := p.Multiple; v != expect.Multiple {
t.Errorf("unexpected: %v", v)
}
}
}
func TestAEDatastore_GeoPoint(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
A appengine.GeoPoint
// B *appengine.GeoPoint
C []appengine.GeoPoint
// D []*appengine.GeoPoint
}
obj := &Data{
A: appengine.GeoPoint{Lat: 1.1, Lng: 2.2},
// B: &appengine.GeoPoint{3.3, 4.4},
C: []appengine.GeoPoint{
{Lat: 5.5, Lng: 6.6},
{Lat: 7.7, Lng: 8.8},
},
/*
D: []*appengine.GeoPoint{
{9.9, 10.10},
{11.11, 12.12},
},
*/
}
key, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Data", nil), obj)
if err != nil {
t.Fatal(err)
}
obj = &Data{}
err = datastore.Get(ctx, key, obj)
if err != nil {
t.Fatal(err)
}
if v := obj.A.Lat; v != 1.1 {
t.Errorf("unexpected: %v", v)
}
if v := obj.A.Lng; v != 2.2 {
t.Errorf("unexpected: %v", v)
}
if v := len(obj.C); v != 2 {
t.Fatalf("unexpected: %v", v)
}
if v := obj.C[0].Lat; v != 5.5 {
t.Errorf("unexpected: %v", v)
}
if v := obj.C[0].Lng; v != 6.6 {
t.Errorf("unexpected: %v", v)
}
if v := obj.C[1].Lat; v != 7.7 {
t.Errorf("unexpected: %v", v)
}
if v := obj.C[1].Lng; v != 8.8 {
t.Errorf("unexpected: %v", v)
}
}
func TestAEDatastore_PutInterface(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
var e EntityInterface = &PutInterfaceTest{}
key := datastore.NewIncompleteKey(ctx, "Test", nil)
_, err = datastore.Put(ctx, key, e)
if err != nil {
t.Fatal(err)
}
}
func TestAEDatastore_PutAndGetPropertyList(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
var ps datastore.PropertyList
ps = append(ps, datastore.Property{
Name: "A",
Value: "A-Value",
})
ps = append(ps, datastore.Property{
Name: "B",
Value: true,
})
key := datastore.NewIncompleteKey(ctx, "Test", nil)
// passed datastore.PropertyList, would be error.
_, err = datastore.Put(ctx, key, ps)
if err != datastore.ErrInvalidEntityType {
t.Fatal(err)
}
// ok!
key, err = datastore.Put(ctx, key, &ps)
if err != nil {
t.Fatal(err)
}
// passed datastore.PropertyList, would be error.
ps = datastore.PropertyList{}
err = datastore.Get(ctx, key, ps)
if err != datastore.ErrInvalidEntityType {
t.Fatal(err)
}
// ok!
ps = datastore.PropertyList{}
err = datastore.Get(ctx, key, &ps)
if err != nil {
t.Fatal(err)
}
if v := len(ps); v != 2 {
t.Fatalf("unexpected: %v", v)
}
}
func TestAEDatastore_PutAndGetMultiPropertyListSlice(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
var pss []datastore.PropertyList
var keys []*datastore.Key
{
var ps datastore.PropertyList
ps = append(ps, datastore.Property{
Name: "A",
Value: "A-Value",
})
ps = append(ps, datastore.Property{
Name: "B",
Value: true,
})
key := datastore.NewIncompleteKey(ctx, "Test", nil)
pss = append(pss, ps)
keys = append(keys, key)
}
// passed *[]datastore.PropertyList, would be error.
_, err = datastore.PutMulti(ctx, keys, &pss)
if err == nil {
t.Fatal(err)
}
// ok! []datastore.PropertyList
keys, err = datastore.PutMulti(ctx, keys, pss)
if err != nil {
t.Fatal(err)
}
// passed *[]datastore.PropertyList, would be error.
pss = []datastore.PropertyList{}
err = datastore.GetMulti(ctx, keys, &pss)
if err == nil {
t.Fatal(err)
}
// passed []datastore.PropertyList with length 0, would be error.
pss = make([]datastore.PropertyList, 0)
err = datastore.GetMulti(ctx, keys, pss)
if err == nil {
t.Fatal(err)
}
// ok! []datastore.PropertyList with length == len(keys)
pss = make([]datastore.PropertyList, len(keys))
err = datastore.GetMulti(ctx, keys, pss)
if err != nil {
t.Fatal(err)
}
if v := len(pss); v != 1 {
t.Fatalf("unexpected: %v", v)
}
}
func TestAEDatastore_PutAndGetBareStruct(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Name string
}
key := datastore.NewIncompleteKey(ctx, "Test", nil)
// passed Data, would be error.
_, err = datastore.Put(ctx, key, Data{Name: "A"})
if err != datastore.ErrInvalidEntityType {
t.Fatal(err)
}
// ok! *Data
key, err = datastore.Put(ctx, key, &Data{Name: "A"})
if err != nil {
t.Fatal(err)
}
// ok! but struct are copied. can't watching Get result.
obj := Data{}
err = datastore.Get(ctx, key, obj)
if err != datastore.ErrInvalidEntityType {
t.Fatal(err)
}
if v := obj.Name; v != "" {
t.Errorf("unexpected: '%v'", v)
}
}
func TestAEDatastore_PutAndGetMultiBareStruct(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Name string
}
var list []Data
var keys []*datastore.Key
{
obj := Data{Name: "A"}
key := datastore.NewIncompleteKey(ctx, "Test", nil)
list = append(list, obj)
keys = append(keys, key)
}
// ok!
keys, err = datastore.PutMulti(ctx, keys, list)
if err != nil {
t.Fatal(err)
}
// passed []Data with length 0, would be error.
list = make([]Data, 0)
err = datastore.GetMulti(ctx, keys, list)
if err == nil {
t.Fatal(err)
}
// ok! []Data with length == len(keys)
list = make([]Data, len(keys))
err = datastore.GetMulti(ctx, keys, list)
if err != nil {
t.Fatal(err)
}
if v := len(list); v != 1 {
t.Fatalf("unexpected: '%v'", v)
}
if v := list[0].Name; v != "A" {
t.Errorf("unexpected: '%v'", v)
}
}
func TestAEDatastore_PutAndGetStringSynonym(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Email string
type Data struct {
Email Email
}
key, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Data", nil), &Data{Email: "test@example.com"})
if err != nil {
t.Fatal(err)
}
obj := &Data{}
err = datastore.Get(ctx, key, obj)
if err != nil {
t.Fatal(err)
}
if v := obj.Email; v != "test@example.com" {
t.Errorf("unexpected: '%v'", v)
}
}
func TestAEDatastore_QueryNextByPropertyList(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Name string
}
_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Data", nil), &Data{Name: "A"})
if err != nil {
t.Fatal(err)
}
q := datastore.NewQuery("Data")
{ // passed datastore.PropertyList, would be error.
iter := q.Run(ctx)
var ps datastore.PropertyList
_, err = iter.Next(ps)
if err == nil {
t.Fatal(err)
}
}
{ // ok! *datastore.PropertyList
iter := q.Run(ctx)
var ps datastore.PropertyList
_, err = iter.Next(&ps)
if err != nil {
t.Fatal(err)
}
}
}
func TestAEDatastore_GetAllByPropertyListSlice(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Name string
}
_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Data", nil), &Data{Name: "A"})
if err != nil {
t.Fatal(err)
}
q := datastore.NewQuery("Data")
var psList []datastore.PropertyList
// passed []datastore.PropertyList, would be error.
_, err = q.GetAll(ctx, psList)
if err == nil {
t.Fatal(err)
}
// ok! *[]datastore.PropertyList
psList = nil
_, err = q.GetAll(ctx, &psList)
if err != nil {
t.Fatal(err)
}
}
func TestAEDatastore_Namespace(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type Data struct {
Name string
}
nsCtx, err := appengine.Namespace(ctx, "no1")
if err != nil {
t.Fatal(err)
}
key := datastore.NewKey(nsCtx, "Test", "", 1, nil)
if v := key.String(); v != "/Test,1" {
t.Fatalf("unexpected: %v", v)
}
vanillaKey := datastore.NewKey(ctx, "Test", "", 1, nil)
if v := vanillaKey.String(); v != "/Test,1" {
t.Fatalf("unexpected: %v", v)
}
_, err = datastore.Put(ctx, key, &Data{"Name #1"})
if err != nil {
t.Fatal(err)
}
err = datastore.Get(ctx, vanillaKey, &Data{})
if err != datastore.ErrNoSuchEntity {
t.Fatal(err)
}
err = datastore.Get(ctx, key, &Data{})
if err != nil {
t.Fatal(err)
}
q := datastore.NewQuery("Test")
q = q.KeysOnly()
var keys []*datastore.Key
keys, err = q.GetAll(ctx, nil)
if err != nil {
t.Fatal(err)
}
if v := len(keys); v != 0 {
t.Fatalf("unexpected: %v", v)
}
keys, err = q.GetAll(nsCtx, nil)
if err != nil {
t.Fatal(err)
}
if v := len(keys); v != 1 {
t.Fatalf("unexpected: %v", v)
}
}
func TestAEDatastore_KindlessQueryWithAncestor(t *testing.T) {
ctx, close, err := newContext()
if err != nil {
t.Fatal(err)
}
defer close()
type A struct {
A string
}
type B struct {
B int
}
ancestorKey := datastore.NewKey(ctx, "Ancestor", "foo", 0, nil)
_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "A", ancestorKey), &A{A: "1"})
if err != nil {
t.Fatal(err)
}
_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "A", ancestorKey), &A{A: "1"})
if err != nil {
t.Fatal(err)
}
_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "B", ancestorKey), &B{B: 1})
if err != nil {
t.Fatal(err)
}
_, err = datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "B", ancestorKey), &B{B: 1})
if err != nil {
t.Fatal(err)
}
var pss []datastore.PropertyList
keys, err := datastore.NewQuery("").Ancestor(ancestorKey).GetAll(ctx, &pss)
if err != nil {
t.Fatal(err)
}
if v := len(keys); v != 4 {
t.Fatalf("unexpected: %v", v)
}
if v := len(pss); v != 4 {
t.Fatalf("unexpected: %v", v)
}
}
|
// Copyright (c) 2020 Xiaozhe Yao & AICAMP.CO.,LTD
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package runtime
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"path"
"path/filepath"
"github.com/autoai-org/aid/components/cmd/pkg/entities"
"github.com/autoai-org/aid/components/cmd/pkg/utilities"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/term"
"github.com/docker/go-connections/nat"
"github.com/logrusorgru/aurora"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
var logger = utilities.NewDefaultLogger()
var defaultDockerRuntime *DockerRuntime
// DockerRuntime is the basic class for manage docker
type DockerRuntime struct {
client *client.Client
}
// prepareEnvs returns a list of string
func prepareEnvs(imageID string) []string {
reqPackage := entities.GetPackageByImageID(imageID)
envs := entities.GetEnvironmentVariablesbyPackageID(reqPackage.ID, "all")
envStrings := entities.MergeEnvironmentVariables(envs)
serverIP := utilities.GetOutboundIP().String()
systemenv := []string{"AID_SERVER", serverIP + ":10590"}
envStrings = append(envStrings, systemenv...)
return envStrings
}
// prepareVolumes returns a map of volume mappings
func prepareVolumes(hostPath string) map[string]struct{} {
vol := map[string]struct{}{hostPath + ":/package": {}}
return vol
}
// NewDockerRuntime returns a DockerRuntime Instance
func NewDockerRuntime() *DockerRuntime {
if defaultDockerRuntime != nil {
return defaultDockerRuntime
}
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
utilities.CheckError(err, "Cannot Create New Docker Runtime")
}
return &DockerRuntime{
client: cli,
}
}
// Pull will pull an exisiting package
func (docker *DockerRuntime) Pull(imageName string) error {
reader, err := docker.client.ImagePull(context.Background(), imageName, types.ImagePullOptions{})
if err != nil {
utilities.CheckError(err, "Cannot pull image "+imageName)
return err
}
io.Copy(os.Stdout, reader)
return nil
}
// Create will create a container from an image
func (docker *DockerRuntime) Create(imageID string, hostPort string) (container.ContainerCreateCreatedBody, error) {
image := entities.GetImage(imageID)
hostConfig := &container.HostConfig{
PortBindings: nat.PortMap{
"8080/tcp": []nat.PortBinding{
{
HostIP: "0.0.0.0",
HostPort: hostPort,
},
},
},
}
resp, err := docker.client.ContainerCreate(context.Background(), &container.Config{
Image: image.Name,
Tty: true,
ExposedPorts: nat.PortSet{
"8080/tcp": struct{}{},
},
Env: prepareEnvs(image.ID),
}, hostConfig, nil, "")
if err != nil {
utilities.CheckError(err, "Cannot create container from image "+image.Name)
return resp, err
}
container := entities.Container{ID: resp.ID, ImageID: imageID}
container.Save()
runningSolver := entities.RunningSolver{ContainerID: resp.ID, Status: "Ready", EntryPoint: "127.0.0.1:" + hostPort}
runningSolver.Save()
return resp, err
}
// Start will start a container
func (docker *DockerRuntime) Start(containerID string) error {
container := entities.GetContainer(containerID)
runningSolvers := entities.RunningSolver{ContainerID: container.ID, Status: "Running"}
runningSolvers.Save()
if err := docker.client.ContainerStart(context.Background(), containerID, types.ContainerStartOptions{}); err != nil {
utilities.CheckError(err, "Cannot start container "+containerID)
return err
}
return nil
}
func getBuildCtx(solverPath string) io.Reader {
ctx, _ := archive.TarWithOptions(solverPath, &archive.TarOptions{})
return ctx
}
func realBuild(docker *DockerRuntime, dockerfile string, imageName string, buildLogger *logrus.Logger) error {
if !utilities.IsFileExists(dockerfile) {
utilities.Formatter.Warning("Dockerfile Not Found, AID will generate it for you.")
GenerateDockerFiles(filepath.Dir(dockerfile))
tomlFilePath := filepath.Join(filepath.Dir(dockerfile), "aid.toml")
aidToml, err := utilities.ReadFileContent(tomlFilePath)
if err != nil {
utilities.CheckError(err, "Cannot open file "+tomlFilePath)
}
solvers := entities.LoadSolversFromConfig(aidToml)
RenderRunnerTpl(filepath.Dir(dockerfile), solvers)
}
buildResponse, err := docker.client.ImageBuild(context.Background(), getBuildCtx(path.Dir(dockerfile)), types.ImageBuildOptions{
Tags: []string{imageName},
Dockerfile: filepath.Base(dockerfile),
Remove: true,
})
if err != nil {
utilities.CheckError(err, "Cannot build image "+imageName)
buildLogger.Error("Cannot build image " + imageName)
buildLogger.Error(err.Error())
}
// set logs to build logs
reader := buildResponse.Body
defer reader.Close()
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
var buildLog entities.BuildLog
json.Unmarshal(scanner.Bytes(), &buildLog)
buildLogger.Info(buildLog.Stream)
}
termFd, isTerm := term.GetFdInfo(os.Stderr)
err = jsonmessage.DisplayJSONMessagesStream(buildResponse.Body, os.Stderr, termFd, isTerm, nil)
if err != nil {
buildLogger.Error("Cannot show log from " + imageName)
buildLogger.Error(err.Error())
}
return err
}
// Build will build a new image from dockerfile
func (docker *DockerRuntime) Build(imageName string, dockerfile string) (entities.Log, error) {
var err error
nextCount := entities.GetNextImageNumber()
fullImageName := "aid-" + nextCount + "-" + imageName
logger.Info("Starting Build Image: " + fullImageName + "...")
logid := utilities.GenerateUUIDv4()
var logPath = filepath.Join(utilities.GetBasePath(), "logs", "builds", imageName+"."+logid)
log := entities.NewLogObject("build-"+fullImageName, logPath, "docker-build")
log.ID = logid
log.Save()
buildLogger := utilities.NewLogger(logPath)
err = realBuild(docker, dockerfile, fullImageName, buildLogger)
if err == nil {
// no error occured, add image to database
image := entities.Image{Name: fullImageName}
image.Save()
ibe := entities.ImageBuiltEvent{ImageName: fullImageName}
entities.Consume(ibe)
}
return log, err
}
// ListImages returns all images that have been installed on the host
func (docker *DockerRuntime) ListImages() []types.ImageSummary {
images, err := docker.client.ImageList(context.Background(), types.ImageListOptions{})
if err != nil {
logger.Error("Cannot List Images")
logger.Error(err.Error())
}
return images
}
// ListContainers returns all containers that have been built.
func (docker *DockerRuntime) ListContainers() []types.Container {
containers, err := docker.client.ContainerList(context.Background(), types.ContainerListOptions{
All: true,
})
if err != nil {
logger.Error("Cannot List Images")
logger.Error(err.Error())
}
return containers
}
// GenerateDockerFiles returns a DockerFile string that could be used to build image.
func GenerateDockerFiles(baseFilePath string) {
configFile := filepath.Join(baseFilePath, "aid.toml")
tomlString, err := utilities.ReadFileContent(configFile)
if err != nil {
utilities.CheckError(err, "cannot open file "+configFile)
}
packageInfo := entities.LoadPackageFromConfig(tomlString)
for _, solver := range packageInfo.Solvers {
RenderDockerfile(solver.Name, baseFilePath)
}
}
// FetchContainerLogs returns the logs in the container
func (docker *DockerRuntime) FetchContainerLogs(containerID string) entities.Log {
var logPath = filepath.Join(utilities.GetBasePath(), "logs", "container", containerID)
log := entities.NewLogObject("container-"+containerID, logPath, "container-log")
log.Save()
logger := utilities.NewLogger(logPath)
reader, err := docker.client.ContainerLogs(context.Background(), containerID, types.ContainerLogsOptions{
ShowStderr: true,
ShowStdout: true,
Timestamps: false,
Follow: true,
Tail: "40",
})
if err != nil {
utilities.CheckError(err, "Cannot establish error log reader")
}
defer reader.Close()
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
logger.Info(scanner.Text())
}
return log
}
// ExportImage save image into dest, for uploading to other nodes, etc.
// Before calling export, we should ask users if they want to overwrite existing file.
func (docker *DockerRuntime) ExportImage(imageName string) error {
targetFile := filepath.Join(utilities.GetBasePath(), "temp", imageName+".aidimg")
fmt.Printf("%s Exporting your image to %s\n", aurora.Cyan("progress"), targetFile)
// Delete existing file
if utilities.IsExists(targetFile) {
err := os.Remove(targetFile)
utilities.CheckError(err, "Cannot remove existing file "+targetFile)
}
file, err := os.Create(targetFile)
if err != nil {
utilities.CheckError(err, "Cannot create new image file at "+targetFile)
return err
}
defer file.Close()
resBody, err := docker.client.ImageSave(context.Background(), []string{imageName})
_, err = io.Copy(file, resBody)
if err != nil {
utilities.CheckError(err, "Cannot write to the file: "+targetFile)
return err
}
utilities.Formatter.Success("exported your image to " + targetFile)
return nil
}
// ImportImage reads images into docker runtime
func (docker *DockerRuntime) ImportImage(imageName string, quiet bool) error {
targetFile := filepath.Join(utilities.GetBasePath(), "temp", imageName+".aidimg")
fmt.Printf("%s Importing your image from %s\n", aurora.Cyan("progress"), targetFile)
_, err := os.Stat(targetFile)
if os.IsNotExist(err) {
utilities.CheckError(err, "Cannot read the file: "+targetFile)
return err
}
file, err := os.Open(targetFile)
if err != nil {
utilities.CheckError(err, "Cannot open the file: "+targetFile)
}
reader := bufio.NewReader(file)
_, err = docker.client.ImageLoad(context.Background(), reader, quiet)
if err != nil {
utilities.CheckError(err, "Cannot import image from "+targetFile)
return err
}
fmt.Printf("imported your image from " + targetFile)
return nil
}
|
package ardupilotmega
/*
Generated using mavgen - https://github.com/ArduPilot/pymavlink/
Copyright 2020 queue-b <https://github.com/queue-b>
Permission is hereby granted, free of charge, to any person obtaining a copy
of the generated software (the "Generated Software"), to deal
in the Generated Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Generated Software, and to permit persons to whom the Generated
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Generated Software.
THE GENERATED SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE GENERATED SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE GENERATED SOFTWARE.
*/
import (
"bytes"
"encoding/binary"
"fmt"
"text/tabwriter"
"github.com/queue-b/go-mavlink2"
"github.com/queue-b/go-mavlink2/util"
)
/*SensorOffsets Offsets and calibrations values for hardware sensors. This makes it easier to debug the calibration process. */
type SensorOffsets struct {
/*MagDeclination Magnetic declination. */
MagDeclination float32
/*RawPress Raw pressure from barometer. */
RawPress int32
/*RawTemp Raw temperature from barometer. */
RawTemp int32
/*GyroCalX Gyro X calibration. */
GyroCalX float32
/*GyroCalY Gyro Y calibration. */
GyroCalY float32
/*GyroCalZ Gyro Z calibration. */
GyroCalZ float32
/*AccelCalX Accel X calibration. */
AccelCalX float32
/*AccelCalY Accel Y calibration. */
AccelCalY float32
/*AccelCalZ Accel Z calibration. */
AccelCalZ float32
/*MagOfsX Magnetometer X offset. */
MagOfsX int16
/*MagOfsY Magnetometer Y offset. */
MagOfsY int16
/*MagOfsZ Magnetometer Z offset. */
MagOfsZ int16
/*HasExtensionFieldValues indicates if this message has any extensions and */
HasExtensionFieldValues bool
}
func (m *SensorOffsets) String() string {
format := ""
var buffer bytes.Buffer
writer := tabwriter.NewWriter(&buffer, 0, 0, 2, ' ', 0)
format += "Name:\t%v/%v\n"
// Output field values based on the decoded message type
format += "MagDeclination:\t%v [rad]\n"
format += "RawPress:\t%v \n"
format += "RawTemp:\t%v \n"
format += "GyroCalX:\t%v \n"
format += "GyroCalY:\t%v \n"
format += "GyroCalZ:\t%v \n"
format += "AccelCalX:\t%v \n"
format += "AccelCalY:\t%v \n"
format += "AccelCalZ:\t%v \n"
format += "MagOfsX:\t%v \n"
format += "MagOfsY:\t%v \n"
format += "MagOfsZ:\t%v \n"
fmt.Fprintf(
writer,
format,
m.GetDialect(),
m.GetMessageName(),
m.MagDeclination,
m.RawPress,
m.RawTemp,
m.GyroCalX,
m.GyroCalY,
m.GyroCalZ,
m.AccelCalX,
m.AccelCalY,
m.AccelCalZ,
m.MagOfsX,
m.MagOfsY,
m.MagOfsZ,
)
writer.Flush()
return string(buffer.Bytes())
}
// GetVersion gets the MAVLink version of the Message contents
func (m *SensorOffsets) GetVersion() int {
if m.HasExtensionFieldValues {
return 2
}
return 1
}
// GetDialect gets the name of the dialect that defines the Message
func (m *SensorOffsets) GetDialect() string {
return "ardupilotmega"
}
// GetMessageName gets the name of the Message
func (m *SensorOffsets) GetMessageName() string {
return "SensorOffsets"
}
// GetID gets the ID of the Message
func (m *SensorOffsets) GetID() uint32 {
return 150
}
// HasExtensionFields returns true if the message definition contained extensions; false otherwise
func (m *SensorOffsets) HasExtensionFields() bool {
return false
}
func (m *SensorOffsets) getV1Length() int {
return 42
}
func (m *SensorOffsets) getIOSlice() []byte {
return make([]byte, 42+1)
}
// Read sets the field values of the message from the raw message payload
func (m *SensorOffsets) Read(frame mavlink2.Frame) (err error) {
version := frame.GetVersion()
// Ensure only Version 1 or Version 2 were specified
if version != 1 && version != 2 {
err = mavlink2.ErrUnsupportedVersion
return
}
// Don't attempt to Read V2 messages from V1 frames
if m.GetID() > 255 && version < 2 {
err = mavlink2.ErrDecodeV2MessageV1Frame
return
}
// binary.Read can panic; swallow the panic and return a sane error
defer func() {
if r := recover(); r != nil {
err = mavlink2.ErrPrivateField
}
}()
// Get a slice of bytes long enough for the all the SensorOffsets fields
// binary.Read requires enough bytes in the reader to read all fields, even if
// the fields are just zero values. This also simplifies handling MAVLink2
// extensions and trailing zero truncation.
ioSlice := m.getIOSlice()
copy(ioSlice, frame.GetMessageBytes())
// Indicate if
if version == 2 && m.HasExtensionFields() {
ioSlice[len(ioSlice)-1] = 1
}
reader := bytes.NewReader(ioSlice)
err = binary.Read(reader, binary.LittleEndian, m)
return
}
// Write encodes the field values of the message to a byte array
func (m *SensorOffsets) Write(version int) (output []byte, err error) {
var buffer bytes.Buffer
// Ensure only Version 1 or Version 2 were specified
if version != 1 && version != 2 {
err = mavlink2.ErrUnsupportedVersion
return
}
// Don't attempt to Write V2 messages to V1 bodies
if m.GetID() > 255 && version < 2 {
err = mavlink2.ErrEncodeV2MessageV1Frame
return
}
err = binary.Write(&buffer, binary.LittleEndian, *m)
if err != nil {
return
}
output = buffer.Bytes()
// V1 uses fixed message lengths and does not include any extension fields
// Truncate the byte slice to the correct length
// This also removes the trailing extra byte written for HasExtensionFieldValues
if version == 1 {
output = output[:m.getV1Length()]
}
// V2 uses variable message lengths and includes extension fields
// The variable length is caused by truncating any trailing zeroes from
// the end of the message before it is added to a frame
if version == 2 {
// Set HasExtensionFieldValues to zero so that it doesn't interfere with V2 truncation
output[len(output)-1] = 0
output = util.TruncateV2(buffer.Bytes())
}
return
}
|
package main
import (
"context"
"fmt"
"os"
"os/signal"
"redisDB"
"omokServer"
)
func main() {
ctx, done := signal.NotifyContext(context.Background(), os.Interrupt)
defer done()
conf := createHostConf()
redisC := createRedis(conf)
redisC.Start()
omokServerList := make([]*omokServer.Server, conf.maxGameCount)
for i := 0; i < conf.maxGameCount; i++ {
omokServ := new(omokServer.Server)
omokServ.Init(conf.startTcpPort + i, conf.omokConf, redisC.ReqTaskChan)
omokServ.StartServer()
omokServerList[i] = omokServ
}
fmt.Println("Waiting for SIGINT.")
<-ctx.Done()
for i := 0; i < conf.maxGameCount; i++ {
omokServerList[i].Stop()
}
redisC.Stop()
fmt.Println("END")
}
func createRedis(hconf hostConf) *redisDB.Client {
conf := redisDB.Conf{
Address: hconf.RedisAddress,
PoolSize: hconf.RedisPoolSize,
ReqTaskChanCapacity: hconf.RedisReqTaskChanCapacity,
}
client := new(redisDB.Client)
client.Init(conf)
return client
} |
package main
import (
"fmt"
"github.com/rainmyy/easyDB/bootstrap"
)
/***
* easydb 服务端入库
*/
func main() {
bootstrap.GenInstance().Setup()
bootstrap.GenInstance().Start()
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
}
|
package common
import "sync"
//计数
var sum int64 = 0
// 互斥锁
var mutex sync.Mutex
//获取一个
func PassOne(hasNum int64) bool {
// 总数
//var hasNum int64
// 加锁
mutex.Lock()
defer mutex.Unlock()
// 判断是否超限
if sum < hasNum {
sum += 1
return true
}
return false
}
|
package prompt
import "strings"
const (
None = "none"
Login = "login"
Consent = "consent"
SelectAccount = "select_account"
)
type NoConsentPromptPolicy int
const (
NoConsentPromptPolicyForceConsent NoConsentPromptPolicy = iota
NoConsentPromptPolicyOmitConsentIfCan
)
type NonePromptPolicy int
const (
NonePromptPolicyForbidden NonePromptPolicy = iota
NonePromptPolicyAllowWithLoginSession
NonePromptPolicyAllowIfLoginHintMatched
NonePromptPolicyAllowIfIdTokenHintMatched
)
func Split(prompts string) []string {
return strings.Split(prompts, " ")
}
func IncludeAll(prompts string, targetPrompts []string) (bool, string) {
list := Split(prompts)
existanceMap := make(map[string]bool, 0)
for _, p := range list {
existanceMap[p] = true
}
for _, p := range targetPrompts {
if _, exists := existanceMap[p]; !exists {
return false, p
}
}
return true, ""
}
func Include(prompts string, target string) bool {
list := Split(prompts)
for _, s := range list {
if s == target {
return true
}
}
return false
}
func Validate(prompts string) bool {
list := Split(prompts)
hasNone := false
hasOther := false
for _, p := range list {
switch p {
case None:
hasNone = true
case Login:
hasOther = true
case Consent:
hasOther = true
case SelectAccount:
hasOther = true
default:
return false
}
}
if hasNone && hasOther {
return false
}
return true
}
func IncludeNone(prompts string) bool {
return Include(prompts, None)
}
func IncludeLogin(prompts string) bool {
return Include(prompts, Login)
}
func IncludeConsent(prompts string) bool {
return Include(prompts, Consent)
}
func IncludeSelectAccount(prompts string) bool {
return Include(prompts, SelectAccount)
}
|
package variant
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/fatih/structs"
"github.com/go-playground/validator"
"github.com/markus-azer/products-service/pkg/entity"
"github.com/markus-azer/products-service/pkg/product"
"github.com/sirupsen/logrus"
)
//Service service interface
type Service struct {
msgRepo MessagesRepository
storeRepo StoreRepository
productRepo product.StoreRepository
}
//NewService create new service
func NewService(msgR MessagesRepository, storeR StoreRepository, productR product.StoreRepository) *Service {
return &Service{
msgRepo: msgR,
storeRepo: storeR,
productRepo: productR,
}
}
//CreateVariantDTO new variant DTO
type CreateVariantDTO struct {
Product entity.ID `json:"product" validate:"required" structs:"product"`
SKU string `json:"sku,omitempty" validate:"omitempty" structs:"sku,omitempty"`
Quantity int `json:"quantity,omitempty" validate:"omitempty" structs:"quantity,omitempty"`
Price int `json:"price,omitempty" validate:"omitempty,min=1" structs:"price,omitempty"`
Image string `json:"image,omitempty" validate:"omitempty,uri" structs:"image,omitempty"`
Attributes map[string]string `json:"attributes" validate:"required" structs:"attributes"`
}
//Create new variant
func (s *Service) Create(createVariantDTO CreateVariantDTO) (*entity.ID, *int32, *entity.Error) {
//Validate DTOs, Terminate the Create process if the input is not valid
if err := validator.New().Struct(createVariantDTO); err != nil {
errs := entity.Error{Op: "Create", Kind: entity.ValidationFailed, ErrorMessage: "Provide valid Payload", Severity: logrus.InfoLevel}
for _, e := range err.(validator.ValidationErrors) {
errs.Errors = append(errs.Errors, entity.ErrorField{Field: e.Field(), Error: fmt.Sprint(e)})
}
return nil, nil, &errs
}
ID := entity.NewID()
Timestamp := time.Now()
//Loop through the struct to generate events and validate
errs := entity.Error{Op: "Create", Kind: entity.ValidationFailed, ErrorMessage: "Provide valid Payload", Severity: logrus.InfoLevel}
var messages []*entity.Message
var version entity.Version = 1
//Lower Case Attributes
for k, v := range createVariantDTO.Attributes {
delete(createVariantDTO.Attributes, k)
createVariantDTO.Attributes[strings.ToLower(k)] = strings.ToLower(v)
}
payload := make(map[string]interface{})
payload["product"] = createVariantDTO.Product
payload["attributes"] = createVariantDTO.Attributes
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_DRAFT_CREATED",
Version: version,
Payload: payload,
Timestamp: Timestamp},
)
fields := reflect.TypeOf(createVariantDTO)
values := reflect.ValueOf(createVariantDTO)
num := fields.NumField()
for i := 0; i < num; i++ {
fieldName := fields.Field(i).Name
field := fields.Field(i)
value := values.Field(i)
switch field.Name {
case "Product":
_, err := s.productRepo.FindOneByID(entity.ID(value.String()))
switch err {
case entity.ErrNotFound:
errs.Errors = append(errs.Errors, entity.ErrorField{Field: fieldName, Error: "Product with ID " + value.String() + " doesn't Exist"})
default:
if err != nil {
return nil, nil, &entity.Error{Op: "Create", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
}
case "Attributes":
duplicatedVariant, err := s.storeRepo.FindOneByAttribute(createVariantDTO.Product, createVariantDTO.Attributes)
if err != entity.ErrNotFound && err != nil {
return nil, nil, &entity.Error{Op: "Create", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
if duplicatedVariant != nil {
errs.Errors = append(errs.Errors, entity.ErrorField{Field: fieldName, Error: "Variant Attributes Duplication with ID " + string(duplicatedVariant.ID)})
}
if len(createVariantDTO.Attributes) > 3 {
errs.Errors = append(errs.Errors, entity.ErrorField{Field: fieldName, Error: "Max Attributes is 3"})
}
case "SKU":
if value.String() != "" {
version++
payload := make(map[string]interface{})
payload["sku"] = value.String()
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_SKU_UPDATED",
Version: version,
Payload: payload,
Timestamp: Timestamp})
}
case "Quantity":
if value.Int() != 0 {
version++
payload := make(map[string]interface{})
payload["quantity"] = value.Int()
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_QUANTITY_UPDATED",
Version: version,
Payload: payload,
Timestamp: Timestamp})
}
case "Price":
if value.Int() != 0 {
version++
payload := make(map[string]interface{})
payload["price"] = value.String()
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_PRICE_UPDATED",
Version: version,
Payload: payload,
Timestamp: Timestamp})
}
case "Image":
//TODO: check if image exist and add event to delete other image
if value.String() != "" {
version++
payload := make(map[string]interface{})
payload["image"] = value.String()
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_IMAGE_UPDATED",
Version: version,
Payload: payload,
Timestamp: Timestamp})
}
}
}
if len(errs.Errors) >= 1 {
return nil, nil, &errs
}
v := &entity.Variant{
ID: ID,
Version: version,
Product: createVariantDTO.Product,
SKU: createVariantDTO.SKU,
Quantity: createVariantDTO.Quantity,
Price: createVariantDTO.Price,
Image: createVariantDTO.Image,
Attributes: createVariantDTO.Attributes,
CreatedAt: Timestamp,
}
c := &entity.Command{AggregateID: string(ID), Type: "CreateVariant", Payload: structs.Map(createVariantDTO), Timestamp: Timestamp}
_, err := s.storeRepo.StoreCommand(c)
if err != nil {
return nil, nil, &entity.Error{Op: "Create", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
_, err = s.storeRepo.Create(v)
if err != nil {
return nil, nil, &entity.Error{Op: "Create", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
s.msgRepo.SendMessages(messages)
Version := int32(v.Version)
return &ID, &Version, nil
}
//UpdateVariantDTO update variant DTO
type UpdateVariantDTO struct {
SKU string `json:"sku,omitempty" validate:"omitempty" structs:"sku,omitempty"`
Quantity int `json:"quantity,omitempty" validate:"omitempty" structs:"quantity,omitempty"`
Price int `json:"price,omitempty" validate:"omitempty,min=1" structs:"price,omitempty"`
Image string `json:"image,omitempty" validate:"omitempty,uri" structs:"image,omitempty"`
}
//UpdateOne product
func (s *Service) UpdateOne(ID entity.ID, v int32, updateVariantDTO UpdateVariantDTO) (*int32, *entity.Error) {
//Validate DTOs, Terminate the Create process if the input is not valid
if err := validator.New().Struct(updateVariantDTO); err != nil {
errs := entity.Error{Op: "UpdateOne", Kind: entity.ValidationFailed, ErrorMessage: "Provide valid Payload", Severity: logrus.InfoLevel}
for _, e := range err.(validator.ValidationErrors) {
errs.Errors = append(errs.Errors, entity.ErrorField{Field: e.Field(), Error: fmt.Sprint(e)})
}
return nil, &errs
}
Timestamp := time.Now()
version := entity.Version(v)
variant, err := s.storeRepo.FindOneByID(ID)
switch err {
case entity.ErrNotFound:
return nil, &entity.Error{Op: "Update", Kind: entity.NotFound, ErrorMessage: entity.ErrorMessage("Variant with id " + string(ID) + " Not found"), Severity: logrus.InfoLevel}
default:
if err != nil {
return nil, &entity.Error{Op: "Update", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
}
if version != variant.Version {
return nil, &entity.Error{Op: "Update", Kind: entity.ConcurrentModification, ErrorMessage: entity.ErrorMessage("Version conflict"), Severity: logrus.InfoLevel}
}
//Loop through the struct to generate events and validate
errs := entity.Error{Op: "Create", Kind: entity.ValidationFailed, ErrorMessage: "Provide valid Payload", Severity: logrus.InfoLevel}
var messages []*entity.Message
fields := reflect.TypeOf(updateVariantDTO)
values := reflect.ValueOf(updateVariantDTO)
num := fields.NumField()
for i := 0; i < num; i++ {
fieldName := fields.Field(i).Name
field := fields.Field(i)
value := values.Field(i)
switch field.Name {
case "SKU":
if value.String() != "" {
if variant.SKU == updateVariantDTO.SKU {
errs.Errors = append(errs.Errors, entity.ErrorField{Field: fieldName, Error: "Sku already updated"})
}
version++
payload := make(map[string]interface{})
payload["sku"] = value.String()
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_SKU_UPDATED",
Version: version,
Payload: payload,
Timestamp: Timestamp})
}
case "Quantity":
if value.String() != "" {
if variant.Quantity == updateVariantDTO.Quantity {
errs.Errors = append(errs.Errors, entity.ErrorField{Field: fieldName, Error: "Quantity already updated"})
}
version++
payload := make(map[string]interface{})
payload["quantity"] = value.String()
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_QUANTITY_UPDATED",
Version: version,
Payload: payload,
Timestamp: Timestamp})
}
case "Image":
//TODO: check if image exist and add event to delete other image
if value.String() != "" {
if variant.Image == updateVariantDTO.Image {
errs.Errors = append(errs.Errors, entity.ErrorField{Field: fieldName, Error: "Image already updated"})
}
version++
payload := make(map[string]interface{})
payload["image"] = value.String()
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_IMAGE_UPDATED",
Version: version,
Payload: payload,
Timestamp: Timestamp})
}
case "Price":
if value.Int() != 0 {
if variant.Price == updateVariantDTO.Price {
errs.Errors = append(errs.Errors, entity.ErrorField{Field: fieldName, Error: "Price already updated"})
}
version++
payload := make(map[string]interface{})
payload["price"] = value.Int()
messages = append(messages, &entity.Message{
ID: string(ID),
Type: "PRODUCT_VARIANT_PRICE_UPDATED",
Version: version,
Payload: payload,
Timestamp: Timestamp})
}
}
}
if len(errs.Errors) > 0 {
return nil, &errs
}
if version == variant.Version {
return nil, &entity.Error{Op: "Update", Kind: entity.NoUpdates, ErrorMessage: entity.ErrorMessage("No updates found"), Severity: logrus.InfoLevel}
}
c := &entity.Command{AggregateID: string(ID), Type: "UpdateProduct", Payload: structs.Map(updateVariantDTO), Timestamp: Timestamp}
_, err = s.storeRepo.StoreCommand(c)
if err != nil {
return nil, &entity.Error{Op: "Update", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
up := &entity.UpdateVariant{
Version: version,
SKU: updateVariantDTO.SKU,
Quantity: updateVariantDTO.Quantity,
Price: updateVariantDTO.Price,
Image: updateVariantDTO.Image,
}
updatedNum, err := s.storeRepo.UpdateOne(ID, up, entity.Version(v))
if err != nil {
return nil, &entity.Error{Op: "Update", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
if updatedNum != 1 {
return nil, &entity.Error{Op: "Update", Kind: entity.ConcurrentModification, ErrorMessage: entity.ErrorMessage("Version conflict"), Severity: logrus.InfoLevel}
}
//TODO:handle failure cases
s.msgRepo.SendMessages(messages)
Version := int32(version)
return &Version, nil
}
//Delete product
func (s *Service) Delete(id entity.ID, v int32) *entity.Error {
Timestamp := time.Now()
version := entity.Version(v)
//TODO check Transactions
p, err := s.storeRepo.FindOneByID(id)
switch err {
case entity.ErrNotFound:
return &entity.Error{Op: "Delete", Kind: entity.NotFound, ErrorMessage: entity.ErrorMessage("Variant with id " + string(id) + " Not found"), Severity: logrus.InfoLevel}
default:
if err != nil {
return &entity.Error{Op: "Delete", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
}
if version != p.Version {
return &entity.Error{Op: "Update", Kind: entity.ConcurrentModification, ErrorMessage: entity.ErrorMessage("Version conflict"), Severity: logrus.InfoLevel}
}
c := &entity.Command{AggregateID: string(id), Type: "DeleteVariant", Timestamp: Timestamp}
s.storeRepo.StoreCommand(c)
updatedNum, err := s.storeRepo.DeleteOne(id, version)
if err != nil {
return &entity.Error{Op: "Delete", Kind: entity.Unexpected, ErrorMessage: "Internal Server Error", Severity: logrus.ErrorLevel}
}
if updatedNum != 1 {
return &entity.Error{Op: "Update", Kind: entity.ConcurrentModification, ErrorMessage: entity.ErrorMessage("Version conflict"), Severity: logrus.InfoLevel}
}
version++
//TODO:handle failure cases
m := &entity.Message{ID: string(id), Type: "PRODUCT_VARIANT_DELETED", Version: version, Timestamp: Timestamp}
s.msgRepo.SendMessage(m)
return nil
}
|
package ztimer
import (
"log"
"testing"
"time"
)
//触发函数
func foo(args ...interface{}) {
log.Println("i am no ", args[0].(int), " function delay ", args[1].(int))
}
//手动创建调度运行时间轮 go test -v -run TestNewTimerScheduler
func TestNewTimerScheduler(t *testing.T) {
timerScheduler := NewTimerScheduler()
timerScheduler.Start()
//在scheduler中添加timer
for i := 1; i < 2000; i++ {
f := NewDelayFunc(foo, []interface{}{i, i * 3})
tid, err := timerScheduler.CreateTimerAfter(f, time.Duration(3*i)*time.Millisecond)
if err != nil {
log.Println("create timer error ", tid, err)
break
}
}
//执行调度器
go func() {
delayFuncChan := timerScheduler.GetTriggerChan()
for df := range delayFuncChan {
df.Call()
}
}()
select {}
}
//自动调度时间轮 go test -v -run TestNewAutoExecTimerScheduler
func TestNewAutoExecTimerScheduler(t *testing.T) {
autoTs := NewAutoExecTimerScheduler()
//给调度器添加timer
for i := 0; i < 2000; i++ {
f := NewDelayFunc(foo, []interface{}{i, i * 3})
tid, err := autoTs.CreateTimerAfter(f, time.Duration(3*i)*time.Millisecond)
if err != nil {
log.Println("create timer error ", tid, err)
break
}
}
select {}
}
|
//************************************************************************//
// RightScale API client
//
// Generated with:
// $ praxisgen -metadata=ss/ssm/restful_doc -output=ss/ssm -pkg=ssm -target=1.0 -client=API
//
// The content of this file is auto-generated, DO NOT MODIFY
//************************************************************************//
package ssm
import (
"encoding/json"
"fmt"
"io/ioutil"
"time"
"github.com/rightscale/rsc/metadata"
"github.com/rightscale/rsc/rsapi"
)
// API Version
const APIVersion = "1.0"
// An Href contains the relative path to a resource or resource collection,
// e.g. "/api/servers/123" or "/api/servers".
type Href string
// ActionPath computes the path to the given resource action. For example given the href
// "/api/servers/123" calling ActionPath with resource "servers" and action "clone" returns the path
// "/api/servers/123/clone" and verb POST.
// The algorithm consists of extracting the variables from the href by looking up a matching
// pattern from the resource metadata. The variables are then substituted in the action path.
// If there are more than one pattern that match the href then the algorithm picks the one that can
// substitute the most variables.
func (r *Href) ActionPath(rName, aName string) (*metadata.ActionPath, error) {
res, ok := GenMetadata[rName]
if !ok {
return nil, fmt.Errorf("No resource with name '%s'", rName)
}
var action *metadata.Action
for _, a := range res.Actions {
if a.Name == aName {
action = a
break
}
}
if action == nil {
return nil, fmt.Errorf("No action with name '%s' on %s", aName, rName)
}
vars, err := res.ExtractVariables(string(*r))
if err != nil {
return nil, err
}
return action.URL(vars)
}
/****** Execution ******/
// An Execution is a launched instance of a CloudApp. Executions can be created from the catalog
// by launching an Application, from Designer by launching a Template, or directly in Manager
// by using the API and sending the CAT source or CAT Compiled source.
// Executions are represented in RightScale Cloud Management by a deployment -- the resources
// defined in the CAT are all created in the Deployment. Any action on a running CloudApp should
// be made on its Execution resource.
// Making changes to any resource directly in the CM deployment
// may result in undesired behavior since the Execution only refreshes certain information as a
// result of running an Operation on an Execution. For example, if a Server is replaced in CM
// instead of through Self-Service, the new Server's information won' be available in
// Self-Service.
type Execution struct {
ApiResources []*Resource `json:"api_resources,omitempty"`
AvailableActions []string `json:"available_actions,omitempty"`
AvailableOperations []*OperationDefinition `json:"available_operations,omitempty"`
AvailableOperationsInfo []*OperationInfo `json:"available_operations_info,omitempty"`
CompilationHref string `json:"compilation_href,omitempty"`
ConfigurationOptions []*ConfigurationOption `json:"configuration_options,omitempty"`
Cost *CostStruct `json:"cost,omitempty"`
CreatedBy *User `json:"created_by,omitempty"`
CurrentSchedule string `json:"current_schedule,omitempty"`
Dependencies []*CatDependency `json:"dependencies,omitempty"`
Deployment string `json:"deployment,omitempty"`
DeploymentUrl string `json:"deployment_url,omitempty"`
Description string `json:"description,omitempty"`
EndsAt *time.Time `json:"ends_at,omitempty"`
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
LatestNotification *Notification `json:"latest_notification,omitempty"`
LatestNotifications []*Notification `json:"latest_notifications,omitempty"`
LaunchedFrom *LaunchedFrom `json:"launched_from,omitempty"`
LaunchedFromSummary map[string]interface{} `json:"launched_from_summary,omitempty"`
Links *ExecutionLinks `json:"links,omitempty"`
Name string `json:"name,omitempty"`
NextAction *ScheduledAction `json:"next_action,omitempty"`
Outputs []*Output `json:"outputs,omitempty"`
RunningOperations []*Operation `json:"running_operations,omitempty"`
ScheduleRequired bool `json:"schedule_required,omitempty"`
Scheduled bool `json:"scheduled,omitempty"`
Schedules []*Schedule `json:"schedules,omitempty"`
Source string `json:"source,omitempty"`
Status string `json:"status,omitempty"`
Timestamps *TimestampsStruct `json:"timestamps,omitempty"`
}
// Locator returns a locator for the given resource
func (r *Execution) Locator(api *API) *ExecutionLocator {
return api.ExecutionLocator(r.Href)
}
//===== Locator
// ExecutionLocator exposes the Execution resource actions.
type ExecutionLocator struct {
Href
api *API
}
// ExecutionLocator builds a locator from the given href.
func (api *API) ExecutionLocator(href string) *ExecutionLocator {
return &ExecutionLocator{Href(href), api}
}
//===== Actions
// GET /api/manager/projects/:project_id/executions
//
// List information about the Executions, or use a filter to only return certain Executions. A view can be used for various levels of detail.
func (loc *ExecutionLocator) Index(options rsapi.APIParams) ([]*Execution, error) {
var res []*Execution
var params rsapi.APIParams
params = rsapi.APIParams{}
var filterOpt = options["filter"]
if filterOpt != nil {
params["filter[]"] = filterOpt
}
var idsOpt = options["ids"]
if idsOpt != nil {
params["ids[]"] = idsOpt
}
var viewOpt = options["view"]
if viewOpt != nil {
params["view"] = viewOpt
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "index")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
// GET /api/manager/projects/:project_id/executions/:id
//
// Show details for a given Execution. A view can be used for various levels of detail.
func (loc *ExecutionLocator) Show(options rsapi.APIParams) (*Execution, error) {
var res *Execution
var params rsapi.APIParams
params = rsapi.APIParams{}
var viewOpt = options["view"]
if viewOpt != nil {
params["view"] = viewOpt
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "show")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
// POST /api/manager/projects/:project_id/executions
//
// Create a new execution from a CAT, a compiled CAT, an Application in the Catalog, or a Template in Designer
func (loc *ExecutionLocator) Create(options rsapi.APIParams) (*ExecutionLocator, error) {
var res *ExecutionLocator
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{}
var applicationHrefOpt = options["application_href"]
if applicationHrefOpt != nil {
p["application_href"] = applicationHrefOpt
}
var compilationHrefOpt = options["compilation_href"]
if compilationHrefOpt != nil {
p["compilation_href"] = compilationHrefOpt
}
var compiledCatOpt = options["compiled_cat"]
if compiledCatOpt != nil {
p["compiled_cat"] = compiledCatOpt
}
var currentScheduleOpt = options["current_schedule"]
if currentScheduleOpt != nil {
p["current_schedule"] = currentScheduleOpt
}
var deferLaunchOpt = options["defer_launch"]
if deferLaunchOpt != nil {
p["defer_launch"] = deferLaunchOpt
}
var descriptionOpt = options["description"]
if descriptionOpt != nil {
p["description"] = descriptionOpt
}
var endsAtOpt = options["ends_at"]
if endsAtOpt != nil {
p["ends_at"] = endsAtOpt
}
var nameOpt = options["name"]
if nameOpt != nil {
p["name"] = nameOpt
}
var options_Opt = options["options"]
if options_Opt != nil {
p["options"] = options_Opt
}
var scheduleRequiredOpt = options["schedule_required"]
if scheduleRequiredOpt != nil {
p["schedule_required"] = scheduleRequiredOpt
}
var scheduledActionsOpt = options["scheduled_actions"]
if scheduledActionsOpt != nil {
p["scheduled_actions"] = scheduledActionsOpt
}
var schedulesOpt = options["schedules"]
if schedulesOpt != nil {
p["schedules"] = schedulesOpt
}
var sourceOpt = options["source"]
if sourceOpt != nil {
p["source"] = sourceOpt
}
var templateHrefOpt = options["template_href"]
if templateHrefOpt != nil {
p["template_href"] = templateHrefOpt
}
uri, err := loc.ActionPath("Execution", "create")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
location := resp.Header.Get("Location")
if len(location) == 0 {
return res, fmt.Errorf("Missing location header in response")
} else {
return &ExecutionLocator{Href(location), loc.api}, nil
}
}
// PATCH /api/manager/projects/:project_id/executions/:id
//
// Updates an execution end date or selected schedule.
func (loc *ExecutionLocator) Patch(options rsapi.APIParams) error {
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{}
var currentScheduleOpt = options["current_schedule"]
if currentScheduleOpt != nil {
p["current_schedule"] = currentScheduleOpt
}
var endsAtOpt = options["ends_at"]
if endsAtOpt != nil {
p["ends_at"] = endsAtOpt
}
uri, err := loc.ActionPath("Execution", "patch")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// DELETE /api/manager/projects/:project_id/executions/:id
//
// No description provided for delete.
func (loc *ExecutionLocator) Delete(options rsapi.APIParams) error {
var params rsapi.APIParams
params = rsapi.APIParams{}
var forceOpt = options["force"]
if forceOpt != nil {
params["force"] = forceOpt
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "delete")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// DELETE /api/manager/projects/:project_id/executions
//
// Delete several executions from the database. Note: if an execution has not successfully been terminated, there may still be associated cloud resources running.
func (loc *ExecutionLocator) MultiDelete(ids []string, options rsapi.APIParams) error {
if len(ids) == 0 {
return fmt.Errorf("ids is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{
"ids[]": ids,
}
var forceOpt = options["force"]
if forceOpt != nil {
params["force"] = forceOpt
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "multi_delete")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// GET /api/manager/projects/:project_id/executions/:id/download
//
// Download the CAT source for the execution.
func (loc *ExecutionLocator) Download(apiVersion string) error {
if apiVersion == "" {
return fmt.Errorf("apiVersion is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{
"api_version": apiVersion,
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "download")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/:id/actions/launch
//
// Launch an Execution.
func (loc *ExecutionLocator) Launch() error {
var params rsapi.APIParams
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "launch")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/:id/actions/start
//
// Start an Execution.
func (loc *ExecutionLocator) Start() error {
var params rsapi.APIParams
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "start")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/:id/actions/stop
//
// Stop an Execution.
func (loc *ExecutionLocator) Stop() error {
var params rsapi.APIParams
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "stop")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/:id/actions/terminate
//
// Terminate an Execution.
func (loc *ExecutionLocator) Terminate() error {
var params rsapi.APIParams
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "terminate")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/actions/launch
//
// Launch several Executions.
func (loc *ExecutionLocator) MultiLaunch(ids []string) error {
if len(ids) == 0 {
return fmt.Errorf("ids is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{
"ids[]": ids,
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "multi_launch")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/actions/start
//
// Start several Executions.
func (loc *ExecutionLocator) MultiStart(ids []string) error {
if len(ids) == 0 {
return fmt.Errorf("ids is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{
"ids[]": ids,
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "multi_start")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/actions/stop
//
// Stop several Executions.
func (loc *ExecutionLocator) MultiStop(ids []string) error {
if len(ids) == 0 {
return fmt.Errorf("ids is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{
"ids[]": ids,
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "multi_stop")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/actions/terminate
//
// Terminate several Executions.
func (loc *ExecutionLocator) MultiTerminate(ids []string) error {
if len(ids) == 0 {
return fmt.Errorf("ids is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{
"ids[]": ids,
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Execution", "multi_terminate")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/:id/actions/run
//
// Runs an Operation on an Execution.
func (loc *ExecutionLocator) Run(name string, options rsapi.APIParams) error {
if name == "" {
return fmt.Errorf("name is required")
}
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{
"name": name,
}
var configurationOptionsOpt = options["configuration_options"]
if configurationOptionsOpt != nil {
p["configuration_options"] = configurationOptionsOpt
}
uri, err := loc.ActionPath("Execution", "run")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/executions/actions/run
//
// Runs an Operation on several Executions.
func (loc *ExecutionLocator) MultiRun(ids []string, name string, options rsapi.APIParams) error {
if len(ids) == 0 {
return fmt.Errorf("ids is required")
}
if name == "" {
return fmt.Errorf("name is required")
}
var params rsapi.APIParams
params = rsapi.APIParams{
"ids[]": ids,
}
var p rsapi.APIParams
p = rsapi.APIParams{
"name": name,
}
var configurationOptionsOpt = options["configuration_options"]
if configurationOptionsOpt != nil {
p["configuration_options"] = configurationOptionsOpt
}
uri, err := loc.ActionPath("Execution", "multi_run")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
/****** Notification ******/
// The Notification resource represents a system notification that an action has occurred. Generally
// these Notifications are the start and completion of Operations. Currently notifications are only
// available via the API/UI and are not distributed externally to users.
type Notification struct {
Category string `json:"category,omitempty"`
Execution *Execution `json:"execution,omitempty"`
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Links *NotificationLinks `json:"links,omitempty"`
Message string `json:"message,omitempty"`
Read bool `json:"read,omitempty"`
Timestamps *TimestampsStruct `json:"timestamps,omitempty"`
}
// Locator returns a locator for the given resource
func (r *Notification) Locator(api *API) *NotificationLocator {
return api.NotificationLocator(r.Href)
}
//===== Locator
// NotificationLocator exposes the Notification resource actions.
type NotificationLocator struct {
Href
api *API
}
// NotificationLocator builds a locator from the given href.
func (api *API) NotificationLocator(href string) *NotificationLocator {
return &NotificationLocator{Href(href), api}
}
//===== Actions
// GET /api/manager/projects/:project_id/notifications
//
// List the most recent 50 Notifications. Use the filter parameter to specify specify Executions.
func (loc *NotificationLocator) Index(options rsapi.APIParams) ([]*Notification, error) {
var res []*Notification
var params rsapi.APIParams
params = rsapi.APIParams{}
var filterOpt = options["filter"]
if filterOpt != nil {
params["filter[]"] = filterOpt
}
var idsOpt = options["ids"]
if idsOpt != nil {
params["ids[]"] = idsOpt
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Notification", "index")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
// GET /api/manager/projects/:project_id/notifications/:id
//
// Get details for a specific Notification
func (loc *NotificationLocator) Show() (*Notification, error) {
var res *Notification
var params rsapi.APIParams
var p rsapi.APIParams
uri, err := loc.ActionPath("Notification", "show")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
/****** Operation ******/
// Operations represent actions that can be taken on an Execution.
// When a CloudApp is launched, a sequence of Operations is run as [explained here](http://docs.rightscale.com/ss/reference/ss_CAT_file_language.html#operations) in the Operations section
// While a CloudApp is running, users may launch any custom Operations as defined in the CAT.
// Once a CAT is Terminated, a sequence of Operations is run as [explained here](http://docs.rightscale.com/ss/reference/ss_CAT_file_language.html#operations) in the Operations section
type Operation struct {
ConfigurationOptions []*ConfigurationOption `json:"configuration_options,omitempty"`
CreatedBy *User `json:"created_by,omitempty"`
Execution *Execution `json:"execution,omitempty"`
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Label string `json:"label,omitempty"`
Links *OperationLinks `json:"links,omitempty"`
Name string `json:"name,omitempty"`
Status *StatusStruct `json:"status,omitempty"`
Timestamps *TimestampsStruct `json:"timestamps,omitempty"`
}
// Locator returns a locator for the given resource
func (r *Operation) Locator(api *API) *OperationLocator {
return api.OperationLocator(r.Href)
}
//===== Locator
// OperationLocator exposes the Operation resource actions.
type OperationLocator struct {
Href
api *API
}
// OperationLocator builds a locator from the given href.
func (api *API) OperationLocator(href string) *OperationLocator {
return &OperationLocator{Href(href), api}
}
//===== Actions
// GET /api/manager/projects/:project_id/operations
//
// Get the list of 50 most recent Operations (usually filtered by Execution).
func (loc *OperationLocator) Index(options rsapi.APIParams) ([]*Operation, error) {
var res []*Operation
var params rsapi.APIParams
params = rsapi.APIParams{}
var filterOpt = options["filter"]
if filterOpt != nil {
params["filter[]"] = filterOpt
}
var idsOpt = options["ids"]
if idsOpt != nil {
params["ids[]"] = idsOpt
}
var limitOpt = options["limit"]
if limitOpt != nil {
params["limit"] = limitOpt
}
var viewOpt = options["view"]
if viewOpt != nil {
params["view"] = viewOpt
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Operation", "index")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
// GET /api/manager/projects/:project_id/operations/:id
//
// Get the details for a specific Operation
func (loc *OperationLocator) Show(options rsapi.APIParams) (*Operation, error) {
var res *Operation
var params rsapi.APIParams
params = rsapi.APIParams{}
var viewOpt = options["view"]
if viewOpt != nil {
params["view"] = viewOpt
}
var p rsapi.APIParams
uri, err := loc.ActionPath("Operation", "show")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
// POST /api/manager/projects/:project_id/operations
//
// Trigger an Operation to run by specifying the Execution ID and the name of the Operation.
func (loc *OperationLocator) Create(executionId string, name string, options rsapi.APIParams) (*OperationLocator, error) {
var res *OperationLocator
if executionId == "" {
return res, fmt.Errorf("executionId is required")
}
if name == "" {
return res, fmt.Errorf("name is required")
}
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{
"execution_id": executionId,
"name": name,
}
var options_Opt = options["options"]
if options_Opt != nil {
p["options"] = options_Opt
}
uri, err := loc.ActionPath("Operation", "create")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
location := resp.Header.Get("Location")
if len(location) == 0 {
return res, fmt.Errorf("Missing location header in response")
} else {
return &OperationLocator{Href(location), loc.api}, nil
}
}
/****** ScheduledAction ******/
// ScheduledActions describe a set of timed occurrences for an action to be run (at most once per day).
// Recurrence Rules are based off of the [RFC 5545](https://tools.ietf.org/html/rfc5545) iCal spec, and timezones are from the standard [tzinfo database](http://www.iana.org/time-zones).
// All DateTimes must be passed in [ISO-8601 format](https://en.wikipedia.org/wiki/ISO_8601)
type ScheduledAction struct {
Action string `json:"action,omitempty"`
CreatedBy *User `json:"created_by,omitempty"`
Execution *Execution `json:"execution,omitempty"`
ExecutionSchedule bool `json:"execution_schedule,omitempty"`
FirstOccurrence *time.Time `json:"first_occurrence,omitempty"`
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Links *ScheduledActionLinks `json:"links,omitempty"`
Name string `json:"name,omitempty"`
NextOccurrence *time.Time `json:"next_occurrence,omitempty"`
Operation *OperationStruct `json:"operation,omitempty"`
Recurrence string `json:"recurrence,omitempty"`
RecurrenceDescription string `json:"recurrence_description,omitempty"`
Timestamps *TimestampsStruct `json:"timestamps,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
// Locator returns a locator for the given resource
func (r *ScheduledAction) Locator(api *API) *ScheduledActionLocator {
return api.ScheduledActionLocator(r.Href)
}
//===== Locator
// ScheduledActionLocator exposes the ScheduledAction resource actions.
type ScheduledActionLocator struct {
Href
api *API
}
// ScheduledActionLocator builds a locator from the given href.
func (api *API) ScheduledActionLocator(href string) *ScheduledActionLocator {
return &ScheduledActionLocator{Href(href), api}
}
//===== Actions
// GET /api/manager/projects/:project_id/scheduled_actions
//
// List ScheduledAction resources in the project. The list can be filtered to a given execution.
func (loc *ScheduledActionLocator) Index(options rsapi.APIParams) ([]*ScheduledAction, error) {
var res []*ScheduledAction
var params rsapi.APIParams
params = rsapi.APIParams{}
var filterOpt = options["filter"]
if filterOpt != nil {
params["filter[]"] = filterOpt
}
var p rsapi.APIParams
uri, err := loc.ActionPath("ScheduledAction", "index")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
// GET /api/manager/projects/:project_id/scheduled_actions/:id
//
// Retrieve given ScheduledAction resource.
func (loc *ScheduledActionLocator) Show() (*ScheduledAction, error) {
var res *ScheduledAction
var params rsapi.APIParams
var p rsapi.APIParams
uri, err := loc.ActionPath("ScheduledAction", "show")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return res, err
}
err = json.Unmarshal(respBody, &res)
return res, err
}
// POST /api/manager/projects/:project_id/scheduled_actions
//
// Create a new ScheduledAction resource.
func (loc *ScheduledActionLocator) Create(action string, executionId string, firstOccurrence *time.Time, options rsapi.APIParams) (*ScheduledActionLocator, error) {
var res *ScheduledActionLocator
if action == "" {
return res, fmt.Errorf("action is required")
}
if executionId == "" {
return res, fmt.Errorf("executionId is required")
}
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{
"action": action,
"execution_id": executionId,
"first_occurrence": firstOccurrence,
}
var nameOpt = options["name"]
if nameOpt != nil {
p["name"] = nameOpt
}
var operationOpt = options["operation"]
if operationOpt != nil {
p["operation"] = operationOpt
}
var recurrenceOpt = options["recurrence"]
if recurrenceOpt != nil {
p["recurrence"] = recurrenceOpt
}
var timezoneOpt = options["timezone"]
if timezoneOpt != nil {
p["timezone"] = timezoneOpt
}
uri, err := loc.ActionPath("ScheduledAction", "create")
if err != nil {
return res, err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return res, err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return res, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return res, fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
location := resp.Header.Get("Location")
if len(location) == 0 {
return res, fmt.Errorf("Missing location header in response")
} else {
return &ScheduledActionLocator{Href(location), loc.api}, nil
}
}
// PATCH /api/manager/projects/:project_id/scheduled_actions/:id
//
// Updates the 'next_occurrence' property of a ScheduledAction.
func (loc *ScheduledActionLocator) Patch(options rsapi.APIParams) error {
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{}
var nextOccurrenceOpt = options["next_occurrence"]
if nextOccurrenceOpt != nil {
p["next_occurrence"] = nextOccurrenceOpt
}
uri, err := loc.ActionPath("ScheduledAction", "patch")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// DELETE /api/manager/projects/:project_id/scheduled_actions/:id
//
// Delete a ScheduledAction.
func (loc *ScheduledActionLocator) Delete() error {
var params rsapi.APIParams
var p rsapi.APIParams
uri, err := loc.ActionPath("ScheduledAction", "delete")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
// POST /api/manager/projects/:project_id/scheduled_actions/:id/actions/skip
//
// Skips the requested number of ScheduledAction occurrences. If no count is provided, one occurrence is skipped. On success, the next_occurrence view of the updated ScheduledAction is returned.
func (loc *ScheduledActionLocator) Skip(options rsapi.APIParams) error {
var params rsapi.APIParams
var p rsapi.APIParams
p = rsapi.APIParams{}
var countOpt = options["count"]
if countOpt != nil {
p["count"] = countOpt
}
uri, err := loc.ActionPath("ScheduledAction", "skip")
if err != nil {
return err
}
req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p)
if err != nil {
return err
}
resp, err := loc.api.PerformRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
sr := string(respBody)
if sr != "" {
sr = ": " + sr
}
return fmt.Errorf("invalid response %s%s", resp.Status, sr)
}
return nil
}
/****** Data Types ******/
type ApiResourcesValueStruct struct {
Details map[string]interface{} `json:"details,omitempty"`
Href string `json:"href,omitempty"`
}
type AvailableOperationsParametersUiStruct struct {
Category string `json:"category,omitempty"`
Index int `json:"index,omitempty"`
Label string `json:"label,omitempty"`
}
type AvailableOperationsParametersValidationStruct struct {
AllowedPattern string `json:"allowed_pattern,omitempty"`
AllowedValues []interface{} `json:"allowed_values,omitempty"`
ConstraintDescription string `json:"constraint_description,omitempty"`
MaxLength int `json:"max_length,omitempty"`
MaxValue int `json:"max_value,omitempty"`
MinLength int `json:"min_length,omitempty"`
MinValue int `json:"min_value,omitempty"`
NoEcho bool `json:"no_echo,omitempty"`
}
type CatDependency struct {
Alias string `json:"alias,omitempty"`
Name string `json:"name,omitempty"`
Package string `json:"package,omitempty"`
SourceHref string `json:"source_href,omitempty"`
}
type CompiledCAT struct {
CatParserGemVersion string `json:"cat_parser_gem_version,omitempty"`
CompilerVer string `json:"compiler_ver,omitempty"`
Conditions map[string]interface{} `json:"conditions,omitempty"`
Definitions map[string]interface{} `json:"definitions,omitempty"`
DependencyHashes []map[string]interface{} `json:"dependency_hashes,omitempty"`
Imports map[string]interface{} `json:"imports,omitempty"`
LongDescription string `json:"long_description,omitempty"`
Mappings map[string]interface{} `json:"mappings,omitempty"`
Name string `json:"name,omitempty"`
Namespaces []*Namespace `json:"namespaces,omitempty"`
Operations map[string]interface{} `json:"operations,omitempty"`
Outputs map[string]interface{} `json:"outputs,omitempty"`
Package string `json:"package,omitempty"`
Parameters map[string]interface{} `json:"parameters,omitempty"`
Permissions map[string]interface{} `json:"permissions,omitempty"`
RequiredParameters []string `json:"required_parameters,omitempty"`
Resources map[string]interface{} `json:"resources,omitempty"`
RsCaVer int `json:"rs_ca_ver,omitempty"`
ShortDescription string `json:"short_description,omitempty"`
Source string `json:"source,omitempty"`
}
type ConfigurationOption struct {
Name string `json:"name,omitempty"`
Type_ string `json:"type,omitempty"`
Value interface{} `json:"value,omitempty"`
}
type CostStruct struct {
Unit string `json:"unit,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
Value string `json:"value,omitempty"`
}
type ExecutionLink struct {
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
type ExecutionLinks struct {
LatestNotifications *NotificationLatestNotificationsLink `json:"latest_notifications,omitempty"`
RunningOperations *OperationRunningOperationsLink `json:"running_operations,omitempty"`
}
type ExecutionParam struct {
ApiResources []*Resource `json:"api_resources,omitempty"`
AvailableActions []string `json:"available_actions,omitempty"`
AvailableOperations []*OperationDefinition `json:"available_operations,omitempty"`
AvailableOperationsInfo []*OperationInfo `json:"available_operations_info,omitempty"`
CompilationHref string `json:"compilation_href,omitempty"`
ConfigurationOptions []*ConfigurationOption `json:"configuration_options,omitempty"`
Cost *LatestNotificationExecutionCostStruct `json:"cost,omitempty"`
CreatedBy *User `json:"created_by,omitempty"`
CurrentSchedule string `json:"current_schedule,omitempty"`
Dependencies []*CatDependency `json:"dependencies,omitempty"`
Deployment string `json:"deployment,omitempty"`
DeploymentUrl string `json:"deployment_url,omitempty"`
Description string `json:"description,omitempty"`
EndsAt *time.Time `json:"ends_at,omitempty"`
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
LatestNotification *NotificationParam `json:"latest_notification,omitempty"`
LatestNotifications []*NotificationParam `json:"latest_notifications,omitempty"`
LaunchedFrom *LaunchedFrom `json:"launched_from,omitempty"`
LaunchedFromSummary map[string]interface{} `json:"launched_from_summary,omitempty"`
Links *ExecutionLinks `json:"links,omitempty"`
Name string `json:"name,omitempty"`
NextAction *ScheduledActionParam `json:"next_action,omitempty"`
Outputs []*Output `json:"outputs,omitempty"`
RunningOperations []*OperationParam `json:"running_operations,omitempty"`
ScheduleRequired bool `json:"schedule_required,omitempty"`
Scheduled bool `json:"scheduled,omitempty"`
Schedules []*Schedule `json:"schedules,omitempty"`
Source string `json:"source,omitempty"`
Status string `json:"status,omitempty"`
Timestamps *LatestNotificationExecutionTimestampsStruct `json:"timestamps,omitempty"`
}
type LatestNotificationExecutionCostStruct struct {
Unit string `json:"unit,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
Value string `json:"value,omitempty"`
}
type LatestNotificationExecutionNextActionOperationStruct struct {
ConfigurationOptions []*ConfigurationOption `json:"configuration_options,omitempty"`
Name string `json:"name,omitempty"`
}
type LatestNotificationExecutionNextActionTimestampsStruct struct {
CreatedAt *time.Time `json:"created_at,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
}
type LatestNotificationExecutionRunningOperationsStatusStruct struct {
Percent int `json:"percent,omitempty"`
Summary string `json:"summary,omitempty"`
Tasks []*Task `json:"tasks,omitempty"`
}
type LatestNotificationExecutionRunningOperationsStatusTasksStatusStruct struct {
Percent int `json:"percent,omitempty"`
Summary string `json:"summary,omitempty"`
}
type LatestNotificationExecutionRunningOperationsTimestampsStruct struct {
CreatedAt *time.Time `json:"created_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
type LatestNotificationExecutionTimestampsStruct struct {
CreatedAt *time.Time `json:"created_at,omitempty"`
LaunchedAt *time.Time `json:"launched_at,omitempty"`
TerminatedAt *time.Time `json:"terminated_at,omitempty"`
}
type LatestNotificationTimestampsStruct struct {
CreatedAt *time.Time `json:"created_at,omitempty"`
}
type LaunchedFrom struct {
Type_ string `json:"type,omitempty"`
Value interface{} `json:"value,omitempty"`
}
type Namespace struct {
Name string `json:"name,omitempty"`
Service *NamespaceService `json:"service,omitempty"`
Types []*NamespaceType `json:"types,omitempty"`
}
type NamespaceService struct {
Auth string `json:"auth,omitempty"`
Headers map[string]interface{} `json:"headers,omitempty"`
Host string `json:"host,omitempty"`
Path string `json:"path,omitempty"`
}
type NamespaceType struct {
Delete string `json:"delete,omitempty"`
Fields map[string]interface{} `json:"fields,omitempty"`
Name string `json:"name,omitempty"`
Path string `json:"path,omitempty"`
Provision string `json:"provision,omitempty"`
}
type NotificationLatestNotificationsLink struct {
Href string `json:"href,omitempty"`
}
type NotificationLinks struct {
Execution *ExecutionLink `json:"execution,omitempty"`
}
type NotificationParam struct {
Category string `json:"category,omitempty"`
Execution *ExecutionParam `json:"execution,omitempty"`
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Links *NotificationLinks `json:"links,omitempty"`
Message string `json:"message,omitempty"`
Read bool `json:"read,omitempty"`
Timestamps *LatestNotificationTimestampsStruct `json:"timestamps,omitempty"`
}
type OperationDefinition struct {
Description string `json:"description,omitempty"`
Label string `json:"label,omitempty"`
Name string `json:"name,omitempty"`
Parameters []*Parameter `json:"parameters,omitempty"`
}
type OperationInfo struct {
Description string `json:"description,omitempty"`
Label string `json:"label,omitempty"`
Name string `json:"name,omitempty"`
}
type OperationLinks struct {
Execution *ExecutionLink `json:"execution,omitempty"`
}
type OperationParam struct {
ConfigurationOptions []*ConfigurationOption `json:"configuration_options,omitempty"`
CreatedBy *User `json:"created_by,omitempty"`
Execution *ExecutionParam `json:"execution,omitempty"`
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Label string `json:"label,omitempty"`
Links *OperationLinks `json:"links,omitempty"`
Name string `json:"name,omitempty"`
Status *LatestNotificationExecutionRunningOperationsStatusStruct `json:"status,omitempty"`
Timestamps *LatestNotificationExecutionRunningOperationsTimestampsStruct `json:"timestamps,omitempty"`
}
type OperationRunningOperationsLink struct {
Href string `json:"href,omitempty"`
}
type OperationStruct struct {
ConfigurationOptions []*ConfigurationOption `json:"configuration_options,omitempty"`
Name string `json:"name,omitempty"`
}
type Output struct {
Category string `json:"category,omitempty"`
Description string `json:"description,omitempty"`
Index int `json:"index,omitempty"`
Label string `json:"label,omitempty"`
Name string `json:"name,omitempty"`
Value interface{} `json:"value,omitempty"`
}
type Parameter struct {
Default interface{} `json:"default,omitempty"`
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
Operations []interface{} `json:"operations,omitempty"`
Type_ string `json:"type,omitempty"`
Ui *AvailableOperationsParametersUiStruct `json:"ui,omitempty"`
Validation *AvailableOperationsParametersValidationStruct `json:"validation,omitempty"`
}
type Recurrence struct {
Hour int `json:"hour,omitempty"`
Minute int `json:"minute,omitempty"`
Rule string `json:"rule,omitempty"`
}
type Resource struct {
Name string `json:"name,omitempty"`
Type_ string `json:"type,omitempty"`
Value *ApiResourcesValueStruct `json:"value,omitempty"`
}
type Schedule struct {
CreatedFrom string `json:"created_from,omitempty"`
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
StartRecurrence *Recurrence `json:"start_recurrence,omitempty"`
StopRecurrence *Recurrence `json:"stop_recurrence,omitempty"`
}
type ScheduledActionLinks struct {
Execution *ExecutionLink `json:"execution,omitempty"`
}
type ScheduledActionParam struct {
Action string `json:"action,omitempty"`
CreatedBy *User `json:"created_by,omitempty"`
Execution *ExecutionParam `json:"execution,omitempty"`
ExecutionSchedule bool `json:"execution_schedule,omitempty"`
FirstOccurrence *time.Time `json:"first_occurrence,omitempty"`
Href string `json:"href,omitempty"`
Id string `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Links *ScheduledActionLinks `json:"links,omitempty"`
Name string `json:"name,omitempty"`
NextOccurrence *time.Time `json:"next_occurrence,omitempty"`
Operation *LatestNotificationExecutionNextActionOperationStruct `json:"operation,omitempty"`
Recurrence string `json:"recurrence,omitempty"`
RecurrenceDescription string `json:"recurrence_description,omitempty"`
Timestamps *LatestNotificationExecutionNextActionTimestampsStruct `json:"timestamps,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
type StatusStruct struct {
Percent int `json:"percent,omitempty"`
Summary string `json:"summary,omitempty"`
Tasks []*Task `json:"tasks,omitempty"`
}
type Task struct {
Label string `json:"label,omitempty"`
Name string `json:"name,omitempty"`
Status *LatestNotificationExecutionRunningOperationsStatusTasksStatusStruct `json:"status,omitempty"`
}
type TimestampsStruct struct {
CreatedAt *time.Time `json:"created_at,omitempty"`
LaunchedAt *time.Time `json:"launched_at,omitempty"`
TerminatedAt *time.Time `json:"terminated_at,omitempty"`
}
type TimestampsStruct2 struct {
CreatedAt *time.Time `json:"created_at,omitempty"`
}
type TimestampsStruct3 struct {
CreatedAt *time.Time `json:"created_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
type TimestampsStruct4 struct {
CreatedAt *time.Time `json:"created_at,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
}
type User struct {
Email string `json:"email,omitempty"`
Id int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
|
package xhlog
import (
"bytes"
"encoding/json"
"fmt"
"github.com/cyongxue/magicbox/xhiris/xhid"
"github.com/kataras/iris/v12"
"reflect"
"runtime"
"strings"
)
const (
RealRemoteIP = "x-real-ip"
)
// 日志格式为:
// [INFO] [2020-06-29T22:26:59.972+0800] [logic/middleware/middlerware_handler.go:64] _request_in||uri=/api/ping?world=hello||from=[::1]:63846||method=GET||proto=HTTP/1.1||traceid=1234567890||spanid=1234567890||args={"world":"hello"}
// buildValueLog 拼接日志全文
// 拼接的内容为: [logic/middleware/middlerware_handler.go:64] _request_in||uri=/api/ping?world=hello||from=[::1]:63846||method=GET||proto=HTTP/1.1||traceid=1234567890||spanid=1234567890||args={"world":"hello"}
func buildValueLog(stackDeep int, dFlag string, ctx iris.Context, v ...interface{}) string {
_, file, line, ok := runtime.Caller(stackDeep)
if !ok {
file = "???"
line = 0
} else {
beginIndex := strings.LastIndex(file, "/") + 1
if beginIndex <= len(file) {
file = file[beginIndex:]
}
}
var msgBuffer bytes.Buffer
msgBuffer.WriteString(fmt.Sprintf("[%s:%d]", file, line))
// 添加dflag
{
msgBuffer.WriteString(" ")
msgBuffer.WriteString(fmt.Sprintf("op=%s", dFlag))
}
// 普通日志,采用当前打印的时间戳
if dFlag != OPHttpSuccess && dFlag != OPHttpFailure {
msgBuffer.WriteString(fmt.Sprintf("||%s=%d", TimeStamp, NowUSec()))
}
// 上下文件的一些信息,利用Context来完成
if ctx != nil {
if dFlag == OPRequestIn {
msgBuffer.WriteString(fmt.Sprintf("||%s=%s", "uri", ctx.Request().URL.String()))
if ctx.Request().Header.Get(RealRemoteIP) != "" {
msgBuffer.WriteString(fmt.Sprintf("||%s=%s", "from", ctx.Request().Header.Get(RealRemoteIP)))
} else {
msgBuffer.WriteString(fmt.Sprintf("||%s=%s", "from", ctx.Request().RemoteAddr))
}
}
if dFlag == OPRequestIn || dFlag == OPRequestOut {
msgBuffer.WriteString(fmt.Sprintf("||%s=%s", "method", ctx.Request().Method))
msgBuffer.WriteString(fmt.Sprintf("||%s=%s", "proto", ctx.Request().Proto))
}
msgBuffer.WriteString(fmt.Sprintf("||%s=%s", "traceid", ctx.Values().GetStringDefault(xhid.TraceId, "")))
msgBuffer.WriteString(fmt.Sprintf("||%s=%s", "parentid", ctx.Values().GetStringDefault(xhid.ParentId, "")))
if dFlag != OPHttpFailure && dFlag != OPHttpSuccess {
msgBuffer.WriteString(fmt.Sprintf("||%s=%s", "spanid", ctx.Values().GetStringDefault(xhid.SpanId, "")))
}
}
// 利用v自定义携带的k-v
{
paramSlice := []interface{}{}
paramSlice = append(paramSlice, v...)
appendValueToBytesBuffer(&msgBuffer, paramSlice...)
}
return msgBuffer.String()
}
// appendValueToBytesBuffer 拼接日志格式
func appendValueToBytesBuffer(stringBuffer *bytes.Buffer, v ...interface{}) {
for _, item := range v {
// 如果参数是nil,那么就不输出
if item == nil {
continue
}
// 是不是空
itemValue := reflect.ValueOf(item)
switch itemValue.Kind() {
case reflect.Map:
// 是不是空
if itemValue.IsNil() {
continue
}
// 拿到所有key
keys := itemValue.MapKeys()
for _, key := range keys {
value := itemValue.MapIndex(key)
for value.Kind() == reflect.Interface ||
value.Kind() == reflect.Ptr {
value = value.Elem()
}
switch value.Kind() {
case reflect.Map, reflect.Slice, reflect.Struct:
jsonString, _ := json.Marshal(value.Interface())
stringBuffer.WriteString(fmt.Sprintf("||%s=%s", key.Interface(), jsonString))
case reflect.Invalid:
stringBuffer.WriteString(fmt.Sprintf("||%s=%v", key.Interface(), nil))
default:
stringBuffer.WriteString(fmt.Sprintf("||%s=%s", key.Interface(), fmt.Sprint(value.Interface())))
}
}
case reflect.Struct:
var logString string
logBytes, _ := json.Marshal(v)
logString = fmt.Sprintf("||msg=%s", logBytes)
stringBuffer.WriteString(logString)
case reflect.Invalid:
stringBuffer.WriteString(fmt.Sprintf("||msg=%v", nil))
default:
stringBuffer.WriteString(fmt.Sprintf("||msg=%s", fmt.Sprint(item)))
}
}
return
}
|
/*
See https://app.swaggerhub.com/apis/epixode1/BYhZzCNUCkA/4.0.0
*/
package api
/* This is specific to task1. */
type GameParams struct {
NbPlayers uint32 `json:"nb_players" yaml:"nb_players"`
MapSide uint32 `json:"map_side" yaml:"map_side"`
FirstBlock string `json:"first_block"`
NbRounds uint32 `json:"nb_rounds" yaml:"nb_rounds"`
RoundDuration uint32 `json:"round_duration" yaml:"round_duration"`
CyclesPerRound uint32 `json:"cycles_per_round" yaml:"cycles_per_round"`
}
type PlayerInfos struct {
Rank uint32 `json:"rank"`
TeamKey string `json:"team_key"`
TeamPlayer uint32 `json:"team_player"`
}
type GameState struct {
Key string `json:"key"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
OwnerId string `json:"ownerId"`
FirstBlock string `json:"firstBlock"`
LastBlock string `json:"lastBlock"`
StartedAt *string `json:"startedAt"`
RoundEndsAt *string `json:"roundEndsAt"`
IsLocked bool `json:"isLocked"`
NbCyclesPerRound uint `json:"nbCyclesPerRound"`
CurrentRound uint32 `json:"currentRound"`
}
type AnyBlock struct {
Type string `json:"type"`
Parent string `json:"parent"`
Round uint32 `json:"round"`
}
type ProtocolBlock struct {
AnyBlock
Interface string `json:"interface"`
Implementation string `json:"implementation"`
}
type SetupBlock struct {
AnyBlock
GameParams GameParams `json:"game_params"`
}
type PlayerCommand struct {
PlayerRank uint32 `json:"player_rank"`
Command string `json:"command"`
}
type CommandBlock struct {
AnyBlock
Commands [][]PlayerCommand `json:"commands"`
}
|
package model
import (
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/bson/primitive"
"github.com/mongodb/mongo-go-driver/mongo"
log "github.com/sirupsen/logrus"
)
// VerifyApplication 申请中
const VerifyApplication = "application"
// VerifyPass 通过
const VerifyPass = "pass"
// VerifyReturn 打回
const VerifyReturn = "return"
// VerifyClosed 关闭
const VerifyClosed = "closed"
// Organization ...
type Organization struct {
Model `bson:",inline"`
IsDefault bool `bson:"is_default"` //是否为默认
Verify string `bson:"verify"` //验证状态
Corporate string `bson:"corporate"` //企业法人
CorporateIDCardFacade string `bson:"corporate_id_card_facade"` //法人身份证(正)
CorporateIDCardObverse string `bson:"corporate_id_card_obverse"` //法人身份证(反)
BusinessLicense string `bson:"business_license"` //营业执照
Name string `bson:"name"` //商户名称
Code string `bson:"code"` //社会统一信用代码
Contact string `bson:"contact"` //商户联系人
Position string `bson:"position"` //联系人职位
Phone string `bson:"phone"` //联系人手机号
Mailbox string `bson:"mailbox"` //联系人邮箱
IDCardFacade string `bson:"id_card_facade"` //联系人身份证(正)
IDCardObverse string `bson:"id_card_obverse"` //联系人身份证(反)
Description string `bson:"description"` //描述
}
// NewOrganization ...
func NewOrganization() *Organization {
return &Organization{
Model: model(),
}
}
// IsExist ...
func (o *Organization) IsExist() bool {
if o.ID != primitive.NilObjectID {
return IDExist(o)
}
return IsExist(o, bson.M{
"name": o.Name,
})
}
// All ...
func (o *Organization) All() ([]*Organization, error) {
var orgs []*Organization
m := bson.M{}
err := Find(o, m, func(cursor mongo.Cursor) error {
log.Println(cursor.DecodeBytes())
var o Organization
err := cursor.Decode(&o)
if err != nil {
return err
}
orgs = append(orgs, &o)
return nil
})
return orgs, err
}
// CreateIfNotExist ...
func (o *Organization) CreateIfNotExist() error {
return CreateIfNotExist(o)
}
// Create ...
func (o *Organization) Create() error {
return InsertOne(o)
}
// Update ...
func (o *Organization) Update() error {
return UpdateOne(o)
}
// Delete ...
func (o *Organization) Delete() error {
return DeleteByID(o)
}
// Find ...
func (o *Organization) Find() error {
return FindByID(o)
}
// Users ...
func (o *Organization) Users() ([]*User, error) {
var users []*User
err := Find(NewUser(), bson.M{
"organization_id": o.ID,
}, func(cursor mongo.Cursor) error {
user := NewUser()
err := cursor.Decode(user)
if err != nil {
return err
}
users = append(users, user)
return nil
})
return users, err
}
func (o *Organization) _Name() string {
return "organization"
}
|
func minPathSum(grid [][]int) int {
min:=func(a,b int)int{if a<b{return a};return b}
y:=len(grid)
x:=len(grid[0])
dp:=make([][]int, y)
for i:=range dp{ dp[i] = make([]int,x) }
dp[0][0] = grid[0][0]
for i:=1; i<y;i++{ dp[i][0] = grid[i][0]+dp[i-1][0] }
for i:=1; i<x;i++{ dp[0][i] = grid[0][i]+dp[0][i-1] }
for i:=1;i<y;i++{
for j:=1;j<x;j++{
dp[i][j] = grid[i][j]+min(dp[i-1][j],dp[i][j-1])
}
}
return dp[y-1][x-1]
}
|
/*
* @lc app=leetcode id=46 lang=golang
*
* [46] Permutations
*/
func per(pr *[][]int, nums []int, depth int) {
if depth == len(nums) {
a := make([]int, len(nums))
copy(a, nums)
*pr = append(*pr, a)
}
for i := depth; i < len(nums); i++ {
nums[i], nums[depth] = nums[depth], nums[i]
per(pr, nums, depth+1)
nums[i], nums[depth] = nums[depth], nums[i]
}
}
func permute(nums []int) [][]int {
var ret [][]int
per(&ret, nums, 0)
return ret
}
|
package xml
import (
"io"
"utf8"
"os"
)
// NOTE separate desc types from ?
const (
startType = iota
keyType
valueType
endType
charsType
cdataType
directiveType
commentType
eofType
)
const (
noneState = iota
startState
keyState
)
// NOTE a: Indexer
// NOTE: use bytes.Buffer instead of bytes ?
type parser struct {
reader io.Reader
index int
bytes []byte
buffer []byte
}
func makeParser(reader io.Reader) parser {
return parser{
reader: reader,
buffer: make([]byte, 1024),
}
}
type Mark struct { S, E int }
// NOTE eofType instead of f bool ?
func (p *parser) token() (tokenType int, mark Mark, marks []Mark, f bool) {
b, e := p.get()
if e { return }
f = true
if b != '<' {
p.back()
tokenType, mark = charsType, p.markUntilEOFOr('<')
return
}
switch p.mustGet() {
case '/':
tokenType, mark = endType, p.name()
if p.mustGetNonSpace() != '>' {
p.error("invalid characters between </ and >")
}
case '?':
index := p.index
var bb, b byte
for !(bb == '?' && b == '>') {
bb, b = b, p.mustGet()
}
tokenType, mark = directiveType, Mark{index, p.index - 2}
case '!':
switch p.mustGet() {
case '-':
if p.mustGet() != '-' {
p.error("invalid sequence <!- not part of <!--")
}
index := p.index
var b3, b2, b1 byte
for !(b3 == '-' && b2 == '-' && b1 == '>') {
b3, b2, b1 = b2, b1, p.mustGet()
}
tokenType, mark = commentType, Mark{index, p.index - 3}
case '[':
for i := 0; i < 6; i++ {
if p.mustGet() != "CDATA"[i] {
p.error("invalid <![ sequence")
}
}
index := p.index
var bb, b byte
for !(bb == ']' && b == ']') {
bb, b = b, p.mustGet()
}
tokenType, mark = cdataType, Mark{index, p.index - 2}
default:
}
default:
p.back()
tokenType, mark = startType, p.name()
var empty bool
for {
b := p.mustGetNonSpace()
if b == '/' { // empty tag
empty = true
if p.mustGet() != '>' {
p.error("expected /> in element")
}
break
} else if b == '>' {
break
}
p.back()
marks = append(marks, p.name())
if p.mustGetNonSpace() != '=' {
p.error("attribute name without = in element")
}
b = p.mustGetNonSpace()
if b != '\'' && b != '"' {
p.error("unquoted attribute value")
}
marks = append(marks, p.markUntil(b))
p.mustGet()
}
if empty {
marks = append(marks, Mark{})
}
}
return
}
func (p *parser) sliceBytes() (bytes []byte) {
bytes, p.bytes = p.bytes[:p.index], p.bytes[p.index:]
p.index = 0
return
}
func (p *parser) markEq(m1, m2 Mark) bool {
if m1.E - m1.S != m2.E - m2.S { return false }
i, j := m1.S, m2.S
for i < m1.E {
if p.bytes[i] != p.bytes[j] { return false }
i++; j++
}
return true
}
func (p *parser) string(m Mark) string {
return string(p.bytes[m.S:m.E])
}
func (p *parser) back() {
p.index--
}
type ParserError string
func (p *parser) error(s string) {
panic(ParserError(s))
}
// TODO more efficiently ? use bufio.Reader
func (p *parser) read() bool {
l, e := p.reader.Read(p.buffer)
// XXX when p.reader is tls.Conn Read can return (0, nil)
if l == 0 && e == nil {
l, e = p.reader.Read(p.buffer)
}
// buf = buf[:length]
// println("get: bytes =", string(bytes))
// assert (e == os.EOF && p.l == 0)
if e != nil {
if e == os.EOF {
return false
} else {
panic(e)
}
}
p.bytes = append(p.bytes, p.buffer[:l]...)
return true
}
func (p *parser) mustRead() {
if !p.read() {
p.error("unexpected EOF")
}
}
func (p *parser) get() (b byte, e bool) {
if p.index == len(p.bytes) {
if !p.read() {
e = true
return
}
}
b = p.bytes[p.index]
p.index++
return
}
func (p *parser) mustGet() byte {
b, e := p.get()
if e { p.error("unexpected EOF") }
return b
}
func isSpace(b byte) bool {
return b == ' ' || b == '\r' || b == '\n' || b == '\t'
}
func (p *parser) mustGetNonSpace() (b byte) {
for {
if p.index == len(p.bytes) {
p.mustRead()
}
b = p.bytes[p.index]
p.index++
if !isSpace(b) {
break
}
}
return
}
func (p *parser) markUntil(b byte) (m Mark) {
m.S = p.index
for {
if p.index == len(p.bytes) {
p.mustRead()
}
if p.bytes[p.index] == b {
break
}
p.index++
}
m.E = p.index
return
}
func (p *parser) markUntilEOFOr(b byte) (m Mark) {
m.S = p.index
for {
if p.index == len(p.bytes) {
if !p.read() {
break
}
}
if p.bytes[p.index] == b {
break
}
p.index++
}
m.E = p.index
return
}
func isNameByte(b byte) bool {
return 'A' <= b && b <= 'Z' ||
'a' <= b && b <= 'z' ||
'0' <= b && b <= '9' ||
b == '_' || b == ':' || b == '.' || b == '-'
}
func (p *parser) name() (m Mark) {
m.S = p.index
if b := p.mustGet(); !(b >= utf8.RuneSelf || isNameByte(b)) {
p.error("invalid tag name first letter")
}
for {
if p.index == len(p.bytes) {
p.mustRead()
}
if b := p.bytes[p.index]; !(b >= utf8.RuneSelf || isNameByte(b)) {
break
}
p.index++
}
m.E = p.index
return
// TODO check the characters in [i:p.index]
}
|
package isis
type IsisRpc struct {
Information struct {
Adjacencies []IsisAdjacenciesRpc `xml:"isis-adjacency"`
} `xml:"isis-adjacency-information"`
}
type IsisAdjacenciesRpc struct {
InterfaceName string `xml:"interface-name"`
SystemName string `xml:"system-name"`
Level int64 `xml:"level"`
AdjacencyState string `xml:"adjacency-state"`
Holdtime int64 `xml:"holdtime"`
SNPA string `xml:"snpa"`
}
|
/**
* User: ghostwwl
* Date: 16-12-4
* Time: 上午11:17
*/
package main
import (
//"bufio"
"database/sql"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os/exec"
//"net"
//"strings"
"strings"
"os"
)
func main() {
//runHttpService()
runHttpService2()
}
func PathExists(fpath string) bool {
_, err := os.Stat(fpath)
if nil == err {
return true
} else if os.IsNotExist(err) {
return false
}
return false
}
var STATIC_PATH_MAP map[string]string
func runHttpService2() {
mux := http.NewServeMux()
mux.HandleFunc("/h", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Go net/http Test!!!"))
})
mux.HandleFunc("/bye", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "byebye")
})
mux.HandleFunc("/hello", handle_hello)
mux.HandleFunc("/index", handle_index)
mux.HandleFunc("/uptime", handle_uptime)
mux.HandleFunc("/tobaidu", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://www.baidu.com", http.StatusFound)
})
STATIC_PATH_MAP = make(map[string]string)
STATIC_PATH_MAP["/src"] = "./test"
STATIC_PATH_MAP["/baidu"] = "/data/ghostwwl/html-百度"
// 运行过程中动态增加静态目录呢
mux.HandleFunc("/add_static", func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
fmt.Fprintf(w, "\nerror: %v", err)
//return
}
src := r.Form.Get("s")
local := r.Form.Get("l")
if len(src) < 1 && len(local) < 1 {
fmt.Fprintf(w, "参数错误")
return
}
STATIC_PATH_MAP[src] = local
fmt.Fprintf(w, "%v", STATIC_PATH_MAP)
fmt.Fprintf(w, "OK")
})
// 其它情况的handle呢
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// 静态文件服务
path_array_list := strings.Split(r.URL.Path, "/")
alias_path := "/" + path_array_list[1]
localdir, has_static_map := STATIC_PATH_MAP[alias_path];
if has_static_map {
local_file_path := localdir + r.URL.Path[len(alias_path):]
log.Printf("Get File:%s", local_file_path)
if PathExists(local_file_path) {
http.ServeFile(w, r, local_file_path)
} else {
http.Error(w, "File Not Exists", 404)
}
return
}
// end 静态文件
// 获取 cookie
mycv, xer := r.Cookie("testcook")
if nil != xer{
fmt.Fprintf(w, "%v", xer)
} else {
fmt.Fprintf(w, "%v", mycv.Value)
}
// 跳转
//w.Header().Set("Location", "/uptime")
//w.WriteHeader(302)
// use cookie
cookie := http.Cookie{
Name: "testcook",
Value: "123",
Path: "/",
}
http.SetCookie(w, &cookie)
log.Println(r.RequestURI)
//http.Error(w, "我靠 404 了", 404)
fmt.Fprintf(w, "我靠 404 了\n")
fmt.Fprintf(w, "Thanks for the %s query: %s", r.Method, r.URL.RawQuery)
fmt.Fprintf(w, "\npath: ", r.Method, r.URL.Path)
fmt.Fprintf(w, "\nYou IP: %s", r.RemoteAddr)
fmt.Fprintf(w, "\nUserAgent: %s", r.UserAgent())
err := r.ParseForm()
if err != nil {
fmt.Fprintf(w, "\nerror: %v", err)
//return
}
fmt.Fprintf(w, "\nparam: %v", r.Form.Get("a"))
fmt.Fprintf(w, "\nparam: %v", r.FormValue("b"))
fmt.Fprintf(w, "\nGET: %v", r.URL.Query())
fmt.Fprintf(w, "\nGET: %v", r.Form)
fmt.Fprintf(w, "\nPOST: %v", r.PostForm)
err = r.ParseMultipartForm(16 << 20)
if nil != err {
fmt.Fprintf(w, "\nParseMultipartForm Error: %v", err)
} else {
fmt.Fprintf(w, "\nMutilPOST: %v", r.MultipartForm.Value)
}
// r.URL.Query() --> 获取到的是 GET 的MAP
// r.ParseForm() 之后
// r.Form 获取到的是 GET 和 url-encode 方式POST的 MAP
// r.PostForm 获取到 url-encode post的 参数
// r.ParseMultipartForm(16 << 20) // 16 mb -- 如果connected不是 multipart/form-data 会报错
// r.MultipartForm.Value 获取到的是 multipart/form-data 上传的 MAP 这个时候 r.PostForm 是空的
})
//http.Request
http.ListenAndServe(":8001", mux)
}
//---------------------------------------------------------------------
func runHttpService() {
// http.HandleFunc("/index", handle_index)
// http.HandleFunc("/hello", handle_hello)
// http.ListenAndServe(":8001", nil)
http.ListenAndServe(":8001", &http_handle{})
}
type http_handle struct{}
func (*http_handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.String() //获得访问的路径
//io.WriteString(w, path)
switch r.URL.String() {
case "/hello":
handle_hello(w, r)
break
case "/index":
handle_index(w, r)
break
default:
w.Write([]byte(path))
}
}
//---------------------------------------------------------------------
func handle_index(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("你吃了么?\n"))
w.Write([]byte("我还没吃?"))
}
func handle_hello(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Hello"))
}
func handle_uptime(w http.ResponseWriter, req *http.Request) {
cmd := exec.Command("uptime")
//cmd2 := exec.Command("last")
bytes, err := cmd.Output()
if err != nil {
//fmt.Println("cmd.Output: ", err)
fmt.Fprintf(w, "出错了: %s", err)
} else {
fmt.Fprintf(w, "服务器uptime为: %s\n", string(bytes))
}
//lastr, err := cmd2.Output()
//if err != nil {
// //fmt.Println("cmd.Output: ", err)
// fmt.Fprintf(w, "出错了: %s", err)
//} else {
// fmt.Fprintf(w, "服务器last为: %s", string(lastr))
//}
}
|
package accrew
import (
"math"
"math/rand"
"github.com/devinmcgloin/clr/clr"
"github.com/devinmcgloin/sail/pkg/slog"
"github.com/fogleman/gg"
)
type pointColor struct {
Point gg.Point
Color clr.Color
}
//DotLines defines the type of sketch
type DotLines struct{}
//Dimensions determes the size of the sketch to be rendered
func (dl DotLines) Dimensions() (int, int) {
return int(dl.Width()), int(dl.Height())
}
// Width defines the width of the sketch
func (dl DotLines) Width() float64 {
return 1000.0
}
// Height defines the width of the sketch
func (dl DotLines) Height() float64 {
return 1000.0
}
// Draw renders the sketch on the given context with the seed
func (dl DotLines) Draw(context *gg.Context, rand *rand.Rand) {
rungs := rand.Intn(30) + 5
hue := rand.Intn(365)
margins := rand.Float64() * 300
spacing := rand.Intn(30) + 10
delta := rand.Float64()*float64(spacing) + 5
slog.InfoValues("margins", margins)
w := dl.Width() - margins*2
h := dl.Height() - margins*2
slog.InfoValues("h", h, "w", w)
x0 := w*rand.Float64() + margins
y0 := h*rand.Float64() + margins
x1 := w*rand.Float64() + margins
y1 := h*rand.Float64() + margins
x2 := w*rand.Float64() + margins
y2 := h*rand.Float64() + margins
slog.InfoValues("rungs", rungs, "delta", delta)
var pointColors []pointColor
for i := 0; i < rungs; i++ {
color := clr.HSV{H: hue, S: (100 / rungs) * i, V: 70}
x0 += delta
y0 += delta
x1 += delta
y1 += delta
x2 += delta
y2 += delta
points := quadraticBezier(x0, y0, x1, y1, x2, y2, spacing)
for _, p := range points {
pointColors = append(pointColors, pointColor{Color: color, Point: p})
}
}
slog.InfoValues("len(point)", len(pointColors))
x, y := boundingBox(pointColors)
slog.InfoValues("boundX", x, "boundY", y)
sw, sh := y.X-x.X, y.Y-x.Y
slog.InfoValues("sw", sw, "sh", sh)
//context.DrawRectangle(x.X, x.Y, sw, sh)
slog.InfoValues("desiredX", (w-sw)/2, "desiredY", (h-sh)/2)
deltaX := (w-sw)/2 - x.X
deltaY := (h-sh)/2 - x.Y
slog.InfoValues("deltaX", deltaX, "deltaY", deltaY)
context.Translate(deltaX+margins, deltaY+margins)
for _, p := range pointColors {
r, g, b := p.Color.RGB()
context.SetRGB(float64(r), float64(g), float64(b))
context.DrawPoint(p.Point.X, p.Point.Y, 2)
context.Fill()
}
}
func boundingBox(points []pointColor) (x, y gg.Point) {
x.X, x.Y = math.MaxFloat64, math.MaxFloat64
for _, pc := range points {
if pc.Point.X < x.X {
x.X = pc.Point.X
}
if pc.Point.Y < x.Y {
x.Y = pc.Point.Y
}
if pc.Point.X > y.X {
y.X = pc.Point.X
}
if pc.Point.Y > y.Y {
y.Y = pc.Point.Y
}
}
return
}
func quadratic(x0, y0, x1, y1, x2, y2, t float64) (x, y float64) {
u := 1 - t
a := u * u
b := 2 * u * t
c := t * t
x = a*x0 + b*x1 + c*x2
y = a*y0 + b*y1 + c*y2
return
}
func quadraticBezier(x0, y0, x1, y1, x2, y2 float64, sampleRate int) []gg.Point {
l := (math.Hypot(x1-x0, y1-y0) +
math.Hypot(x2-x1, y2-y1))
n := int(l + 0.5)
if n < 4 {
n = 4
}
d := float64(n) - 1
var result []gg.Point
for i := 0; i < n; i += sampleRate {
t := float64(i) / d
x, y := quadratic(x0, y0, x1, y1, x2, y2, t)
result = append(result, gg.Point{X: x, Y: y})
}
return result
}
|
package main
import (
"github.com/hashicorp/memberlist"
)
// Broadcast is something that can be broadcasted via gossip to
// the memberlist cluster.
type broadcast struct {
msg []byte
notify chan<- struct{}
}
// Invalidates checks if enqueuing the current broadcast
// invalidates a previous broadcast
func (b *broadcast) Invalidates(other memberlist.Broadcast) bool {
return false
}
// Returns a byte form of the message
func (b *broadcast) Message() []byte {
return b.msg
}
// Finished is invoked when the message will no longer
// be broadcast, either due to invalidation or to the
// transmit limit being reached
func (b *broadcast) Finished() {
if b.notify != nil {
close(b.notify)
}
}
|
package main
import (
"github.com/ofpiyush/automerger/automerger"
)
func main() {
automerger.Serve(automerger.ConfigureOrDie())
}
|
package orm
import (
"time"
_ "github.com/go-sql-driver/mysql" // justifying
"github.com/go-xorm/xorm"
"xorm.io/core"
"github.com/any-lyu/go.library/errors"
"github.com/any-lyu/go.library/logs"
xtime "github.com/any-lyu/go.library/time"
)
// Config database config.
type Config struct {
DSN string // data source name.
Active int // pool
Idle int // pool
IdleTimeout xtime.Duration // connect max life time.
}
type ormLog struct {
showSQL bool
}
func (l ormLog) Debug(v ...interface{}) {
logs.Debug(v)
}
func (l ormLog) Debugf(format string, v ...interface{}) {
logs.Debug(format, v...)
}
func (l ormLog) Error(v ...interface{}) {
logs.Error(v)
}
func (l ormLog) Errorf(format string, v ...interface{}) {
logs.Error(format, v...)
}
func (l ormLog) Info(v ...interface{}) {
logs.Info(v)
}
func (l ormLog) Infof(format string, v ...interface{}) {
logs.Info(format, v...)
}
func (l ormLog) Warn(v ...interface{}) {
logs.Warn(v)
}
func (l ormLog) Warnf(format string, v ...interface{}) {
logs.Warn(format, v...)
}
func (l ormLog) Level() core.LogLevel {
return core.LogLevel(logs.GetLevel())
}
func (l ormLog) SetLevel(level core.LogLevel) {
logs.Info("ormLog-SetLevel-Invalid")
}
func (l ormLog) ShowSQL(show ...bool) {
if len(show) == 0 {
l.showSQL = true
} else {
l.showSQL = show[0]
}
}
func (l ormLog) IsShowSQL() bool {
return l.showSQL
}
func init() {
xorm.ErrNotExist = errors.ErrNotFount
}
// NewMySQL new db and retry connection when has error.
func NewMySQL(c *Config) (db *xorm.Engine) {
db, err := xorm.NewEngine("database", c.DSN)
if err != nil {
logs.Error("db dsn(%s) error: %v", c.DSN, err)
panic(err)
}
db.DB().SetMaxIdleConns(c.Idle)
db.DB().SetMaxOpenConns(c.Active)
db.DB().SetConnMaxLifetime(time.Duration(c.IdleTimeout) / time.Second)
db.SetLogger(ormLog{})
return
}
|
package main
import (
"fmt"
)
func main() {
x := []string{"Sun", "Moon", "Star", "Jupitar", "Earth", "Planet"}
fmt.Println(x)
x = append(x, "Tree", "Forest", "Land") //func append(slice []T, elements ...T) []T
fmt.Println(x)
y := []string{"Honey", "Penny", "Money", "Funny"}
x = append(x, y...) //x = append(x, 4, 5, 6)
fmt.Println(x)
for i, v := range x {
fmt.Println(i, v)
}
fmt.Println("\tAnother one")
for i := 0; i <= 12; i++ {
fmt.Println(i, x[i])
}
//delete Jupitar and Earth
x = append(x[:2], x[5:]...)
fmt.Println(x)
}
|
package server
import (
"bytes"
"io"
"golang.org/x/net/websocket"
)
type wsconn struct {
ws *websocket.Conn
backend []*bytes.Buffer
index int
}
func NewWSConn(ws *websocket.Conn) *wsconn {
conn := &wsconn{}
conn.ws = ws
conn.backend = make([]*bytes.Buffer, 2)
conn.backend[0] = bytes.NewBuffer(nil)
conn.backend[1] = bytes.NewBuffer(nil)
conn.index = 0
return conn
}
func (conn *wsconn) Read(buf []byte) (n int, err error) {
r := conn.backend[conn.index]
min := len(buf)
for {
for n < min && err == nil {
var nn int
nn, err = r.Read(buf[n:])
n += nn
}
if n >= min {
err = nil
conn.index = (conn.index + 1) % len(conn.backend)
r.WriteTo(conn.backend[conn.index])
r.Reset()
return
} else if err == io.EOF {
r.Reset()
var data []byte
err = websocket.Message.Receive(conn.ws, &data)
if err != nil {
return
}
r.Write(data)
}
}
return
}
func (conn *wsconn) Write(p []byte) (n int, err error) {
err = websocket.Message.Send(conn.ws, p)
n = len(p)
return
}
func (conn *wsconn) Close() error {
return conn.ws.Close()
}
|
package portsbinding
import (
"testing"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/acceptance/tools"
"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/portsbinding"
"github.com/gophercloud/gophercloud/openstack/networking/v2/ports"
)
// CreatePortsbinding will create a port on the specified subnet. An error will be
// returned if the port could not be created.
func CreatePortsbinding(t *testing.T, client *gophercloud.ServiceClient, networkID, subnetID, hostID string) (*portsbinding.Port, error) {
portName := tools.RandomString("TESTACC-", 8)
iFalse := false
t.Logf("Attempting to create port: %s", portName)
createOpts := portsbinding.CreateOpts{
CreateOptsBuilder: ports.CreateOpts{
NetworkID: networkID,
Name: portName,
AdminStateUp: &iFalse,
FixedIPs: []ports.IP{ports.IP{SubnetID: subnetID}},
},
HostID: hostID,
}
port, err := portsbinding.Create(client, createOpts).Extract()
if err != nil {
return port, err
}
t.Logf("Successfully created port: %s", portName)
return port, nil
}
// PrintPortsbinging will print a port and all of its attributes.
func PrintPortsbinding(t *testing.T, port *portsbinding.Port) {
t.Logf("ID: %s", port.ID)
t.Logf("NetworkID: %s", port.NetworkID)
t.Logf("Name: %s", port.Name)
t.Logf("AdminStateUp: %t", port.AdminStateUp)
t.Logf("Status: %s", port.Status)
t.Logf("MACAddress: %s", port.MACAddress)
t.Logf("FixedIPs: %s", port.FixedIPs)
t.Logf("TenantID: %s", port.TenantID)
t.Logf("DeviceOwner: %s", port.DeviceOwner)
t.Logf("SecurityGroups: %s", port.SecurityGroups)
t.Logf("DeviceID: %s", port.DeviceID)
t.Logf("DeviceOwner: %s", port.DeviceOwner)
t.Logf("AllowedAddressPairs: %s", port.AllowedAddressPairs)
t.Logf("HostID: %s", port.HostID)
t.Logf("VNICType: %s", port.VNICType)
}
|
package log
// Logger interface taken from https://github.com/golang/go/issues/28412
type Logger interface {
// all levels + Prin
Print(v ...interface{})
Printf(format string, v ...interface{})
Println(v ...interface{})
Info(v ...interface{})
Infof(format string, v ...interface{})
Infoln(v ...interface{})
Warn(v ...interface{})
Warnf(format string, v ...interface{})
Warnln(v ...interface{})
Error(v ...interface{})
Errorf(format string, v ...interface{})
Errorln(v ...interface{})
Fatal(v ...interface{})
Fatalf(format string, v ...interface{})
Fatalln(v ...interface{})
Panic(v ...interface{})
Panicf(format string, v ...interface{})
Panicln(v ...interface{})
// Prefix - chainable so it can create a logger instance, safe for concurrent use
Prefix(prefix string) Logger
// Prefixf to avoid having to use fmt.Sprintf whenever using this
Prefixf(fromat string, v ...interface{}) Logger
// fields for other formatters, acts like prefix be default
WithField(k, v interface{}) Logger
}
|
package gui
import (
"github.com/jesseduffield/gocui"
)
const UNKNOWN_VIEW_ERROR_MSG = "unknown view"
// getFocusLayout returns a manager function for when view gain and lose focus
func (gui *Gui) getFocusLayout() func(g *gocui.Gui) error {
var previousView *gocui.View
return func(g *gocui.Gui) error {
newView := gui.g.CurrentView()
if err := gui.onFocusChange(); err != nil {
return err
}
// for now we don't consider losing focus to a popup panel as actually losing focus
if newView != previousView && !gui.isPopupPanel(newView.Name()) {
gui.onFocusLost(previousView, newView)
gui.onFocus(newView)
previousView = newView
}
return nil
}
}
func (gui *Gui) onFocusChange() error {
currentView := gui.g.CurrentView()
for _, view := range gui.g.Views() {
view.Highlight = view == currentView && view.Name() != "main"
}
return nil
}
func (gui *Gui) onFocusLost(v *gocui.View, newView *gocui.View) {
if v == nil {
return
}
if !gui.isPopupPanel(newView.Name()) {
v.ParentView = nil
}
// refocusing because in responsive mode (when the window is very short) we want to ensure that after the view size changes we can still see the last selected item
gui.focusPointInView(v)
gui.Log.Info(v.Name() + " focus lost")
}
func (gui *Gui) onFocus(v *gocui.View) {
if v == nil {
return
}
gui.focusPointInView(v)
gui.Log.Info(v.Name() + " focus gained")
}
// layout is called for every screen re-render e.g. when the screen is resized
func (gui *Gui) layout(g *gocui.Gui) error {
g.Highlight = true
width, height := g.Size()
appStatus := gui.statusManager.getStatusString()
viewDimensions := gui.getWindowDimensions(gui.getInformationContent(), appStatus)
// we assume that the view has already been created.
setViewFromDimensions := func(viewName string, windowName string) (*gocui.View, error) {
dimensionsObj, ok := viewDimensions[windowName]
view, err := g.View(viewName)
if err != nil {
return nil, err
}
if !ok {
// view not specified in dimensions object: so create the view and hide it
// making the view take up the whole space in the background in case it needs
// to render content as soon as it appears, because lazyloaded content (via a pty task)
// cares about the size of the view.
_, err := g.SetView(viewName, 0, 0, width, height, 0)
view.Visible = false
return view, err
}
frameOffset := 1
if view.Frame {
frameOffset = 0
}
_, err = g.SetView(
viewName,
dimensionsObj.X0-frameOffset,
dimensionsObj.Y0-frameOffset,
dimensionsObj.X1+frameOffset,
dimensionsObj.Y1+frameOffset,
0,
)
view.Visible = true
return view, err
}
for _, viewName := range gui.autoPositionedViewNames() {
_, err := setViewFromDimensions(viewName, viewName)
if err != nil && err.Error() != UNKNOWN_VIEW_ERROR_MSG {
return err
}
}
// here is a good place log some stuff
// if you download humanlog and do tail -f development.log | humanlog
// this will let you see these branches as prettified json
// gui.Log.Info(utils.AsJson(gui.State.Branches[0:4]))
return gui.resizeCurrentPopupPanel(g)
}
func (gui *Gui) focusPointInView(view *gocui.View) {
if view == nil {
return
}
currentPanel, ok := gui.currentListPanel()
if ok {
currentPanel.Refocus()
}
}
func (gui *Gui) prepareView(viewName string) (*gocui.View, error) {
// arbitrarily giving the view enough size so that we don't get an error, but
// it's expected that the view will be given the correct size before being shown
return gui.g.SetView(viewName, 0, 0, 10, 10, 0)
}
|
package main
import "fmt"
func main() {
// Define map
emails := make(map[string]string)
//Assign kv
emails["Bob"] = "bob@gmail.com"
emails["Sharon"] = "sharon@gmail.com"
emails["Delete"] = "to_delete@gmail.com"
fmt.Println(emails,len(emails))
delete(emails,"Delete")
fmt.Println(emails)
emailsDefinedWithAssignment := map[string]string{"Bob":"bob@gmail.com","Sharon":"sharoon@gmail.com"}
fmt.Println(emailsDefinedWithAssignment)
namesDefinedWithAssignment := map[int]string{1:"Jake",2:"Jones",5:"Bill"}
fmt.Println(namesDefinedWithAssignment)
delete(namesDefinedWithAssignment,2)
fmt.Println(namesDefinedWithAssignment,namesDefinedWithAssignment[5])
} |
package help
const (
root = "https://github.com/argoproj/argo/blob/master/docs"
ArgoSever = root + "/argo-server.md"
CLI = root + "/cli.md"
WorkflowTemplates = root + "/workflow-templates.md"
WorkflowTemplatesReferencingOtherTemplates = WorkflowTemplates + "#referencing-other-workflowtemplates"
)
|
// Copyright 2018 Andrew Bates
//
// 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 insteon
import "time"
// I2Device can communicate with Version 2 Insteon Engines
type I2Device struct {
*I1Device
}
// NewI2Device will construct an device object that can communicate with version 2
// Insteon engines
func NewI2Device(address Address, sendCh chan<- *MessageRequest, recvCh <-chan *Message, timeout time.Duration) *I2Device {
return &I2Device{NewI1Device(address, sendCh, recvCh, timeout)}
}
// AddLink will either add the link to the All-Link database
// or it will replace an existing link-record that has been marked
// as deleted
func (i2 *I2Device) AddLink(newLink *LinkRecord) error {
return ErrNotImplemented
}
// RemoveLinks will either remove the link records from the device
// All-Link database, or it will simply mark them as deleted
func (i2 *I2Device) RemoveLinks(oldLinks ...*LinkRecord) error {
return ErrNotImplemented
}
// Links will retrieve the link-database from the device and
// return a list of LinkRecords
func (i2 *I2Device) Links() (links []*LinkRecord, err error) {
Log.Debugf("Retrieving Device link database")
lastAddress := MemAddress(0)
buf, _ := (&LinkRequest{Type: ReadLink, NumRecords: 0}).MarshalBinary()
recvCh, err := i2.SendCommandAndListen(CmdReadWriteALDB, buf)
for response := range recvCh {
if response.Message.Flags.Extended() && response.Message.Command[1] == CmdReadWriteALDB[1] {
lr := &LinkRequest{}
err = lr.UnmarshalBinary(response.Message.Payload)
// make sure there was no error unmarshalling, also make sure
// that it's a new memory address. Since insteon messages
// are retransmitted, it is possible that the same ALDB response
// will be received more than once
if err == nil && lr.MemAddress != lastAddress {
lastAddress = lr.MemAddress
links = append(links, lr.Link)
} else if err != nil {
if err == ErrEndOfLinks {
err = nil
}
response.DoneCh <- response
}
}
}
return links, err
}
// EnterLinkingMode is the programmatic equivalent of holding down
// the set button for two seconds. If the device is the first
// to enter linking mode, then it is the controller. The next
// device to enter linking mode is the responder. LinkingMode
// is usually indicated by a flashing GREEN LED on the device
func (i2 *I2Device) EnterLinkingMode(group Group) error {
return extractError(i2.SendCommand(CmdEnterLinkingMode.SubCommand(int(group)), nil))
}
// EnterUnlinkingMode puts a controller device into unlinking mode
// when the set button is then pushed (EnterLinkingMode) on a linked
// device the corresponding links in both the controller and responder
// are deleted. EnterUnlinkingMode is the programmatic equivalent
// to pressing the set button until the device beeps, releasing, then
// pressing the set button again until the device beeps again. UnlinkingMode
// is usually indicated by a flashing RED LED on the device
func (i2 *I2Device) EnterUnlinkingMode(group Group) error {
return extractError(i2.SendCommand(CmdEnterUnlinkingMode.SubCommand(int(group)), nil))
}
// ExitLinkingMode takes a controller out of linking/unlinking mode.
func (i2 *I2Device) ExitLinkingMode() error {
return extractError(i2.SendCommand(CmdExitLinkingMode, nil))
}
// WriteLink will write the link record to the device's link database
func (i2 *I2Device) WriteLink(link *LinkRecord) (err error) {
if link.memAddress == MemAddress(0x0000) {
err = ErrInvalidMemAddress
} else {
buf, _ := (&LinkRequest{MemAddress: link.memAddress, Type: WriteLink, Link: link}).MarshalBinary()
_, err = i2.SendCommand(CmdReadWriteALDB, buf)
}
return err
}
// String returns the string "I2 Device (<address>)" where <address> is the destination
// address of the device
func (i2 *I2Device) String() string {
return sprintf("I2 Device (%s)", i2.Address())
}
|
// Copyright 2023 Google LLC. 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 compute
import (
"context"
"fmt"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
dclService "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/alpha"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured"
)
type NetworkFirewallPolicyAssociation struct{}
func NetworkFirewallPolicyAssociationToUnstructured(r *dclService.NetworkFirewallPolicyAssociation) *unstructured.Resource {
u := &unstructured.Resource{
STV: unstructured.ServiceTypeVersion{
Service: "compute",
Version: "alpha",
Type: "NetworkFirewallPolicyAssociation",
},
Object: make(map[string]interface{}),
}
if r.AttachmentTarget != nil {
u.Object["attachmentTarget"] = *r.AttachmentTarget
}
if r.FirewallPolicy != nil {
u.Object["firewallPolicy"] = *r.FirewallPolicy
}
if r.Location != nil {
u.Object["location"] = *r.Location
}
if r.Name != nil {
u.Object["name"] = *r.Name
}
if r.Project != nil {
u.Object["project"] = *r.Project
}
if r.ShortName != nil {
u.Object["shortName"] = *r.ShortName
}
return u
}
func UnstructuredToNetworkFirewallPolicyAssociation(u *unstructured.Resource) (*dclService.NetworkFirewallPolicyAssociation, error) {
r := &dclService.NetworkFirewallPolicyAssociation{}
if _, ok := u.Object["attachmentTarget"]; ok {
if s, ok := u.Object["attachmentTarget"].(string); ok {
r.AttachmentTarget = dcl.String(s)
} else {
return nil, fmt.Errorf("r.AttachmentTarget: expected string")
}
}
if _, ok := u.Object["firewallPolicy"]; ok {
if s, ok := u.Object["firewallPolicy"].(string); ok {
r.FirewallPolicy = dcl.String(s)
} else {
return nil, fmt.Errorf("r.FirewallPolicy: expected string")
}
}
if _, ok := u.Object["location"]; ok {
if s, ok := u.Object["location"].(string); ok {
r.Location = dcl.String(s)
} else {
return nil, fmt.Errorf("r.Location: expected string")
}
}
if _, ok := u.Object["name"]; ok {
if s, ok := u.Object["name"].(string); ok {
r.Name = dcl.String(s)
} else {
return nil, fmt.Errorf("r.Name: expected string")
}
}
if _, ok := u.Object["project"]; ok {
if s, ok := u.Object["project"].(string); ok {
r.Project = dcl.String(s)
} else {
return nil, fmt.Errorf("r.Project: expected string")
}
}
if _, ok := u.Object["shortName"]; ok {
if s, ok := u.Object["shortName"].(string); ok {
r.ShortName = dcl.String(s)
} else {
return nil, fmt.Errorf("r.ShortName: expected string")
}
}
return r, nil
}
func GetNetworkFirewallPolicyAssociation(ctx context.Context, config *dcl.Config, u *unstructured.Resource) (*unstructured.Resource, error) {
c := dclService.NewClient(config)
r, err := UnstructuredToNetworkFirewallPolicyAssociation(u)
if err != nil {
return nil, err
}
r, err = c.GetNetworkFirewallPolicyAssociation(ctx, r)
if err != nil {
return nil, err
}
return NetworkFirewallPolicyAssociationToUnstructured(r), nil
}
func ListNetworkFirewallPolicyAssociation(ctx context.Context, config *dcl.Config, project string, location string, firewallPolicy string) ([]*unstructured.Resource, error) {
c := dclService.NewClient(config)
l, err := c.ListNetworkFirewallPolicyAssociation(ctx, project, location, firewallPolicy)
if err != nil {
return nil, err
}
var resources []*unstructured.Resource
for {
for _, r := range l.Items {
resources = append(resources, NetworkFirewallPolicyAssociationToUnstructured(r))
}
if !l.HasNext() {
break
}
if err := l.Next(ctx, c); err != nil {
return nil, err
}
}
return resources, nil
}
func ApplyNetworkFirewallPolicyAssociation(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) {
c := dclService.NewClient(config)
r, err := UnstructuredToNetworkFirewallPolicyAssociation(u)
if err != nil {
return nil, err
}
if ush := unstructured.FetchStateHint(opts); ush != nil {
sh, err := UnstructuredToNetworkFirewallPolicyAssociation(ush)
if err != nil {
return nil, err
}
opts = append(opts, dcl.WithStateHint(sh))
}
r, err = c.ApplyNetworkFirewallPolicyAssociation(ctx, r, opts...)
if err != nil {
return nil, err
}
return NetworkFirewallPolicyAssociationToUnstructured(r), nil
}
func NetworkFirewallPolicyAssociationHasDiff(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) {
c := dclService.NewClient(config)
r, err := UnstructuredToNetworkFirewallPolicyAssociation(u)
if err != nil {
return false, err
}
if ush := unstructured.FetchStateHint(opts); ush != nil {
sh, err := UnstructuredToNetworkFirewallPolicyAssociation(ush)
if err != nil {
return false, err
}
opts = append(opts, dcl.WithStateHint(sh))
}
opts = append(opts, dcl.WithLifecycleParam(dcl.BlockDestruction), dcl.WithLifecycleParam(dcl.BlockCreation), dcl.WithLifecycleParam(dcl.BlockModification))
_, err = c.ApplyNetworkFirewallPolicyAssociation(ctx, r, opts...)
if err != nil {
if _, ok := err.(dcl.ApplyInfeasibleError); ok {
return true, nil
}
return false, err
}
return false, nil
}
func DeleteNetworkFirewallPolicyAssociation(ctx context.Context, config *dcl.Config, u *unstructured.Resource) error {
c := dclService.NewClient(config)
r, err := UnstructuredToNetworkFirewallPolicyAssociation(u)
if err != nil {
return err
}
return c.DeleteNetworkFirewallPolicyAssociation(ctx, r)
}
func NetworkFirewallPolicyAssociationID(u *unstructured.Resource) (string, error) {
r, err := UnstructuredToNetworkFirewallPolicyAssociation(u)
if err != nil {
return "", err
}
return r.ID()
}
func (r *NetworkFirewallPolicyAssociation) STV() unstructured.ServiceTypeVersion {
return unstructured.ServiceTypeVersion{
"compute",
"NetworkFirewallPolicyAssociation",
"alpha",
}
}
func (r *NetworkFirewallPolicyAssociation) SetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) (*unstructured.Resource, error) {
return nil, unstructured.ErrNoSuchMethod
}
func (r *NetworkFirewallPolicyAssociation) GetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, role, member string) (*unstructured.Resource, error) {
return nil, unstructured.ErrNoSuchMethod
}
func (r *NetworkFirewallPolicyAssociation) DeletePolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) error {
return unstructured.ErrNoSuchMethod
}
func (r *NetworkFirewallPolicyAssociation) SetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) {
return nil, unstructured.ErrNoSuchMethod
}
func (r *NetworkFirewallPolicyAssociation) SetPolicyWithEtag(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) {
return nil, unstructured.ErrNoSuchMethod
}
func (r *NetworkFirewallPolicyAssociation) GetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) {
return nil, unstructured.ErrNoSuchMethod
}
func (r *NetworkFirewallPolicyAssociation) Get(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) {
return GetNetworkFirewallPolicyAssociation(ctx, config, resource)
}
func (r *NetworkFirewallPolicyAssociation) Apply(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) {
return ApplyNetworkFirewallPolicyAssociation(ctx, config, resource, opts...)
}
func (r *NetworkFirewallPolicyAssociation) HasDiff(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) {
return NetworkFirewallPolicyAssociationHasDiff(ctx, config, resource, opts...)
}
func (r *NetworkFirewallPolicyAssociation) Delete(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) error {
return DeleteNetworkFirewallPolicyAssociation(ctx, config, resource)
}
func (r *NetworkFirewallPolicyAssociation) ID(resource *unstructured.Resource) (string, error) {
return NetworkFirewallPolicyAssociationID(resource)
}
func init() {
unstructured.Register(&NetworkFirewallPolicyAssociation{})
}
|
package models
type CommitAuthor struct {
Name string
Email string
}
type Commit struct {
Sha string
Distinct bool
Message string
Author *CommitAuthor
}
|
package sql
import (
"fmt"
)
type Catalog struct {
Databases []Database
}
func (c Catalog) Database(name string) (Database, error) {
for _, db := range c.Databases {
if db.Name() == name {
return db, nil
}
}
return nil, fmt.Errorf("database not found: %s", name)
}
func (c Catalog) Table(dbName string, tableName string) (Table, error) {
db, err := c.Database(dbName)
if err != nil {
return nil, err
}
tables := db.Tables()
table, found := tables[tableName]
if !found {
return nil, fmt.Errorf("table not found: %s", tableName)
}
return table, nil
}
|
package gps
import "testing"
type testStruct struct {
A bool
B int
C int8
D int16
E int32
F int64
G uint
H uint8
I uint16
J uint32
K uint64
L rune // alias of int32
M byte // alias of uint8
N string
O []byte
P [16]byte
Q float32
R float64
S complex64
T complex128
/* U
V
W
X
Y
Z*/
}
// Small interface with various types for testing base-behaviour
type interfaceMethodA interface {
MethodA(a, b string, c int) testStruct
}
// Mock implementation of testMethodA
type mockMethodA rune
func (t mockMethodA) MethodA(a string, b string, c int) testStruct {
return testStruct{}
}
func newController() *Controller {
return NewController()
}
func TestRegisterInterface(t *testing.T) {
c := newController()
c.RegisterInterface(struct{ interfaceMethodA }{mockMethodA('A')})
t.Log(c.InterfaceRegistry, c.TypeRegistry)
}
func TestRegisterFunc(t *testing.T) {
c := newController()
f := func(i int) int {
return i + 50
}
c.RegisterFunc("hello", f)
t.Log(c.FuncRegistry, c.TypeRegistry)
result := c.CallFunction("hello", 50)
if result[0].(int) != 100 {
t.Error("Wrongdoing")
}
}
// BenchmarkCallFunction benchmarks a simple function call through
// Controller.CallFunction.
func BenchmarkCallFunction(b *testing.B) {
f := func(i int) int {
return i + 50
}
c := newController()
c.RegisterFunc("bench", f)
for i := 0; i < b.N; i++ {
res := c.CallFunction("bench", 50)
_ = res[0].(int)
}
}
// BenchmarkNormalFunction benchmarks the same simple function call
// as BenchmarkCallFunction but does so without reflection
func BenchmarkNormalFunction(b *testing.B) {
f := func(i int) int {
return i + 50
}
for i := 0; i < b.N; i++ {
_ = f(50)
}
}
|
package api
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/gorilla/mux"
commonClients "github.com/tidepool-org/go-common/clients"
"github.com/tidepool-org/go-common/clients/highwater"
"github.com/tidepool-org/go-common/clients/shoreline"
"github.com/tidepool-org/go-common/clients/status"
"github.com/tidepool-org/go-common/clients/version"
"github.com/tidepool-org/hydrophone/clients"
"github.com/tidepool-org/hydrophone/models"
)
const (
make_store_fail = true
make_store_return_nothing = true
testing_token = "a.fake.token.to.use.in.tests"
testing_token_uid1 = "a.fake.token.for.uid.1"
testing_uid1 = "UID123"
testing_token_uid2 = "a.fake.token.for.uid.2"
testing_uid2 = "UID999"
)
var (
NO_PARAMS = map[string]string{}
FAKE_CONFIG = Config{
ServerSecret: "shhh! don't tell",
I18nTemplatesPath: "../templates",
}
/*
* basics setup
*/
rtr = mux.NewRouter()
mockNotifier = clients.NewMockNotifier()
mockShoreline = shoreline.NewMock(testing_token)
mockGatekeeper = commonClients.NewGatekeeperMock(nil, &status.StatusError{status.NewStatus(500, "Unable to parse response.")})
mockMetrics = highwater.NewMock()
mockSeagull = commonClients.NewSeagullMock()
mockTemplates = models.Templates{}
/*
* stores
*/
mockStore = clients.NewMockStoreClient(false, false)
mockStoreEmpty = clients.NewMockStoreClient(make_store_return_nothing, false)
mockStoreFails = clients.NewMockStoreClient(false, make_store_fail)
/*
* users permissons scenarios
*/
mock_NoPermsGatekeeper = commonClients.NewGatekeeperMock(commonClients.Permissions{"upload": commonClients.Permission{"userid": "other-id"}}, nil)
mock_uid1Shoreline = newtestingShorelingMock(testing_uid1)
responsableGatekeeper = NewResponsableMockGatekeeper()
responsableHydrophone = InitApi(FAKE_CONFIG, mockStore, mockNotifier, mockShoreline, responsableGatekeeper, mockMetrics, mockSeagull, mockTemplates)
)
// In an effort to mock shoreline so that we can return the token we wish
type testingShorelingMock struct{ userid string }
func newtestingShorelingMock(userid string) *testingShorelingMock {
return &testingShorelingMock{userid: userid}
}
func (m *testingShorelingMock) Start() error { return nil }
func (m *testingShorelingMock) Close() { return }
func (m *testingShorelingMock) Login(username, password string) (*shoreline.UserData, string, error) {
return &shoreline.UserData{UserID: m.userid, Emails: []string{m.userid + "@email.org"}, Username: m.userid + "@email.org"}, "", nil
}
func (m *testingShorelingMock) Signup(username, password, email string) (*shoreline.UserData, error) {
return &shoreline.UserData{UserID: m.userid, Emails: []string{m.userid + "@email.org"}, Username: m.userid + "@email.org"}, nil
}
func (m *testingShorelingMock) TokenProvide() string { return testing_token }
func (m *testingShorelingMock) GetUser(userID, token string) (*shoreline.UserData, error) {
return &shoreline.UserData{UserID: m.userid, Emails: []string{m.userid + "@email.org"}, Username: m.userid + "@email.org"}, nil
}
func (m *testingShorelingMock) UpdateUser(userID string, userUpdate shoreline.UserUpdate, token string) error {
return nil
}
func (m *testingShorelingMock) CheckToken(token string) *shoreline.TokenData {
return &shoreline.TokenData{UserID: m.userid, IsServer: false}
}
type (
//common test structure
toTest struct {
desc string
skip bool
returnNone bool
method string
url string
body testJSONObject
token string
respCode int
response testJSONObject
}
// These two types make it easier to define blobs of json inline.
// We don't use the types defined by the API because we want to
// be able to test with partial data structures.
// testJSONObject is a generic json object
testJSONObject map[string]interface{}
// and ja is a generic json array
ja []interface{}
)
func TestGetStatus_StatusOk(t *testing.T) {
version.ReleaseNumber = "1.2.3"
version.FullCommit = "e0c73b95646559e9a3696d41711e918398d557fb"
request, _ := http.NewRequest("GET", "/status", nil)
response := httptest.NewRecorder()
hydrophone := InitApi(FAKE_CONFIG, mockStore, mockNotifier, mockShoreline, mockGatekeeper, mockMetrics, mockSeagull, mockTemplates)
hydrophone.SetHandlers("", rtr)
hydrophone.GetStatus(response, request)
if response.Code != http.StatusOK {
t.Fatalf("Resp given [%d] expected [%d] ", response.Code, http.StatusOK)
}
body, _ := ioutil.ReadAll(response.Body)
if string(body) != `{"status":{"code":200,"reason":"OK"},"version":"1.2.3+e0c73b95646559e9a3696d41711e918398d557fb"}` {
t.Fatalf("Message given [%s] expected [%s] ", string(body), "OK")
}
}
func TestGetStatus_StatusInternalServerError(t *testing.T) {
version.ReleaseNumber = "1.2.3"
version.FullCommit = "e0c73b95646559e9a3696d41711e918398d557fb"
request, _ := http.NewRequest("GET", "/status", nil)
response := httptest.NewRecorder()
hydrophoneFails := InitApi(FAKE_CONFIG, mockStoreFails, mockNotifier, mockShoreline, mockGatekeeper, mockMetrics, mockSeagull, mockTemplates)
hydrophoneFails.SetHandlers("", rtr)
hydrophoneFails.GetStatus(response, request)
if response.Code != http.StatusInternalServerError {
t.Fatalf("Resp given [%d] expected [%d] ", response.Code, http.StatusInternalServerError)
}
body, _ := ioutil.ReadAll(response.Body)
if string(body) != `{"status":{"code":500,"reason":"Session failure"},"version":"1.2.3+e0c73b95646559e9a3696d41711e918398d557fb"}` {
t.Fatalf("Message given [%s] expected [%s] ", string(body), "Session failure")
}
}
func (i *testJSONObject) deepCompare(j *testJSONObject) string {
for k := range *i {
if reflect.DeepEqual((*i)[k], (*j)[k]) == false {
return fmt.Sprintf("`%s` expected `%v` actual `%v` ", k, (*j)[k], (*i)[k])
}
}
return ""
}
////////////////////////////////////////////////////////////////////////////////
func T_ExpectResponsablesEmpty(t *testing.T) {
if responsableGatekeeper.HasResponses() {
if len(responsableGatekeeper.UserInGroupResponses) > 0 {
t.Logf("UserInGroupResponses still available")
}
if len(responsableGatekeeper.UsersInGroupResponses) > 0 {
t.Logf("UsersInGroupResponses still available")
}
if len(responsableGatekeeper.SetPermissionsResponses) > 0 {
t.Logf("SetPermissionsResponses still available")
}
responsableGatekeeper.Reset()
t.Fail()
}
}
func Test_TokenUserHasRequestedPermissions_Server(t *testing.T) {
tokenData := &shoreline.TokenData{UserID: "abcdef1234", IsServer: true}
requestedPermissions := commonClients.Permissions{"a": commonClients.Allowed, "b": commonClients.Allowed}
permissions, err := responsableHydrophone.tokenUserHasRequestedPermissions(tokenData, "1234567890", requestedPermissions)
if err != nil {
t.Fatalf("Unexpected error: %#v", err)
}
if !reflect.DeepEqual(permissions, requestedPermissions) {
t.Fatalf("Unexpected permissions returned: %#v", permissions)
}
}
func Test_TokenUserHasRequestedPermissions_Owner(t *testing.T) {
tokenData := &shoreline.TokenData{UserID: "abcdef1234", IsServer: false}
requestedPermissions := commonClients.Permissions{"a": commonClients.Allowed, "b": commonClients.Allowed}
permissions, err := responsableHydrophone.tokenUserHasRequestedPermissions(tokenData, "abcdef1234", requestedPermissions)
if err != nil {
t.Fatalf("Unexpected error: %#v", err)
}
if !reflect.DeepEqual(permissions, requestedPermissions) {
t.Fatalf("Unexpected permissions returned: %#v", permissions)
}
}
func Test_TokenUserHasRequestedPermissions_GatekeeperError(t *testing.T) {
responsableGatekeeper.UserInGroupResponses = []PermissionsResponse{{commonClients.Permissions{}, errors.New("ERROR")}}
defer T_ExpectResponsablesEmpty(t)
tokenData := &shoreline.TokenData{UserID: "abcdef1234", IsServer: false}
requestedPermissions := commonClients.Permissions{"a": commonClients.Allowed, "b": commonClients.Allowed}
permissions, err := responsableHydrophone.tokenUserHasRequestedPermissions(tokenData, "1234567890", requestedPermissions)
if err == nil {
t.Fatalf("Unexpected success")
}
if err.Error() != "ERROR" {
t.Fatalf("Unexpected error: %#v", err)
}
if len(permissions) != 0 {
t.Fatalf("Unexpected permissions returned: %#v", permissions)
}
}
func Test_TokenUserHasRequestedPermissions_CompleteMismatch(t *testing.T) {
responsableGatekeeper.UserInGroupResponses = []PermissionsResponse{{commonClients.Permissions{"y": commonClients.Allowed, "z": commonClients.Allowed}, nil}}
defer T_ExpectResponsablesEmpty(t)
tokenData := &shoreline.TokenData{UserID: "abcdef1234", IsServer: false}
requestedPermissions := commonClients.Permissions{"a": commonClients.Allowed, "b": commonClients.Allowed}
permissions, err := responsableHydrophone.tokenUserHasRequestedPermissions(tokenData, "1234567890", requestedPermissions)
if err != nil {
t.Fatalf("Unexpected error: %#v", err)
}
if len(permissions) != 0 {
t.Fatalf("Unexpected permissions returned: %#v", permissions)
}
}
func Test_TokenUserHasRequestedPermissions_PartialMismatch(t *testing.T) {
responsableGatekeeper.UserInGroupResponses = []PermissionsResponse{{commonClients.Permissions{"a": commonClients.Allowed, "z": commonClients.Allowed}, nil}}
defer T_ExpectResponsablesEmpty(t)
tokenData := &shoreline.TokenData{UserID: "abcdef1234", IsServer: false}
requestedPermissions := commonClients.Permissions{"a": commonClients.Allowed, "b": commonClients.Allowed}
permissions, err := responsableHydrophone.tokenUserHasRequestedPermissions(tokenData, "1234567890", requestedPermissions)
if err != nil {
t.Fatalf("Unexpected error: %#v", err)
}
if !reflect.DeepEqual(permissions, commonClients.Permissions{"a": commonClients.Allowed}) {
t.Fatalf("Unexpected permissions returned: %#v", permissions)
}
}
func Test_TokenUserHasRequestedPermissions_FullMatch(t *testing.T) {
responsableGatekeeper.UserInGroupResponses = []PermissionsResponse{{commonClients.Permissions{"a": commonClients.Allowed, "b": commonClients.Allowed}, nil}}
defer T_ExpectResponsablesEmpty(t)
tokenData := &shoreline.TokenData{UserID: "abcdef1234", IsServer: false}
requestedPermissions := commonClients.Permissions{"a": commonClients.Allowed, "b": commonClients.Allowed}
permissions, err := responsableHydrophone.tokenUserHasRequestedPermissions(tokenData, "1234567890", requestedPermissions)
if err != nil {
t.Fatalf("Unexpected error: %#v", err)
}
if !reflect.DeepEqual(permissions, requestedPermissions) {
t.Fatalf("Unexpected permissions returned: %#v", permissions)
}
}
|
package frac
import "testing"
func TestFracMul(t *testing.T) {
exp := Frac{10, 21}
frac1 := Frac{2, 3}
frac2 := Frac{5, 7}
act1 := Mul(frac1, frac2)
if exp != act1 {
t.Error("Expected", exp, "got", act1)
}
act2 := Mul(frac2, frac1)
if exp != act2 {
t.Error("Expected", exp, "got", act2)
}
}
|
package common
const (
// Database operation error messages
ErrorMessageNoConnectionProvider = "Connection provider not specified"
ErrorMessageNoTransactionFunction = "Transaction function not specified"
ErrorMessageNotExist = "Not exist"
ErrorMessageAlreadyExist = "Already exist"
ErrorMessageInvalidParameter = "Invalid Parameter"
ErrorMessageInvalidStatus = "Invalid Status"
ErrorMessageInternalError = "Internal error"
ErrorMessageNoPrivileges = "No privileges"
ErrorMessageRefreshTokenExpired = "Refresh token expired"
ErrorMessageTokenExpired = "Token expired"
ErrorMessageNoDeviceInformation = "No deviceinformation"
ErrorMessageLimitExceed = "Limit exceed"
)
|
package main
import (
"github.com/andlabs/ui"
)
// The main window
var window *ui.Window
var box *ui.Box
var area *ui.Area
var mainText *ui.AttributedString
var height = 1024
var width = 1024
type areaHandler struct {
}
func (areaHandler) DragBroken(a *ui.Area) {
}
func (areaHandler) MouseCrossed(a *ui.Area, left bool) {
}
func (areaHandler) MouseEvent(a *ui.Area, me *ui.AreaMouseEvent) {
}
func (areaHandler) KeyEvent(a *ui.Area, ke *ui.AreaKeyEvent) bool {
return false
}
func (areaHandler) Draw(a *ui.Area, dp *ui.AreaDrawParams) {
tl := ui.DrawNewTextLayout(&ui.DrawTextLayoutParams{
String: mainText,
DefaultFont: &ui.FontDescriptor{
Family: ui.TextFamily("Times New Roman"),
Size: ui.TextSize(13),
Stretch: ui.TextStretchNormal,
Weight: ui.TextWeightNormal,
Italic: ui.TextItalicNormal,
},
Width: dp.AreaWidth,
Align: ui.DrawTextAlign(ui.AlignFill),
})
defer tl.Free()
dp.Context.Text(tl, 0, 0)
}
// setupUI setups the UI
func setupUI() {
window = ui.NewWindow("Markdown Viewer", 640, 480, true)
window.SetMargined(true)
window.OnClosing(func(*ui.Window) bool {
window.Destroy()
ui.Quit()
return false
})
ui.OnShouldQuit(func() bool {
window.Destroy()
return true
})
box = ui.NewVerticalBox()
area = ui.NewArea(new(areaHandler))
box.Append(area, true)
mainText = ui.NewAttributedString("")
window.SetChild(box)
appendWithAttributes("\r\n MarkdownViewer", ui.TextSize(50))
area.QueueRedrawAll()
realMain()
window.Show()
}
func appendWithAttributes(str string, attrs ...ui.Attribute) {
start := len(mainText.String())
end := start + len(str)
mainText.AppendUnattributed(str)
for _, v := range attrs {
mainText.SetAttribute(v, start, end)
}
}
func restoreText() {
mainText = ui.NewAttributedString("")
}
|
package service
type Storage interface {
ConvertFileToStruct(namePath string) ([]*Data, error)
} |
package urls
import (
"net/http"
"github.com/go-chi/chi"
)
// Register Get() and Head() methods at once
// Due to issue: https://github.com/go-chi/chi/issues/238#event-1189509880
func GetHead(r chi.Router, pattern string, h http.HandlerFunc) {
r.Get(pattern, h)
r.Head(pattern, h)
}
|
package sandbox
import (
"os"
"testing"
)
func TestIO(t *testing.T) {
r := Run("test/open", os.Stdin, os.Stdout, []string{""}, 1000, 2000)
if r.Status != IOE {
t.Fatal("IO test failed")
}
}
func TestTime(t *testing.T) {
obj := Run("/bin/sleep", os.Stdin, os.Stdout, []string{"5"}, 1000, 20000)
if obj.Status != TLE {
t.Log(status[obj.Status])
t.Log(obj.Time)
t.Fatal("time exceed test failed.")
}
}
func TestCPUTime(t *testing.T) {
obj := Run("test/time", os.Stdin, os.Stdout, []string{""}, 1000, 10000)
if obj.Status != TLE {
t.Log(status[obj.Status])
t.Fatal("time exceed test failed")
}
}
func TestMemory(t *testing.T) {
obj := Run("test/memo", os.Stdin, os.Stdout, []string{""}, 1000, 10000)
if obj.Status != MLE {
t.Log(status[obj.Status])
t.Log(obj.Memory)
t.Fatal("memory exceed test failed")
}
}
|
package main
import (
"go/ast"
"reflect"
gu "github.com/athlum/gorp/utils"
)
func BaseStructTypes() map[string]*ast.StructType {
m := make(map[string]*ast.StructType)
for _, i := range []interface{}{
gu.Base{},
gu.EnableBase{},
} {
m = typeToStructType(reflect.TypeOf(i), m)
}
return m
}
func typeToStructType(ty reflect.Type, m map[string]*ast.StructType) map[string]*ast.StructType {
if ty.Kind() != reflect.Struct {
return m
}
if _, ok := m[ty.Name()]; ok {
return m
}
st := &ast.StructType{
Fields: &ast.FieldList{},
}
for i := 0; i < ty.NumField(); i++ {
f := ty.Field(i)
sf := &ast.Field{
Tag: &ast.BasicLit{},
}
if v, ok := f.Tag.Lookup("db"); ok {
sf.Names = append(sf.Names, &ast.Ident{
Name: f.Name,
})
sf.Tag.Value = "`db:" + `"` + v + `"` + "`"
} else {
sf.Type = &ast.Ident{
Name: f.Name,
}
}
st.Fields.List = append(st.Fields.List, sf)
}
if st.Fields.List != nil {
m[ty.Name()] = st
}
return m
}
|
package chain
import (
"github.com/ethereum/go-ethereum/common"
"github.com/sanguohot/medichain/etc"
"github.com/sanguohot/medichain/util"
"github.com/sanguohot/medichain/contracts/medi"
"math/big"
"time"
"github.com/google/uuid"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
)
func GetUsersDataInstance() (error, *medi.UsersData) {
client, err := GetEthDialClient()
if err != nil {
return err, nil
}
err, address := GetAddressFromCns(etc.ContractUsersData)
if err != nil {
return err, nil
}
instance, err := medi.NewUsersData(*address, client)
if err != nil {
return err, nil
}
return nil, instance
}
func GetUsersDataInstanceAndAuth() (error, *medi.UsersData, *bind.TransactOpts) {
err, instance := GetUsersDataInstance()
if err != nil {
return err, nil, nil
}
auth, err := util.GetDefaultTransactOptsFromStore()
if err != nil {
return err, nil, nil
}
return nil, instance, auth
}
func UsersDataAddSuper(address common.Address) (error, *common.Hash) {
err, instance, auth := GetUsersDataInstanceAndAuth()
if err != nil {
return err, nil
}
tx, err := instance.AddSuper(auth, address)
if err != nil {
return err, nil
}
hash := tx.Hash()
if err := CheckReceiptStatus(hash); err!=nil {
return err, nil
}
return nil, &hash
}
func UsersDataAddUser(uuid [16]byte, orgUuid [16]byte, userAddress common.Address, publicKey [2][32]byte, idCartNoHash common.Hash) (error, *common.Hash) {
err, instance, auth := GetUsersDataInstanceAndAuth()
if err != nil {
return err, nil
}
tx, err := instance.AddUser(auth, uuid, userAddress, orgUuid, publicKey, idCartNoHash, big.NewInt(time.Now().Unix()))
if err != nil {
return err, nil
}
hash := tx.Hash()
if err := CheckReceiptStatus(hash); err!=nil {
return err, nil
}
return nil, &hash
}
func UsersDataDelUser(uuid [16]byte) (error, *common.Hash) {
err, instance, auth := GetUsersDataInstanceAndAuth()
if err != nil {
return err, nil
}
tx, err := instance.DelUser(auth, uuid)
if err != nil {
return err, nil
}
hash := tx.Hash()
if err := CheckReceiptStatus(hash); err!=nil {
return err, nil
}
return nil, &hash
}
func UsersDataIsUuidExist(uuid uuid.UUID) (bool, error) {
err, instance := GetUsersDataInstance()
if err != nil {
return false, err
}
return instance.IsUuidExist(nil, uuid)
}
func UsersDataGetUuidByIdCartNoHash(hash common.Hash) (*uuid.UUID, error) {
err, instance := GetUsersDataInstance()
if err != nil {
return nil, err
}
bytes16, err := instance.GetUuidByIdCartNoHash(nil, hash)
if err != nil {
return nil, err
}
userUuid := uuid.UUID(bytes16)
return &userUuid, nil
}
func UsersDataGetSuperSize() (*big.Int, error) {
err, instance := GetUsersDataInstance()
if err != nil {
return nil, err
}
size, err := instance.GetSuperSize(nil)
if err != nil {
return nil, err
}
return size, nil
}
func UsersDataGetSuperByIndex(index *big.Int) (*common.Address, error) {
err, instance := GetUsersDataInstance()
if err != nil {
return nil, err
}
address, err := instance.GetSuperByIndex(nil, index)
if err != nil {
return nil, err
}
return &address, nil
}
func UsersDataGetOwner() (*common.Address, error) {
err, instance := GetUsersDataInstance()
if err != nil {
return nil, err
}
address, err := instance.GetOwner(nil)
if err != nil {
return nil, err
}
return &address, nil
} |
package event
import (
"errors"
"fmt"
)
type event struct {
eType byte
expectedArgs int
}
var (
follow = event{'F', 2}
unfollow = event{'U', 2}
broadcast = event{'B', 0}
privateMsg = event{'P', 2}
statusUpdate = event{'S', 1}
payloadFormat = "%d|%1s|%d|%d\n"
)
// ErrBadFormat is returned by Parse function when event's payload
// does not conform the expected format (`Seq|Type[|Arg1[|Arg2]]\n`).
var ErrBadFormat = errors.New("events: bad event payload format")
// UnknownTypeError records unknown event type.
type UnknownTypeError struct {
Type byte
}
func (e *UnknownTypeError) Error() string {
return fmt.Sprintf("events: unknown type %q", e.Type)
}
// BadArgumentsNumberError records bad number of received arguments.
type BadArgumentsNumberError struct {
Want int
Got int
}
func (e *BadArgumentsNumberError) Error() string {
return fmt.Sprintf("events: expected %d arguments, got %d", e.Want, e.Got)
}
// Event implements ActionsTrigger and has a sequence number.
type Event struct {
Seq int64
ActionsTrigger
}
type followActionsTrigger struct {
followerID, followedID int
msg []byte
}
func (f followActionsTrigger) Trigger(actions Actions) {
actions.Follow(f.followerID, f.followedID)
actions.SendMsg(f.followedID, f.msg)
}
type unfollowActionsTrigger struct {
followerID, followedID int
}
func (u unfollowActionsTrigger) Trigger(actions Actions) {
actions.Unfollow(u.followerID, u.followedID)
}
type broadcastActionsTrigger struct {
msg []byte
}
func (b broadcastActionsTrigger) Trigger(actions Actions) {
actions.Broadcast(b.msg)
}
type privateMsgActionsTrigger struct {
userID int
msg []byte
}
func (p privateMsgActionsTrigger) Trigger(actions Actions) {
actions.SendMsg(p.userID, p.msg)
}
type statusUpdateActionsTrigger struct {
userID int
msg []byte
}
func (s statusUpdateActionsTrigger) Trigger(actions Actions) {
actions.SendMsgToFollowers(s.userID, s.msg)
}
// Parse parses event's payload
func Parse(payload []byte) (Event, error) {
var (
e Event
eType = []byte{0}
arg1 int
arg2 int
)
n, _ := fmt.Sscanf(string(payload), payloadFormat, &e.Seq, &eType, &arg1, &arg2)
if n < 2 {
return e, ErrBadFormat
}
t := eType[0]
nArgs := n - 2
var trig ActionsTrigger
switch t {
case follow.eType:
if nArgs != follow.expectedArgs {
return e, &BadArgumentsNumberError{Want: follow.expectedArgs, Got: nArgs}
}
trig = followActionsTrigger{
followerID: arg1,
followedID: arg2,
msg: payload,
}
case unfollow.eType:
if nArgs != unfollow.expectedArgs {
return e, &BadArgumentsNumberError{Want: unfollow.expectedArgs, Got: nArgs}
}
trig = unfollowActionsTrigger{
followerID: arg1,
followedID: arg2,
}
case broadcast.eType:
if nArgs != broadcast.expectedArgs {
return e, &BadArgumentsNumberError{Want: broadcast.expectedArgs, Got: nArgs}
}
trig = broadcastActionsTrigger{
msg: payload,
}
case privateMsg.eType:
if nArgs != privateMsg.expectedArgs {
return e, &BadArgumentsNumberError{Want: privateMsg.expectedArgs, Got: nArgs}
}
trig = privateMsgActionsTrigger{
userID: arg2,
msg: payload,
}
case statusUpdate.eType:
if nArgs != statusUpdate.expectedArgs {
return e, &BadArgumentsNumberError{Want: statusUpdate.expectedArgs, Got: nArgs}
}
trig = statusUpdateActionsTrigger{
userID: arg1,
msg: payload,
}
default:
return e, &UnknownTypeError{eType[0]}
}
e.ActionsTrigger = trig
return e, nil
}
|
package core
import (
"github.com/bitwormhole/go-wormhole-core/io/fs"
"github.com/bitwormhole/go-wormhole-git/git/repository/config"
"github.com/bitwormhole/go-wormhole-git/git/repository/head"
"github.com/bitwormhole/go-wormhole-git/git/repository/index"
"github.com/bitwormhole/go-wormhole-git/git/repository/objects"
"github.com/bitwormhole/go-wormhole-git/git/repository/refs"
)
// RepositoryCore 表示一个仓库的对内面貌
type RepositoryCore struct {
Path fs.Path // the core repository directory
createHandlers []ElementCreateHandler
destroyHandlers []ElementDestroyHandler
Objects objects.ObjectStore
Config config.GitConfig
HEAD head.GitHEAD
Index index.GitIndex
Refs refs.GitRefs
}
// Close 方法用于关闭一个 RepositoryCore,以便释放该对象持有的所有资源
func (inst *RepositoryCore) Close() error {
errlist := make([]error, 0)
list := inst.destroyHandlers
for index := range list {
item := list[index]
err := item.OnDestroy()
if err != nil {
errlist = append(errlist, err)
}
}
if len(errlist) > 0 {
return errlist[0]
}
return nil
}
|
package ble
import (
"crypto/rand"
"encoding/json"
"github.com/muka/go-bluetooth/hw"
"log"
"strings"
)
const SEC_APP_UUID_SUFFIX = "-0000-1000-8000-00805F9B34FB"
const APP_UUID = "0001"
const KEY_EXC_SERVICE_UUID = "0001"
const OOB_EXC_SERVICE_UUID = "0002"
const READ_CERT_1_CHAR_UUID = "00000002" // ECDSA
const READ_CERT_2_CHAR_UUID = "00000003" // ECDSA
const READ_CERT_3_CHAR_UUID = "00000004" // ECDSA
const WRITE_CERT_CHAR_UUID = "00000005" // ECDSA
const ECDH_EXC_CHAR_UUID = "00000010" // ECDH
const OOB_EXC_CHAR_UUID = "00000020" // OOB token exchange
const CHALLENGE_CHAR_UUID = "00000030" // ChallengeResponse
type ECDHExchange struct {
Signature []byte `json:"s"`
PubKey []byte `json:"p"`
Random [32]byte `json:"r"` // challenge
}
/**
Challenge the other party to sign the random value that is send in the ECDHExchange message
This mitigates a scenario where the adversary has access to the ECDH private key and has sniffed the ECDHExchange
message that contains the signature of the ECDH key (signed using ECDSA). Without this mitigation, the adversary could establish a session by
by replaying the ECDHExchange message that contains the signature of the public ECDH key, whose private key the has adversary stolen.
This attack would bypass the TPM (ECDSA).
*/
type ChallengeResponse struct {
Signature []byte `json:"s"`
}
// Allow specifying MAC in case pairing is done for another adapter
type OOBExchange struct {
Data [32]byte `json:"data"` // OOB data (hash, randomizer)
Address string `json:"addr"` // MAC address of the device this oob data should be added to
}
func MarshalECDHExchange(exchange ECDHExchange) ([]byte, error) {
return json.Marshal(exchange)
}
func UnmarshalECDHExchange(data []byte) (*ECDHExchange, error) {
var exchange ECDHExchange
err := json.Unmarshal(data, &exchange)
if err != nil {
return nil, err
}
return &exchange, nil
}
func MarshalOOBExchange(exchange OOBExchange) ([]byte, error) {
return json.Marshal(exchange)
}
func UnmarshalOOBExchange(data []byte) (*OOBExchange, error) {
var exchange OOBExchange
err := json.Unmarshal(data, &exchange)
if err != nil {
return nil, err
}
return &exchange, nil
}
func MarshalChallengeResponse(response ChallengeResponse) ([]byte, error) {
return json.Marshal(response)
}
func UnmarshalChallengeResponse(data []byte) (*ChallengeResponse, error) {
var response ChallengeResponse
err := json.Unmarshal(data, &response)
if err != nil {
return nil, err
}
return &response, nil
}
func EnableLESingleMode(adapterID string) {
btmgmtCli := hw.NewBtMgmt(adapterID)
btmgmtCli.SetPowered(false)
btmgmtCli.SetLe(true)
btmgmtCli.SetBredr(false)
btmgmtCli.SetPowered(true)
}
func SecRand32Bytes() (out [32]byte) {
bytes := make([]byte, 32)
n, err := rand.Read(bytes)
if n != 32 || err != nil {
log.Fatalf("Could not generate secure random bytes. Count :%d, err: %v\n", n, err)
}
copy(out[:], bytes)
return
}
// Extract characteristic UUID from full UUID (e.g., 00002A38-0000-1000-8000-00805F9B34FB)
// and pad to full length (8 characters)
// Returns empty string if invalid uuid
func GetCharUUIDFromUUID(uuid string) string {
parts := strings.Split(uuid, "-")
if len(parts) == 0 {
return ""
}
padLen := 8 - len(parts[0])
return strings.ToUpper(strings.Repeat("0", padLen) + parts[0])
} |
package e2e
import (
"context"
"fmt"
"os/exec"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorclient"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// This module contains helper functions for copying images and creating image registries
// Use for tests that require manipulating images or use of custom container registries
const (
registryImage = "registry:2.7.1"
registryName = "registry"
localFQDN = "localhost:5000"
)
func createDockerRegistry(client operatorclient.ClientInterface, namespace string) (string, error) {
registry := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: registryName,
Namespace: namespace,
Labels: map[string]string{"name": registryName},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: registryName,
Image: registryImage,
Ports: []corev1.ContainerPort{
{
HostPort: int32(5000),
ContainerPort: int32(5000),
},
},
},
},
},
}
svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: registryName,
Namespace: namespace,
},
Spec: corev1.ServiceSpec{
Selector: map[string]string{"name": registryName},
Ports: []corev1.ServicePort{
{
Port: int32(5000),
},
},
},
}
_, err := client.KubernetesInterface().CoreV1().Pods(namespace).Create(context.TODO(), registry, metav1.CreateOptions{})
if err != nil {
return "", fmt.Errorf("creating test registry: %s", err)
}
_, err = client.KubernetesInterface().CoreV1().Services(namespace).Create(context.TODO(), svc, metav1.CreateOptions{})
if err != nil {
return "", fmt.Errorf("creating test registry: %s", err)
}
return localFQDN, nil
}
func deleteDockerRegistry(client operatorclient.ClientInterface, namespace string) {
_ = client.KubernetesInterface().CoreV1().Pods(namespace).Delete(context.TODO(), registryName, metav1.DeleteOptions{})
_ = client.KubernetesInterface().CoreV1().Services(namespace).Delete(context.TODO(), registryName, metav1.DeleteOptions{})
}
// port-forward registry pod port 5000 for local test
// port-forwarding ends when registry pod is deleted: no need for explicit port-forward stop
func registryPortForward(namespace string) error {
cmd := exec.Command("kubectl", "-n", namespace, "port-forward", "registry", "5000:5000")
err := cmd.Start()
if err != nil {
return fmt.Errorf("failed to exec %#v: %v", cmd.Args, err)
}
return nil
}
|
package handler
import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/vanWezel/to-do/internal/model"
)
func (h *Handler) TaskIndex(c echo.Context) error {
page := getPageQueryParam(c.QueryParam("page"))
list, err := h.Task.Index(page)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, model.Response{
Message: "Successfully loaded",
Status: true,
Data: list,
})
}
|
package handler
import (
std "CRUD"
"os"
"io/ioutil"
"net/http"
)
func NewOrgHandler() *OrgHandler {
return &OrgHandler{Repo: std.NewStudents()}
}
// OrgHandler ..
type OrgHandler struct {
Repo *std.Repo
}
func setupResponse(w *http.ResponseWriter, req *http.Request) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
func (p *OrgHandler) GetClientInfo(w http.ResponseWriter, r *http.Request) {
setupResponse(&w, r)
if r.Method != "GET" {
http.Error(w, http.StatusText(405), 405)
return
}
url := os.Getenv("URL")
apikey := os.Getenv("API_KEY")
uri := r.URL.Query().Get("uri")
newurl := url + uri[1:len(uri)-1] + "?access_token=" + apikey
println(newurl)
println(newurl)
rr, err := http.Get(newurl)
if err != nil {
s := "<error>Server not found</error>"
RespondWithJSON(w, http.StatusNotFound, []byte(s))
}
response, _ := ioutil.ReadAll(rr.Body)
res := string(response)
println(res)
RespondWithJSON(w, http.StatusOK, []byte(res))
}
|
package main
import(
"fmt"
"reflect"
)
type rectangle struct {
length float64
breadth float64
color string
}
func main() {
var rect1 = rectangle{
10,
20,
"red",
}
fmt.Println(reflect.TypeOf(rect1)) // main.rectangle
fmt.Println(reflect.ValueOf(rect1)) // {{{10 20 red}
rect2 := rectangle{
length: 10.1,
breadth: 20.1,
color: "blue",
}
fmt.Println(reflect.TypeOf(rect2))
fmt.Println(reflect.ValueOf(rect2).Kind()) // .Kind() with type bunch of value
rect3 := new(rectangle)
fmt.Printf("%T\n",rect3) // *main.rectangle
fmt.Println(reflect.TypeOf(rect3)) // *main.rectangle
fmt.Println(reflect.ValueOf(rect3).Kind()) // pointer
fmt.Println(reflect.ValueOf(&rectangle{}).Kind()) // same kind as -> top of
}
|
package components
// A Cell is something that can be alive or dead.
// The contains some logic that lets it know if it
// should be alive or dead Next.
type Cell struct {
alive bool
}
// Calling `Cell` will create a new struct, we then return
// a pointer to that struct, rather than a copy (which would
// happen if we just returned `Cell`)
func NewCell(alive bool) *Cell {
return &Cell{alive}
}
// a live cell with 3 neighbors lives in the next step
// a dead cell with 3 neighbors lives in the next step
// a live cell with 2 or 3 neighbors lives in the next step
func (c *Cell) Next(count int) *Cell {
return &Cell{count == 3 || (c.alive && count == 2)}
}
// returns the integer value of the Cell state
func (c *Cell) Value() int {
if c.alive {
return 1
}
return 0
}
// returns the state of the Cell
func (c *Cell) IsAlive() bool {
return c.alive
}
|
package main
import (
"fmt"
"strings"
)
type parser struct {
lexer *lexer
matched token
next token
}
// ParseError is returned if the input cannot be successfuly parsed
type ParseError struct {
// The original query
Input string
// The position where the parsing fails
Pos int
// The error message
Message string
}
func (e ParseError) Error() string {
return fmt.Sprintf("Parse error: %s\n%s\n%s^", e.Message, e.Input, strings.Repeat(" ", e.Pos))
}
/*
Parse accepts an input string and the list and types of valid fields and returns either a matcher expression if the query
is valid, or else an error
*/
func Parse(input string) ([]Generator, error) {
lexer := newLexer(input)
return (&parser{
lexer: lexer,
next: lexer.next(),
}).parse()
}
func (p *parser) parse() (gen []Generator, err error) {
defer func() {
if r := recover(); r != nil {
gen = nil
err = ParseError{
Input: p.lexer.input,
Pos: p.matched.pos,
Message: fmt.Sprintf("%v", r),
}
}
}()
gen = p.start()
if !p.found(tkEOF) {
p.advance()
panic("Unexpected input")
}
return
}
func (p *parser) start() []Generator {
if p.peek(tkObjStart) || p.peek(tkArrStart) {
res := []Generator{}
for {
switch {
case p.found(tkObjStart):
res = append(res, p.obj())
case p.found(tkArrStart):
res = append(res, p.arr())
default:
return res
}
}
}
objGen := NewObj()
for p.found(tkLiteral) {
field := p.matched.value
value := p.field(field)
objGen.Add(field, value)
}
return []Generator{objGen}
}
func (p *parser) obj() Generator {
res := NewObj()
for p.found(tkLiteral) {
field := p.matched.value
value := p.field(field)
res.Add(field, value)
}
p.expect(tkObjEnd)
return res
}
func (p *parser) arr() Generator {
res := Arr{}
for {
switch {
case p.found(tkRawLiteral):
rawValue, err := parseRawValue(p.matched.value)
if err != nil {
panic("Invalid literal")
}
res.Add(Value{value: rawValue})
case p.found(tkLiteral):
if p.peek(tkAssign) || p.peek(tkDot) {
field := p.matched.value
value := p.field(field)
// Add 1-field obj to array
obj := NewObj()
obj.Add(field, value)
res.Add(obj)
} else {
res.Add(Value{value: p.matched.value})
}
case p.found(tkObjStart):
res.Add(p.obj())
//Add obj as array elem
case p.found(tkArrStart):
res.Add(p.arr())
// Add array as arr elem
case p.found(tkArrEnd):
// return, the array is complete
return res
case p.found(tkEOF):
panic("Unclosed array")
default:
p.advance()
panic("Unexpected input")
}
}
return nil
}
func (p *parser) field(field string) Generator {
switch {
case p.found(tkAssign):
return p.value()
case p.found(tkDot):
p.expect(tkLiteral)
field := p.matched.value
value := p.field(field)
return NewObj().Add(field, value)
case p.found(tkEOF):
panic("Unexpected end of input")
default:
p.advance()
panic("Unexpected input")
}
}
func (p *parser) value() Generator {
switch {
case p.found(tkLiteral):
return Value{value: p.matched.value}
case p.found(tkRawLiteral):
rawValue, err := parseRawValue(p.matched.value)
if err != nil {
panic("Invalid literal")
}
return Value{value: rawValue}
case p.found(tkObjStart):
return p.obj()
case p.found(tkArrStart):
return p.arr()
case p.found(tkEOF):
panic("Unexpected end of input")
default:
p.advance()
panic("Unexpected input")
}
}
func (p *parser) expect(class tokenClass) {
if !p.found(class) {
p.advance()
panic(fmt.Sprintf("was expecting %v", class))
}
}
func (p *parser) peek(class tokenClass) bool {
return p.next.class == class
}
func (p *parser) found(class tokenClass) bool {
if p.next.class == class {
p.matched = p.next
p.next = p.lexer.next()
return true
}
return false
}
func (p *parser) advance() {
p.matched = p.next
p.next = p.lexer.next()
}
|
package requests
import (
"encoding/json"
"testing"
"github.com/mitchellh/mapstructure"
"github.com/stretchr/testify/assert"
)
func TestDecodeAccountInfoRequest(t *testing.T) {
encoded := `{"action":"account_info","account":"abc","representative":true}`
var decoded AccountInfoRequest
json.Unmarshal([]byte(encoded), &decoded)
assert.Equal(t, "account_info", decoded.Action)
assert.Equal(t, "abc", decoded.Account)
assert.True(t, *decoded.Representative)
assert.Nil(t, decoded.Pending)
}
func TestMapStructureDecodeAccountInfoRequest(t *testing.T) {
request := map[string]interface{}{
"action": "account_info",
"account": "abc",
"representative": true,
}
var decoded AccountInfoRequest
mapstructure.Decode(request, &decoded)
assert.Equal(t, "account_info", decoded.Action)
assert.Equal(t, "abc", decoded.Account)
assert.True(t, *decoded.Representative)
assert.Nil(t, decoded.Pending)
}
// Test encoding
func TestEncodeAccountInfoRequest(t *testing.T) {
encoded := `{"action":"account_info","account":"abc","representative":true}`
rep := true
req := AccountInfoRequest{
AccountRequest: AccountRequest{
BaseRequest: BaseRequest{Action: "account_info"},
Account: "abc",
},
Representative: &rep,
}
encodedActual, _ := json.Marshal(&req)
assert.Equal(t, encoded, string(encodedActual))
}
|
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for aValue := len(a); aValue > 0; aValue-- {
a = RemoveBack(a)
fmt.Println(a)
}
}
func RemoveBack(a []int) []int {
sliceLen := len(a)
b := make([]int, sliceLen)
b = a[:sliceLen-1]
return b
}
|
/*
* @lc app=leetcode.cn id=1748 lang=golang
*
* [1748] 唯一元素的和
*/
// @lc code=start
package main
func sumOfUnique(nums []int) int {
ret := 0
numCount := make(map[int]int)
for i := 0; i < len(nums); i++ {
numCount[nums[i]]++
}
for k, v := range numCount {
if v == 1 {
ret += k
}
}
return ret
}
// @lc code=end
|
package client
import (
"bufio"
"context"
"fmt"
"io"
"net"
"os"
"time"
)
// TelnetClient instance of tcp-client as telnet
type TelnetClient struct {
conn net.Conn
stdinScanner *bufio.Scanner
serverScanner *bufio.Scanner
serverCh chan string
stdinCh chan string
}
// NewTelnetClient getting instance of telnet
func NewTelnetClient(addr string, timeOut time.Duration, reader io.Reader) (*TelnetClient, error) {
dialer := &net.Dialer{}
ctx, cancel := context.WithTimeout(context.Background(), timeOut)
defer cancel()
conn, err := dialer.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, err
}
return &TelnetClient{
conn: conn,
stdinScanner: bufio.NewScanner(reader),
serverScanner: bufio.NewScanner(conn),
serverCh: make(chan string, 1),
stdinCh: make(chan string, 1),
}, nil
}
// scanStdin scans IOF of io.Reader of STDIN
func (t *TelnetClient) scanStdin() {
for {
if !t.stdinScanner.Scan() {
t.stdinCh <- "Bye!\n"
return
}
msg := t.stdinScanner.Text()
if _, err := t.conn.Write([]byte(fmt.Sprintf("%s\n", msg))); err != nil {
t.stdinCh <- fmt.Sprintf("server error: %s\n", err.Error())
return
}
}
}
// scanStdin scans IOF of io.Reader of tcp-server
func (t *TelnetClient) scanTCPServer() {
for {
if !t.serverScanner.Scan() {
t.serverCh <- "Server close connection!\nBye!\n"
return
}
if _, err := os.Stdout.WriteString(t.serverScanner.Text() + "\n"); err != nil {
t.serverCh <- err.Error()
}
}
}
// Run launches telnet client
func (t *TelnetClient) Run() error {
defer t.conn.Close()
defer os.Stdin.Close()
defer os.Stdout.Close()
go t.scanStdin()
go t.scanTCPServer()
for {
select {
case msg := <-t.serverCh:
_, err := os.Stdout.WriteString(msg)
return err
case msg := <-t.stdinCh:
_, err := os.Stdout.WriteString(msg)
return err
default:
time.Sleep(10 * time.Millisecond)
}
}
}
|
// Usage: $0 srcdir dstdir
package main
import (
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
// "github.com/maemual/shutil"
"github.com/gosexy/exif"
shutil "github.com/termie/go-shutil"
)
func bincompare(i1, i2 io.Reader, bufsz int) int {
b1 := make([]byte, bufsz)
b2 := make([]byte, bufsz)
for {
n1, e1 := io.ReadAtLeast(i1, b1, bufsz)
n2, e2 := io.ReadAtLeast(i2, b2, bufsz)
clen := n1
if clen > n2 {
clen = n2
}
r := bytes.Compare(b1, b2)
if r != 0 {
return r
}
if n1 < n2 {
return -1
} else if n1 > n2 {
return 1
}
if e1 != nil && e2 != nil {
return 0
}
if e1 != nil {
return -1
}
if e2 != nil {
return 1
}
}
}
func nextfn(src string) string {
dirn, base := path.Split(src)
ext := path.Ext(src)
log.Println("nextfn: dirn=", dirn, ", base=", base, ", ext=", ext)
base = strings.TrimSuffix(base, ext)
log.Println("nextfn: trim=", base)
nn := strings.Split(base, "_")
log.Println("nextfn: nn=", nn)
r := 1
if len(nn) >= 2 && nn[len(nn)-1] != "" {
var err error
if r, err = strconv.Atoi(nn[1]); err == nil {
r += 1
}
}
log.Println("nextfn: nn2=", nn, ", r=", r, "ext=", ext)
return path.Join(dirn, fmt.Sprintf("%s_%d%s", nn[0], r, ext))
}
func stampfn(src string) (dst string, ts time.Time, err error) {
fi, err := os.Stat(src)
if err != nil {
return
}
ts = fi.ModTime()
dst = ts.Format("2006/01/02/150405") + path.Ext(src)
return
}
func getstamp(tbl map[string]string) (out string, ok bool) {
tags := []string{"Date and Time", "Date and Time (Digitized)", "Date and Time (Original)"}
for _, k := range tags {
if out, ok := tbl[k]; ok {
return out + " " + "+0900", true
}
}
if out, ok := tbl["GPS Date"]; ok {
if out2, ok2 := tbl["GPS Time (Atomic Clock)"]; ok2 {
return out + " " + out2 + " " + "+0000", true
}
}
return "", false
}
func exiffn(src string) (dst string, ts time.Time, err error) {
reader := exif.New()
if err = reader.Open(src); err != nil {
log.Println("exif open", err)
return exiffn_cmd(src)
}
getstamp(reader.Tags)
loc, _ := time.LoadLocation("Asia/Tokyo")
if stamp, ok := getstamp(reader.Tags); ok {
if ts, err = time.Parse("2006:01:02 15:04:05 -0700", stamp); err == nil {
dst = ts.In(loc).Format("2006/01/02/150405") + path.Ext(src)
} else {
log.Println("time parse", err)
return exiffn_cmd(src)
}
return
}
return
}
func exiffn_cmd(src string) (dst string, ts time.Time, err error) {
loc := time.Local
if path.Ext(src) == ".mp4" {
loc = time.UTC
}
var out []byte
out, err = exec.Command("exiftool", src).Output()
if err != nil {
log.Println("exec cmd", err)
return stampfn(src)
}
ids := []string{"Create Date", "Modify Date", "Track Create Date", "Track Modify Date", "Date/Time Original"}
for _, v := range strings.Split(string(out), "\n") {
for _, k := range ids {
if strings.HasPrefix(v, k) {
l := strings.SplitN(v, ":", 2)
if len(l) != 2 {
continue
}
if ts, err = time.ParseInLocation("2006:01:02 15:04:05", strings.TrimSpace(l[1]), loc); err == nil {
dst = ts.Local().Format("2006/01/02/150405") + path.Ext(src)
return
}
}
}
}
log.Println("no match line")
return stampfn(src)
}
func exifcopy(src, dstbase string) error {
dstpath, ts, err := exiffn(src)
log.Println("dstpath", dstpath, "ts", ts, "err", err)
var dstfull string
for {
dstfull = path.Join(dstbase, dstpath)
if _, err := os.Stat(dstfull); os.IsNotExist(err) {
// copy
break
}
f1, err := os.Open(src)
if err != nil {
return err
}
defer f1.Close()
f2, err := os.Open(dstfull)
if err != nil {
return err
}
defer f2.Close()
if bincompare(f1, f2, 8192) == 0 {
// pass
log.Println("same content", src, dstfull)
return nil
}
// try next filename
log.Println("try next", src, dstfull)
dstpath = nextfn(dstpath)
}
// copy file
log.Println("to mkdir", dstfull)
err = os.MkdirAll(path.Dir(dstfull), os.ModePerm)
if err != nil {
log.Println("mkdir", err)
}
_, err = shutil.Copy(src, dstfull, false)
if err != nil {
log.Println("copy2", err)
}
err = os.Chtimes(dstfull, ts, ts)
if err != nil {
log.Println("chtimes", err)
}
return err
}
func main() {
src := os.Args[1]
dst := os.Args[2]
filepath.Walk(src, func(p string, info os.FileInfo, err error) error {
if path.Ext(p) == ".thumbnails" {
return filepath.SkipDir
}
if info.IsDir() {
return nil
}
if path.Ext(p) == ".DS_Store" {
return nil
}
exifcopy(p, dst)
return nil
})
}
|
package container_runtime
import (
"context"
"fmt"
"os"
"strings"
"github.com/werf/lockgate"
"github.com/werf/werf/pkg/werf"
"github.com/werf/logboek"
"github.com/werf/werf/pkg/docker"
"github.com/werf/werf/pkg/image"
)
type LegacyStageImage struct {
*legacyBaseImage
fromImage *LegacyStageImage
container *LegacyStageImageContainer
buildImage *legacyBaseImage
dockerfileImageBuilder *DockerfileImageBuilder
}
func NewLegacyStageImage(fromImage *LegacyStageImage, name string, containerRuntime ContainerRuntime) *LegacyStageImage {
stage := &LegacyStageImage{}
stage.legacyBaseImage = newLegacyBaseImage(name, containerRuntime)
stage.fromImage = fromImage
stage.container = newLegacyStageImageContainer(stage)
return stage
}
func (i *LegacyStageImage) BuilderContainer() LegacyBuilderContainer {
return &LegacyStageImageBuilderContainer{i}
}
func (i *LegacyStageImage) Container() LegacyContainer {
return i.container
}
func (i *LegacyStageImage) GetID() string {
if i.buildImage != nil {
return i.buildImage.Name()
} else {
return i.legacyBaseImage.GetStageDescription().Info.ID
}
}
func (i *LegacyStageImage) Build(ctx context.Context, options LegacyBuildOptions) error {
if i.dockerfileImageBuilder != nil {
if err := i.dockerfileImageBuilder.Build(ctx); err != nil {
return err
}
} else {
containerLockName := ContainerLockName(i.container.Name())
if _, lock, err := werf.AcquireHostLock(ctx, containerLockName, lockgate.AcquireOptions{}); err != nil {
return fmt.Errorf("failed to lock %s: %s", containerLockName, err)
} else {
defer werf.ReleaseHostLock(lock)
}
if debugDockerRunCommand() {
runArgs, err := i.container.prepareRunArgs(ctx)
if err != nil {
return err
}
fmt.Printf("Docker run command:\ndocker run %s\n", strings.Join(runArgs, " "))
if len(i.container.prepareAllRunCommands()) != 0 {
fmt.Printf("Decoded command:\n%s\n", strings.Join(i.container.prepareAllRunCommands(), " && "))
}
}
if containerRunErr := i.container.run(ctx); containerRunErr != nil {
if strings.HasPrefix(containerRunErr.Error(), "container run failed") {
if options.IntrospectBeforeError {
logboek.Context(ctx).Default().LogFDetails("Launched command: %s\n", strings.Join(i.container.prepareAllRunCommands(), " && "))
if err := logboek.Context(ctx).Streams().DoErrorWithoutProxyStreamDataFormatting(func() error {
return i.introspectBefore(ctx)
}); err != nil {
return fmt.Errorf("introspect error failed: %s", err)
}
} else if options.IntrospectAfterError {
if err := i.Commit(ctx); err != nil {
return fmt.Errorf("introspect error failed: %s", err)
}
logboek.Context(ctx).Default().LogFDetails("Launched command: %s\n", strings.Join(i.container.prepareAllRunCommands(), " && "))
if err := logboek.Context(ctx).Streams().DoErrorWithoutProxyStreamDataFormatting(func() error {
return i.Introspect(ctx)
}); err != nil {
return fmt.Errorf("introspect error failed: %s", err)
}
}
if err := i.container.rm(ctx); err != nil {
return fmt.Errorf("introspect error failed: %s", err)
}
}
return containerRunErr
}
if err := i.Commit(ctx); err != nil {
return err
}
if err := i.container.rm(ctx); err != nil {
return err
}
}
if info, err := i.ContainerRuntime.GetImageInfo(ctx, i.MustGetBuiltId(), GetImageInfoOpts{}); err != nil {
return err
} else {
i.SetInfo(info)
i.SetStageDescription(&image.StageDescription{
StageID: nil, // stage id does not available at the moment
Info: info,
})
}
return nil
}
func (i *LegacyStageImage) Commit(ctx context.Context) error {
builtId, err := i.container.commit(ctx)
if err != nil {
return err
}
i.buildImage = newLegacyBaseImage(builtId, i.ContainerRuntime)
return nil
}
func (i *LegacyStageImage) Introspect(ctx context.Context) error {
if err := i.container.introspect(ctx); err != nil {
return err
}
return nil
}
func (i *LegacyStageImage) introspectBefore(ctx context.Context) error {
if err := i.container.introspectBefore(ctx); err != nil {
return err
}
return nil
}
func (i *LegacyStageImage) MustResetInfo(ctx context.Context) error {
if i.buildImage != nil {
return i.buildImage.MustResetInfo(ctx)
} else {
return i.legacyBaseImage.MustResetInfo(ctx)
}
}
func (i *LegacyStageImage) GetInfo() *image.Info {
if i.buildImage != nil {
return i.buildImage.GetInfo()
} else {
return i.legacyBaseImage.GetInfo()
}
}
func (i *LegacyStageImage) MustGetBuiltId() string {
builtId := i.GetBuiltId()
if builtId == "" {
panic(fmt.Sprintf("image %s built id is not available", i.Name()))
}
return builtId
}
func (i *LegacyStageImage) GetBuiltId() string {
if i.dockerfileImageBuilder != nil {
return i.dockerfileImageBuilder.GetBuiltId()
} else if i.buildImage != nil {
return i.buildImage.Name()
} else {
return ""
}
}
func (i *LegacyStageImage) TagBuiltImage(ctx context.Context) error {
_ = i.ContainerRuntime.(*DockerServerRuntime)
return docker.CliTag(ctx, i.MustGetBuiltId(), i.name)
}
func (i *LegacyStageImage) Tag(ctx context.Context, name string) error {
_ = i.ContainerRuntime.(*DockerServerRuntime)
return docker.CliTag(ctx, i.GetID(), name)
}
func (i *LegacyStageImage) Pull(ctx context.Context) error {
_ = i.ContainerRuntime.(*DockerServerRuntime)
if err := docker.CliPullWithRetries(ctx, i.name); err != nil {
return err
}
i.legacyBaseImage.UnsetInfo()
return nil
}
func (i *LegacyStageImage) Push(ctx context.Context) error {
_ = i.ContainerRuntime.(*DockerServerRuntime)
return docker.CliPushWithRetries(ctx, i.name)
}
func (i *LegacyStageImage) DockerfileImageBuilder() *DockerfileImageBuilder {
if i.dockerfileImageBuilder == nil {
i.dockerfileImageBuilder = NewDockerfileImageBuilder(i.ContainerRuntime) // TODO: Possibly need to change DockerServerRuntime to abstract ContainerRuntime
}
return i.dockerfileImageBuilder
}
func debugDockerRunCommand() bool {
return os.Getenv("WERF_DEBUG_DOCKER_RUN_COMMAND") == "1"
}
|
// Package name
package main
// imported modules
import (
"fmt"
"os"
)
// const value
const pi = 3.14
// Simple calculator functions
func add(x int, y int) int{
return x + y
}
func diff(x int, y int) int{
return x - y
}
func multiplication(x int, y int) int{
return x * y
}
func division(x int, y int) int{
return x / y
}
// Attribution example
func attributionExample(){
var num1 int // standard attribution with default value 0
var num2 = 10 // standard attribution
var num3, bool1, string1 = 10, true, "some string" // multiple attribution
i := 100 // short attribution
fmt.Println("Attributions:")
fmt.Println(num1) // 0
fmt.Println(num2) // 10
fmt.Println(num3) // 10
fmt.Println(bool1) // true
fmt.Println(string1) // some string
fmt.Println(i) // 100
}
// Simple if - else example
func ifElse(first int){
fmt.Println("If - Else example:")
if first > 0{
fmt.Println("number is highter than 0")
} else if first == 0 {
fmt.Println("number is equal to 0")
} else {
fmt.Println("number is lower than 0")
}
}
// Simple loop example
func loopExample(items int){
fmt.Println("Simple loop example:")
for i := 0; i < items; i++ {
fmt.Println(i)
}
}
// Print command line args(using loop): to run main.go arg1 arg2 arg3
func printFileArgs(){
var s, sep string
for i := 1; i < len(os.Args); i++{
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
}
// main function
func main(){
fmt.Println("Hi, this is your first lesson")
fmt.Println("Calculator example(8 and 4):")
fmt.Println(add(8, 4))
fmt.Println(diff(8, 4))
fmt.Println(multiplication(8, 4))
fmt.Println(division(8, 4))
attributionExample()
ifElse(0)
loopExample(7)
printFileArgs()
}
// Excercise
// Create an application that converts celsius degrees into fahrenheit and kelvin
// Example input: go run main.go 100 12 40 123 30
// Output should be displayed on console
//
//
//
//
//
|
package sim
import (
"time"
)
type Asset interface {
Account
Value() float64
Loan() Debt
Depreciate(date time.Time)
Maintain(amount float64, date time.Time)
CommissionRate() float64
PayOff(date time.Time) *Transaction
Liquidate(date time.Time) *Transaction
}
|
package blocker
// UnknownBlocker 未知Blocker
type UnknownBlocker struct {
}
// NewUnknownBlocker 创建未知Blocker
func NewUnknownBlocker() *UnknownBlocker {
b := &UnknownBlocker{}
return b
}
// IsMacBlocked zone或者mac是否被限制
func (f *UnknownBlocker) IsMacBlocked(mac, zone string) bool {
return true
}
// IgnoreIPCheck 是否忽略对mac对应客户端进行ip过滤
func (f *UnknownBlocker) IgnoreIPCheck(ip string) bool {
return false
}
// IsIPBlocked ip是否被限制
func (f *UnknownBlocker) IsIPBlocked(ip string) bool {
return true
}
|
package main
import (
"fmt"
"strconv"
)
func ExampleDB_UsersTags() {
db := OpenDBInMemory()
MigrateDB(db)
alice := User{Name: "Alice"}
bob := User{Name: "Bob"}
carol := User{Name: "Carol"}
david := User{Name: "David"}
db.Create(&alice)
db.Create(&bob)
db.Create(&carol)
db.Create(&david)
frontend := Tag{Name: "Frontend", Users: []User{alice, bob}}
backend := Tag{Name: "Backend", Users: []User{carol, david}}
teamLead := Tag{Name: "Team Lead", Users: []User{alice, david}}
db.Create(&frontend)
db.Create(&backend)
db.Create(&teamLead)
fmt.Println("Users:")
fmt.Println(alice.Name)
fmt.Println(bob.Name)
fmt.Println(carol.Name)
fmt.Println(david.Name)
fmt.Println("Tags:")
fmt.Println(frontend.Name)
fmt.Println(backend.Name)
fmt.Println(teamLead.Name)
var tags []Tag
db.Model(&alice).Association("Tags").Find(&tags)
fmt.Print("Before: ")
for i, tag := range tags {
if i < len(tags)-1 {
fmt.Print(tag.Name + " ")
} else {
fmt.Print(tag.Name)
}
}
fmt.Println()
alice.Tags = nil
db.Save(&alice)
db.Model(&alice).Association("Tags").Find(&tags)
fmt.Print("After: ")
for i, tag := range tags {
if i < len(tags)-1 {
fmt.Print(tag.Name + " ")
} else {
fmt.Print(tag.Name)
}
}
fmt.Println()
if err := db.Close(); err != nil {
fmt.Println(err)
}
// Output:
// Users:
// Alice
// Bob
// Carol
// David
// Tags:
// Frontend
// Backend
// Team Lead
// Before: Frontend Team Lead
// After: Frontend Team Lead
}
func ExampleDB_BagelLogs() {
db := OpenDBInMemory()
MigrateDB(db)
log := BagelLog{Date: 123456}
db.Create(&log)
for i := 0; i < 5; i++ {
db.Create(&Bagel{
SlackConversationID: strconv.Itoa(1000 + i),
BagelLogID: log.ID,
})
}
var bagels []Bagel
db.Model(&log).Related(&bagels)
for _, bagel := range bagels {
fmt.Println(bagel.SlackConversationID, bagel.BagelLogID)
}
if err := db.Close(); err != nil {
fmt.Println(err)
}
// Output:
// 1000 1
// 1001 1
// 1002 1
// 1003 1
// 1004 1
}
|
package main
import (
"os"
"github.com/therecipe/qt/widgets"
)
func main() {
widgets.NewQApplication(len(os.Args), os.Args)
button := widgets.NewQPushButton2("check for updates", nil)
button.ConnectClicked(func(bool) { sparkle_checkUpdates() })
button.Show()
widgets.QApplication_Exec()
}
|
package main
import (
"fmt"
"io"
"unicode"
)
type jpNameTerms struct {
kanji []string
hiragana []string
katakana []string
}
func (x *jpNameTerms) dump(w io.Writer) error {
raw := "package piidata\n\n"
raw += "// JpNameKanji is Kanji name data in Japanese\n"
raw += "var JpNameKanji = []string{\n"
for _, term := range x.kanji {
raw += fmt.Sprintf("\t\"%s\",\n", term)
}
raw += "}\n\n"
raw += "// JpNameHiragana is Hiragana name data in Japanese\n"
raw += "var JpNameHiragana = []string{\n"
for _, term := range x.hiragana {
raw += fmt.Sprintf("\t\"%s\",\n", term)
}
raw += "}\n\n"
raw += "// JpNameKatakana is Katakana name data in Japanese\n"
raw += "var JpNameKatakana = []string{\n"
for _, term := range x.katakana {
raw += fmt.Sprintf("\t\"%s\",\n", term)
}
raw += "}\n\n"
if _, err := fmt.Fprint(w, raw); err != nil {
return err
}
return nil
}
func (x *jpNameTerms) add(nameSet []string) {
if hasKanji(nameSet[0]) {
x.kanji = append(x.kanji, nameSet[0])
}
x.hiragana = append(x.hiragana, nameSet[1])
x.katakana = append(x.katakana, nameSet[2])
}
type jpAddressTerms struct {
kanji []string
hiragana []string
katakana []string
}
func (x *jpAddressTerms) dump(w io.Writer) error {
raw := "package piidata\n\n"
raw += "// JpAddressKanji is Kanji address data in Japanese\n"
raw += "var JpAddressKanji = []string{\n"
for _, term := range x.kanji {
raw += fmt.Sprintf("\t\"%s\",\n", term)
}
raw += "}\n\n"
raw += "// JpAddressHiragana is Hiragana address data in Japanese\n"
raw += "var JpAddressHiragana = []string{\n"
for _, term := range x.hiragana {
raw += fmt.Sprintf("\t\"%s\",\n", term)
}
raw += "}\n\n"
raw += "// JpAddressKatakana is Katakana address data in Japanese\n"
raw += "var JpAddressKatakana = []string{\n"
for _, term := range x.katakana {
raw += fmt.Sprintf("\t\"%s\",\n", term)
}
raw += "}\n\n"
if _, err := fmt.Fprint(w, raw); err != nil {
return err
}
return nil
}
func hasKanji(s string) bool {
for _, r := range s {
if !unicode.In(r, unicode.Hiragana) {
return true
}
}
return false
}
func (x *jpAddressTerms) add(nameSet []string) {
if hasKanji(nameSet[0]) {
x.kanji = append(x.kanji, nameSet[0])
}
x.hiragana = append(x.hiragana, nameSet[1])
x.katakana = append(x.katakana, nameSet[2])
}
|
package main
import (
"compress/gzip"
"log"
"net/http"
"os"
"time"
"github.com/gosom/context-spell-correct/internal/config"
"github.com/gosom/context-spell-correct/internal/webhandlers"
"github.com/gosom/context-spell-correct/pkg/spellcorrect"
)
func main() {
cfg, err := config.New()
if err != nil {
panic(err)
}
file, err := os.Open(cfg.SentencesPath)
if err != nil {
panic(err)
}
gz, err := gzip.NewReader(file)
if err != nil {
panic(err)
}
file2, err := os.Open(cfg.DictPath)
if err != nil {
panic(err)
}
gz2, err := gzip.NewReader(file2)
if err != nil {
panic(err)
}
tokenizer := spellcorrect.NewSimpleTokenizer()
freq := spellcorrect.NewFrequencies(cfg.MinWordLength, cfg.MinWordFreq)
weights := []float64{cfg.UnigramWeight, cfg.BigramWeight, cfg.TrigramWeight}
sc := spellcorrect.NewSpellCorrector(tokenizer, freq, weights)
log.Printf("starting training...")
t0 := time.Now()
sc.Train(gz, gz2)
t1 := time.Now()
log.Printf("ready[%s]\n", t1.Sub(t0))
file.Close()
gz.Close()
file2.Close()
gz2.Close()
http.HandleFunc("/", webhandlers.GetSuggestions(sc))
log.Fatal(http.ListenAndServe(cfg.Addr, webhandlers.LogRequest(http.DefaultServeMux)))
}
|
package defaults
import (
"github.com/openshift/installer/pkg/types"
"github.com/openshift/installer/pkg/types/ovirt"
)
func setMachinePool(p *types.MachinePool) {
if p.Platform.Ovirt == nil {
p.Platform.Ovirt = &ovirt.MachinePool{}
}
}
func setDefaultAffinityGroups(p *ovirt.Platform, mp *types.MachinePool, agName string) {
if mp.Platform.Ovirt.AffinityGroupsNames == nil {
for _, ag := range p.AffinityGroups {
if ag.Name == agName {
mp.Platform.Ovirt.AffinityGroupsNames = []string{agName}
}
}
}
}
func setDefaultThreads(mp *types.MachinePool) {
// Workaround for buggy threads behavior in previous versions.
if mp.Platform.Ovirt.CPU != nil && mp.Platform.Ovirt.CPU.Threads == 0 {
mp.Platform.Ovirt.CPU.Threads = 1
}
}
// SetControlPlaneDefaults sets the defaults for the ControlPlane Machines.
func SetControlPlaneDefaults(p *ovirt.Platform, mp *types.MachinePool) {
setMachinePool(mp)
setDefaultAffinityGroups(p, mp, DefaultControlPlaneAffinityGroupName)
setDefaultThreads(mp)
}
// SetComputeDefaults sets the defaults for the Compute Machines.
func SetComputeDefaults(p *ovirt.Platform, mp *types.MachinePool) {
setMachinePool(mp)
setDefaultAffinityGroups(p, mp, DefaultComputeAffinityGroupName)
setDefaultThreads(mp)
}
|
package material
import (
"math"
"testing"
"github.com/calbim/ray-tracer/src/pattern"
"github.com/calbim/ray-tracer/src/tuple"
"github.com/calbim/ray-tracer/src/color"
"github.com/calbim/ray-tracer/src/light"
)
func TestMaterial(t *testing.T) {
m := New()
if !m.Color.Equals(color.New(1, 1, 1)) {
t.Errorf("wanted color=%v, should be %v", color.New(1, 1, 1), m.Color)
}
if m.Ambient != 0.1 {
t.Errorf("wanted ambient=%v, should be %v", 0.1, m.Ambient)
}
if m.Diffuse != 0.9 {
t.Errorf("wanted diffuse=%v, should be %v", 0.9, m.Diffuse)
}
if m.Specular != 0.9 {
t.Errorf("wanted specular=%v, should be %v", 0.9, m.Specular)
}
if m.Shininess != 200 {
t.Errorf("wanted shininess=%v, should be %v", 200, m.Shininess)
}
}
func TestLightingEyeBetweenLightAndSurface(t *testing.T) {
m := New()
position := tuple.Point(0, 0, 0)
light := light.PointLight(tuple.Point(0, 0, -10), color.White)
eyev := tuple.Vector(0, 0, -1)
normalv := tuple.Vector(0, 0, -1)
result := m.Lighting(pattern.NewObject(), light, position, eyev, normalv, false)
if !result.Equals(color.New(1.9, 1.9, 1.9)) {
t.Errorf("wanted lighting=%v, got %v", color.New(1.9, 1.9, 1.9), result)
}
}
func TestLightingEyeOffset45BetweenLightAndSurface(t *testing.T) {
m := New()
position := tuple.Point(0, 0, 0)
light := light.PointLight(tuple.Point(0, 0, -10), color.White)
eyev := tuple.Vector(0, math.Sqrt(2)/2, -math.Sqrt(2)/2)
normalv := tuple.Vector(0, 0, -1)
result := m.Lighting(pattern.NewObject(), light, position, eyev, normalv, false)
if !result.Equals(color.White) {
t.Errorf("wanted lighting=%v, got %v", color.White, result)
}
}
func TestLightingEyeInPathOfReflectionVector(t *testing.T) {
m := New()
position := tuple.Point(0, 0, 0)
light := light.PointLight(tuple.Point(0, 10, -10), color.New(1, 1, 1))
eyev := tuple.Vector(0, -math.Sqrt(2)/2, -math.Sqrt(2)/2)
normalv := tuple.Vector(0, 0, -1)
result := m.Lighting(pattern.NewObject(), light, position, eyev, normalv, false)
if !result.Equals(color.New(1.6364, 1.6364, 1.6364)) {
t.Errorf("wanted lighting=%v, got %v", color.New(1.6364, 1.6364, 1.6364), result)
}
}
func TestLightingBehindSurface(t *testing.T) {
m := New()
position := tuple.Point(0, 0, 0)
light := light.PointLight(tuple.Point(0, 0, 10), color.New(1, 1, 1))
eyev := tuple.Vector(0, 0, -1)
normalv := tuple.Vector(0, 0, -1)
result := m.Lighting(pattern.NewObject(), light, position, eyev, normalv, false)
if !result.Equals(color.New(0.1, 0.1, 0.1)) {
t.Errorf("wanted lighting=%v, got %v", color.New(0.1, 0.1, 0.1), result)
}
}
func TestLightingSurfaceInShadow(t *testing.T) {
m := New()
position := tuple.Point(0, 0, 0)
eyev := tuple.Vector(0, 0, -1)
normalv := tuple.Vector(0, 0, -1)
light := light.PointLight(tuple.Point(0, 0, -10), color.New(1, 1, 1))
inShadow := true
result := m.Lighting(pattern.NewObject(), light, position, eyev, normalv, inShadow)
if !result.Equals(color.New(0.1, 0.1, 0.1)) {
t.Errorf("wanted lighting=%v, got %v", result, color.New(0.1, 0.1, 0.1))
}
}
func TestLightingWithPattern(t *testing.T) {
m := New()
m.SetPattern(pattern.NewStripe(color.White, color.Black))
m.Ambient = 1
m.Diffuse = 0
m.Specular = 0
eyev := tuple.Vector(0, 0, -1)
normalv := tuple.Vector(0, 0, -1)
l := light.PointLight(tuple.Point(0, 0, -10), color.White)
c1 := m.Lighting(pattern.NewObject(), l, tuple.Point(0.9, 0, 0), eyev, normalv, false)
c2 := m.Lighting(pattern.NewObject(), l, tuple.Point(1.1, 0, 0), eyev, normalv, false)
if !c1.Equals(color.White) {
t.Errorf("wanted c1=%v, got %v", color.White, c1)
}
if !c2.Equals(color.Black) {
t.Errorf("wanted c2=%v, got %v", color.Black, c2)
}
}
func TestLightingWithPatternApplied(t *testing.T) {
m := New()
m.SetPattern(pattern.NewStripe(color.White, color.Black))
m.Ambient = 1
m.Diffuse = 0
m.Specular = 0
eyev := tuple.Vector(0, 0, -1)
normalv := tuple.Vector(0, 0, -1)
l := light.PointLight(tuple.Point(0, 0, -10), color.White)
c1 := m.Lighting(pattern.NewObject(), l, tuple.Point(0.9, 0, 0), eyev, normalv, false)
c2 := m.Lighting(pattern.NewObject(), l, tuple.Point(1.1, 0, 0), eyev, normalv, false)
if !c1.Equals(color.White) {
t.Errorf("wanted c1=%v, got %v", color.White, c1)
}
if !c2.Equals(color.Black) {
t.Errorf("wanted c2=%v, got %v", color.White, c2)
}
}
func TestReflectivityForDefaultMaterial(t *testing.T) {
m := New()
if m.Reflective != 0.0 {
t.Errorf("wanted default reflectivity=%v, got %v", m.Reflective, 0.0)
}
}
|
package debug
import (
"fmt"
"io"
"os"
"runtime"
"strings"
)
func PrintGoroutines(allFrame bool) {
FprintGoroutines(os.Stderr, allFrame)
}
func FprintGoroutines(w io.Writer, allFrame bool) {
ng := runtime.NumGoroutine()
p := make([]runtime.StackRecord, ng)
n, ok := runtime.GoroutineProfile(p)
if !ok {
panic("The slice is too small too put all records")
return
}
for i := 0; i < n; i++ {
printStackRecord(w, i, p[i].Stack(), allFrame)
}
}
// stolen from `runtime/pprof`
func printStackRecord(w io.Writer, index int, stk []uintptr, allFrame bool) {
wasPanic := false
for i, pc := range stk {
f := runtime.FuncForPC(pc)
if f == nil {
fmt.Fprintf(w, "#\t%#x\n", pc)
wasPanic = false
} else {
tracepc := pc
// Back up to call instruction.
if i > 0 && pc > f.Entry() && !wasPanic {
if runtime.GOARCH == "386" || runtime.GOARCH == "amd64" {
tracepc--
} else {
tracepc -= 4 // arm, etc
}
}
file, line := f.FileLine(tracepc)
name := f.Name()
wasPanic = name == "runtime.panic"
if name == "runtime.goexit" || !allFrame && (strings.HasPrefix(name, "runtime.") || name == "bgsweep" || name == "runfinq" || name == "main.printGoroutines") {
continue
}
fmt.Fprintf(w, "%d.\t%#x\t%s+%#x\t%s:%d\n", index, pc, name, pc-f.Entry(), file, line)
}
}
}
|
package main
import (
"flag"
"time"
"github.com/apex/log"
"github.com/apex/log/handlers/cli"
"github.com/tj/go/flag/usage"
"github.com/apex/static/docs"
)
func init() {
log.SetHandler(cli.Default)
}
func main() {
flag.Usage = usage.Output(&usage.Config{
Examples: []usage.Example{
{
Help: "Generate site in ./build from ./docs/*.md.",
Command: "static-docs -title Up -in ./docs",
},
{
Help: "Generate a site in ./ from ../up/docs/*.md",
Command: "static-docs -title Up -in ../up/docs -out .",
},
},
})
title := flag.String("title", "", "Site title.")
subtitle := flag.String("subtitle", "", "Site subtitle or slogan.")
theme := flag.String("theme", "apex", "Theme name.")
src := flag.String("in", ".", "Source directory for markdown files.")
dst := flag.String("out", "build", "Output directory for the static site.")
segment := flag.String("segment", "", "Segment write key.")
google := flag.String("google", "", "Google Analytics tracking id.")
flag.Parse()
println()
defer println()
start := time.Now()
c := &docs.Config{
Src: *src,
Dst: *dst,
Title: *title,
Subtitle: *subtitle,
Theme: *theme,
Segment: *segment,
Google: *google,
}
if err := docs.Compile(c); err != nil {
log.Fatalf("error: %s", err)
}
log.Infof("compiled in %s\n", time.Since(start).Round(time.Millisecond))
}
|
package release
import (
"archive/zip"
"crypto/sha256"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/ExploratoryEngineering/reto/pkg/toolbox"
)
func checksumFileName(name, version string) string {
return fmt.Sprintf("%s/%s/sha256sum_%s_%s.txt", archiveDir, version, name, version)
}
func generateChecksumFile(ctx *Context, files []string) error {
checksumFilename := checksumFileName(ctx.Config.Name, ctx.Version)
f, err := os.Create(checksumFilename)
if err != nil {
toolbox.PrintError("Could not create the checksum file %s: %v", checksumFilename, err)
return err
}
defer f.Close()
for _, v := range files {
buf, err := ioutil.ReadFile(v)
if err != nil {
toolbox.PrintError("Unable to read %s: %v", v, err)
return err
}
sum := sha256.Sum256(buf)
line := fmt.Sprintf("%x %s\n", sum, filepath.Base(v))
fmt.Print(line)
if _, err := f.Write([]byte(line)); err != nil {
toolbox.PrintError("Could not write checksum to %s: %v", checksumFilename, err)
return err
}
}
return nil
}
// VerifyChecksums verifies that the files in the archive matches the checksums
// in the checksum file.
func VerifyChecksums(checksumFile, archive string) error {
type checksum struct {
File, Checksum string
}
var checksums []checksum
buf, err := ioutil.ReadFile(checksumFile)
if err != nil {
toolbox.PrintError("Couldn't read %s: %v", checksumFile, err)
return err
}
for _, line := range strings.Split(string(buf), "\n") {
fields := strings.Split(line, " ")
if len(fields) == 2 {
checksums = append(checksums, checksum{File: fields[1], Checksum: fields[0]})
}
}
if len(checksums) == 0 {
toolbox.PrintError("Could not find any checksums in file %s", checksumFile)
return errors.New("no checksums")
}
zipArchive, err := zip.OpenReader(archive)
if err != nil {
toolbox.PrintError("Could not open archive %s: %v", archive, err)
return err
}
defer zipArchive.Close()
errs := 0
for _, archivedFile := range zipArchive.File {
found := false
for _, csum := range checksums {
if csum.File == archivedFile.Name {
r, err := archivedFile.Open()
if err != nil {
toolbox.PrintError("Could not open archived file %s: %v", archivedFile.Name, err)
return err
}
buf, err := ioutil.ReadAll(r)
r.Close()
if err != nil {
toolbox.PrintError("Couldn't read archived file %s: %v", archivedFile.Name, err)
return err
}
cs := fmt.Sprintf("%x", sha256.Sum256(buf))
if cs == csum.Checksum {
fmt.Printf("%s is OK\n", csum.File)
} else {
toolbox.PrintError("**** WARNING the checksum for %s does not match the checksum file", archivedFile.Name)
errs++
}
found = true
}
}
if !found {
errs++
fmt.Printf("WARNING! %s is not in the signature file!\n", archivedFile.Name)
}
}
if errs > 0 {
toolbox.PrintError("================================================")
toolbox.PrintError("!!!! Archive has files with checksum errors !!!!")
toolbox.PrintError("================================================")
return errors.New("checksum error")
}
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.