text stringlengths 11 4.05M |
|---|
package evaluation
import (
"errors"
flatbuffers "github.com/google/flatbuffers/go"
"github.com/wolffcm/flatbuffers-example/tree"
)
// EvalFromBytes evaluates the expression tree contained in the given flatbuffer.
func EvalFromBytes(bs []byte) (float64, error) {
root := tree.GetRootAsRoot(bs, 0)
unionTable := new(flatbuffers.Table)
if hasExpr := root.Expr(unionTable); !hasExpr {
return 0.0, errors.New("missing root expr")
}
return dispatchFromUnionTable(root.ExprType(), unionTable)
}
func dispatchFromUnionTable(ty tree.Node, tbl *flatbuffers.Table) (float64, error) {
var v float64
var err error
switch ty {
case tree.NodeConstant:
c := new(tree.Constant)
c.Init(tbl.Bytes, tbl.Pos)
v, err = evalConstant(c)
case tree.NodeBinOp:
bo := new(tree.BinOp)
bo.Init(tbl.Bytes, tbl.Pos)
v, err = evalBinOp(bo)
default:
return 0.0, errors.New("unhandled node type: " + tree.EnumNamesNode[ty])
}
if err != nil {
return 0.0, err
}
return v, nil
}
func evalConstant(c *tree.Constant) (float64, error) {
return c.Value(), nil
}
func evalBinOp(bo *tree.BinOp) (float64, error) {
var lhs float64
{
fbt := new(flatbuffers.Table)
if hasLHS := bo.Lhs(fbt); !hasLHS {
return 0.0, errors.New("missing LHS")
}
var err error
if lhs, err = dispatchFromUnionTable(bo.LhsType(), fbt); err != nil {
return 0.0, err
}
}
var rhs float64
{
fbt := new(flatbuffers.Table)
if hasRHS := bo.Rhs(fbt); !hasRHS {
return 0.0, errors.New("missing RHS")
}
var err error
if rhs, err = dispatchFromUnionTable(bo.RhsType(), fbt); err != nil {
return 0.0, err
}
}
switch o := bo.Op(); o {
case tree.OpAdd:
return lhs + rhs, nil
case tree.OpSubtract:
return lhs - rhs, nil
case tree.OpMultiply:
return lhs * rhs, nil
case tree.OpDivide:
return lhs / rhs, nil
default:
return 0.0, errors.New("unknown bin op: " + tree.EnumNamesOp[o])
}
} |
package nmstask
import (
"fmt"
"github.com/Centny/gwf/util"
"github.com/Centny/nms/nmsdb"
"testing"
"time"
)
var mv = map[string]int{}
func echo(a *nmsdb.Action, args ...interface{}) {
fmt.Println(util.S2Json(a))
mv[a.Uri] += 1
}
func TestTask(t *testing.T) {
var fcfg = util.NewFcfg3()
fcfg.InitWithFilePath("task_c.properties")
var task *Task
//test rc
fcfg.SetVal("tasks", "loc_rcs,loc_rcc")
task = NewTask(ActionF(echo))
task.Start(fcfg)
time.Sleep(time.Second * 3)
task.rcs.Close()
time.Sleep(time.Second * 3)
task.Stop()
if mv["127.0.0.1:2337"] < 1 {
t.Error("error")
return
}
if mv[":2337"] < 1 {
t.Error("error")
return
}
fmt.Println("test rc done...\n\n")
//test http
fcfg.SetVal("tasks", "baidu,baidu_d")
task = NewTask(ActionF(echo))
task.Start(fcfg)
time.Sleep(time.Second * 3)
task.Stop()
if mv["http://www.baidu.com"] < 1 {
t.Error("error")
return
}
if mv["http://www.baidu.com/index.html"] < 1 {
t.Error("error")
return
}
fmt.Println("test http done...\n\n")
//
fcfg.SetVal("loc_rcc/token", "sdkfsk")
fcfg.SetVal("tasks", "loc_rcs,loc_rcc")
task = NewTask(ActionF(echo))
task.Start(fcfg)
time.Sleep(time.Second)
task.Stop()
//
fcfg.SetVal("loc_rcs/rc_addr", ":2kdd")
fcfg.SetVal("tasks", "loc_rcs")
task = NewTask(ActionF(echo))
task.Start(fcfg)
time.Sleep(time.Second)
task.Stop()
//
fcfg.SetVal("loc_rcs/token", "")
fcfg.SetVal("loc_rcc/token", "")
fcfg.SetVal("baidu/url", "")
fcfg.SetVal("baidu_d/url", "")
fcfg.SetVal("tasks", "loc_rcs,loc_rcc,baidu,baidu_d")
task = NewTask(ActionF(echo))
task.Start(fcfg)
time.Sleep(time.Second)
task.Stop()
//
fcfg.SetVal("tasks", "")
task = NewTask(ActionF(echo))
task.Start(fcfg)
time.Sleep(time.Second)
task.Stop()
//
NewTaskCCH("name", "typ", nil).OnCmd(nil)
}
|
//sqlite是一个嵌入式数据库,嵌入到程序当中的数据库.
//几乎每个发行版都会预装sqlite.
//这是一个sqlite的测试程序.
//首先需要安装sqlite3的驱动
// go get -u github.com/mattn/go-sqlite3
//date:2018-06-11
//by:JuZhen
package main
import (
"database/sql"
"fmt"
"time"
_ "github.com/mattn/go-sqlite3"
)
func main() {
//打开数据库,不存在就创建
db, err := sql.Open("sqlite3", "./foo.db")
checkErr(err)
//创建表的命令
//`在~上面,不是单引号
sql_table := `
CREATE TABLE IF NOT EXISTS userinfo(
uid INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(64) NULL,
departname VARCHAR(64) NULL,
created DATE NULL
);
`
db.Exec(sql_table)
//插入数据
stmt, err := db.Prepare("INSERT INTO userinfo(username, departname, created) values(?,?,?)")
checkErr(err)
res, err := stmt.Exec("王大明", "战忽局", "2018-07-03")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Print(id)
//更新数据
stmt, err = db.Prepare("update userinfo set username=? where uid=?")
checkErr(err)
res, err = stmt.Exec("李小明", id)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Print(affect)
//查询数据
rows, err := db.Query("SELECT * FROM userinfo")
checkErr(err)
var uid int
var username string
var departname string
var created time.Time
for rows.Next() {
err = rows.Scan(&uid, &username, &departname, &created)
checkErr(err)
fmt.Println(uid, username, departname, created)
}
rows.Close()
//删除数据
stmt, err = db.Prepare("delete from userinfo where uid=?")
checkErr(err)
res, err = stmt.Exec(id)
checkErr(err)
affect, err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
db.Close()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
|
package file
import (
"fmt"
"os"
"path/filepath"
)
// Path 文件路径
type Path struct {
parts []string
}
// NewPath 创建路径对象
func NewPath(parts ...string) *Path {
return &Path{parts}
}
// Join 连接路径
func (p *Path) Join(parts ...string) *Path {
p.parts = append(p.parts, parts...)
return p
}
func (p *Path) String(parts ...string) string {
return filepath.Join(p.parts...)
}
// Exist 文件或目录是否存在
func Exist(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}
// NotExist 文件或目录是否不存在
func NotExist(filename string) bool {
_, err := os.Stat(filename)
return os.IsNotExist(err)
}
// CreateDir 创建目录
func CreateDir(dirs ...string) error {
for _, dir := range dirs {
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return fmt.Errorf("create dir [%v] failed: %v", dir, err)
}
}
return nil
}
|
package core
func NewList(args ...Type) *Type {
slice := make([]Type, 0)
for _, arg := range args {
slice = append(slice, arg)
}
return &Type{List: &slice}
}
func (node *Type) IsList() bool {
return node.List != nil
}
|
package sdk
// ImagePullPolicy represents a policy for whether container hosts already
// having a certain OCI image should attempt to re-pull that image prior to
// launching a new container based on that image.
type ImagePullPolicy string
const (
// ImagePullPolicyIfNotPresent represents a policy wherein container hosts
// only attempt to pull an OCI image if that image does not already exist on
// the host.
ImagePullPolicyIfNotPresent ImagePullPolicy = "IfNotPresent"
// ImagePullPolicyAlways represents a policy wherein container hosts will
// always attempt to re-pull an OCI image before launching a container based
// on that image.
ImagePullPolicyAlways ImagePullPolicy = "Always"
)
// ContainerSpec represents the technical details of an OCI container.
type ContainerSpec struct {
// Image specifies the OCI image on which the container should be based.
Image string `json:"image,omitempty"`
// ImagePullPolicy specifies whether a container host already having the
// specified OCI image should attempt to re-pull that image prior to launching
// a new container.
ImagePullPolicy ImagePullPolicy `json:"imagePullPolicy,omitempty"`
// Command specifies the command to be executed by the OCI container. This
// can be used to optionally override the default command specified by the OCI
// image itself.
Command []string `json:"command,omitempty"`
// Arguments specifies arguments to the command executed by the OCI container.
Arguments []string `json:"arguments,omitempty"`
// Environment is a map of key/value pairs that specify environment variables
// to be set within the OCI container.
Environment map[string]string `json:"environment,omitempty"`
}
|
package main
import (
"fmt"
"strings"
)
func main() {
boardingPass := "InSight Mission to Mars"
mars := strings.Contains(boardingPass, "Mars")
if mars {
fmt.Printf("Boarding pass: %v\n", boardingPass)
}
if strings.Contains(boardingPass, "Mars") {
fmt.Printf("Mars: %v", boardingPass)
} else {
fmt.Printf("Not Mars: %v", boardingPass)
}
}
|
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
type App struct {
Router *mux.Router
DB *sql.DB
}
func (a *App) Initialize(user, password, dbname, host, port string) {
connectionString :=
fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable host=%s port=%s",
user,
password,
dbname,
host,
port)
var err error
a.DB, err = sql.Open("postgres", connectionString)
if err != nil {
log.Fatal(err)
}
a.Router = mux.NewRouter()
a.initializeRoutes()
}
func (a *App) Run() {
log.Fatal(http.ListenAndServe(":8000", a.Router))
}
// Route actions
func (a *App) getCompanies(w http.ResponseWriter, r *http.Request) {
count, _ := strconv.Atoi(r.FormValue("count"))
start, _ := strconv.Atoi(r.FormValue("start"))
if count > 10 || count < 1 {
count = 10
}
if start < 0 {
start = 0
}
companies, err := getCompanies(a.DB, start, count)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, companies)
}
func (a *App) getCompany(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid company id")
}
c := company{Id: id}
if err := c.getCompany(a.DB); err != nil {
switch err {
case sql.ErrNoRows:
respondWithError(w, http.StatusNotFound, "Company not found")
default:
respondWithError(w, http.StatusInternalServerError, err.Error())
}
return
}
respondWithJSON(w, http.StatusOK, c)
}
func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]string{"error": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
|
// DO NOT REMOVE TAGS BELOW. IF ANY NEW TEST FILES ARE CREATED UNDER /osde2e, PLEASE ADD THESE TAGS TO THEM IN ORDER TO BE EXCLUDED FROM UNIT TESTS.
//go:build osde2e
// +build osde2e
package osde2etests
import (
"context"
"time"
"github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"github.com/openshift/osde2e-common/pkg/clients/openshift"
"github.com/openshift/osde2e-common/pkg/gomega/assertions"
. "github.com/openshift/osde2e-common/pkg/gomega/matchers"
sfv1alpha1 "github.com/openshift/splunk-forwarder-operator/api/v1alpha1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/log"
)
var (
k8s *openshift.Client
deploymentName = "splunk-forwarder-operator"
operatorName = "splunk-forwarder-operator"
serviceNames = []string{"splunk-forwarder-operator-metrics",
"splunk-forwarder-operator-catalog"}
rolePrefix = "splunk-forwarder-operator"
testsplunkforwarder = "osde2e-splunkforwarder-test-2"
dedicatedadminsplunkforwarder = "osde2e-dedicated-admin-splunkforwarder-x"
operatorNamespace = "openshift-splunk-forwarder-operator"
operatorLockFile = "splunk-forwarder-operator-lock"
)
// Blocking SplunkForwarder Signal
var _ = ginkgo.Describe("Splunk Forwarder Operator", ginkgo.Ordered, func() {
ginkgo.BeforeAll(func() {
log.SetLogger(ginkgo.GinkgoLogr)
var err error
k8s, err = openshift.New(ginkgo.GinkgoLogr)
Expect(err).ShouldNot(HaveOccurred(), "unable to setup k8s client")
Expect(sfv1alpha1.AddToScheme(k8s.GetScheme())).Should(BeNil(), "unable to register sfv1alpha1 api scheme")
})
ginkgo.It("is installed", func(ctx context.Context) {
ginkgo.By("checking the namespace exists")
err := k8s.Get(ctx, operatorNamespace, operatorNamespace, &corev1.Namespace{})
Expect(err).Should(BeNil(), "namespace %s not found", operatorNamespace)
ginkgo.By("checking the role exists")
var roles rbacv1.RoleList
err = k8s.WithNamespace(operatorNamespace).List(ctx, &roles)
Expect(err).ShouldNot(HaveOccurred(), "failed to list roles")
Expect(&roles).Should(ContainItemWithPrefix(rolePrefix), "unable to find roles with prefix %s", rolePrefix)
ginkgo.By("checking the rolebinding exists")
var rolebindings rbacv1.RoleBindingList
err = k8s.List(ctx, &rolebindings)
Expect(err).ShouldNot(HaveOccurred(), "failed to list rolebindings")
Expect(&rolebindings).Should(ContainItemWithPrefix(rolePrefix), "unable to find rolebindings with prefix %s", rolePrefix)
ginkgo.By("checking the clusterrole exists")
var clusterRoles rbacv1.ClusterRoleList
err = k8s.List(ctx, &clusterRoles)
Expect(err).ShouldNot(HaveOccurred(), "failed to list clusterroles")
Expect(&clusterRoles).Should(ContainItemWithPrefix(rolePrefix), "unable to find cluster role with prefix %s", rolePrefix)
ginkgo.By("checking the clusterrolebinding exists")
var clusterRoleBindings rbacv1.ClusterRoleBindingList
err = k8s.List(ctx, &clusterRoleBindings)
Expect(err).ShouldNot(HaveOccurred(), "unable to list clusterrolebindings")
Expect(&clusterRoleBindings).Should(ContainItemWithPrefix(rolePrefix), "unable to find clusterrolebinding with prefix %s", rolePrefix)
ginkgo.By("checking the services exist")
for _, serviceName := range serviceNames {
err = k8s.Get(ctx, serviceName, operatorNamespace, &corev1.Service{})
Expect(err).Should(BeNil(), "unable to get service %s/%s", operatorNamespace, serviceName)
}
ginkgo.By("checking the deployment exists and is available")
assertions.EventuallyDeployment(ctx, k8s, deploymentName, operatorNamespace)
ginkgo.By("checking the operator lock file config map exists")
assertions.EventuallyConfigMap(ctx, k8s, operatorLockFile, operatorNamespace).WithTimeout(time.Duration(300)*time.Second).WithPolling(time.Duration(30)*time.Second).Should(Not(BeNil()), "configmap %s should exist", operatorLockFile)
ginkgo.By("checking the operator CSV has Succeeded")
restConfig, _ := config.GetConfig()
dynamicClient, err := dynamic.NewForConfig(restConfig)
Expect(err).ShouldNot(HaveOccurred(), "failed to configure Dynamic client")
Eventually(func() bool {
csvList, err := dynamicClient.Resource(
schema.GroupVersionResource{
Group: "operators.coreos.com",
Version: "v1alpha1",
Resource: "clusterserviceversions",
},
).Namespace(operatorNamespace).List(ctx, metav1.ListOptions{})
Expect(err).NotTo(HaveOccurred(), "Failed to retrieve CSV from namespace %s", operatorNamespace)
for _, csv := range csvList.Items {
specName, _, _ := unstructured.NestedFieldCopy(csv.Object, "spec", "displayName")
statusPhase, _, _ := unstructured.NestedFieldCopy(csv.Object, "status", "phase")
if statusPhase == "Succeeded" && specName == operatorName {
return true
}
}
return false
}).WithTimeout(time.Duration(300)*time.Second).WithPolling(time.Duration(30)*time.Second).Should(BeTrue(), "CSV %s should exist and have Succeeded status", operatorName)
// TODO: post osde2e-common library add upgrade check
//checkUpgrade(helper.New(), "openshift-splunk-forwarder-operator",
// "openshift-splunk-forwarder-operator", "splunk-forwarder-operator",
// "splunk-forwarder-operator-catalog")
})
sf := makeMinimalSplunkforwarder(testsplunkforwarder)
ginkgo.It("admin should be able to create SplunkForwarders CR", func(ctx context.Context) {
err := k8s.WithNamespace(operatorNamespace).Create(ctx, &sf)
Expect(err).NotTo(HaveOccurred())
})
ginkgo.It("admin should be able to delete SplunkForwarders CR", func(ctx context.Context) {
err := k8s.Delete(ctx, &sf)
Expect(err).NotTo(HaveOccurred())
})
ginkgo.It("dedicated admin should not be able to manage SplunkForwarders CR", func(ctx context.Context) {
dsf := makeMinimalSplunkforwarder(dedicatedadminsplunkforwarder)
impersonatedResourceClient, _ := k8s.Impersonate("test-user@redhat.com", "dedicated-admins")
Expect(sfv1alpha1.AddToScheme(impersonatedResourceClient.GetScheme())).Should(BeNil(), "unable to register sfv1alpha1 api scheme")
err := impersonatedResourceClient.WithNamespace(operatorNamespace).Create(ctx, &dsf)
Expect(apierrors.IsForbidden(err)).To(BeTrue(), "expected err to be forbidden, got: %v", err)
})
})
// Create test splunkforwarder CR definition
func makeMinimalSplunkforwarder(name string) sfv1alpha1.SplunkForwarder {
return sfv1alpha1.SplunkForwarder{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: operatorNamespace,
},
Spec: sfv1alpha1.SplunkForwarderSpec{
SplunkLicenseAccepted: true,
UseHeavyForwarder: false,
SplunkInputs: []sfv1alpha1.SplunkForwarderInputs{
{
Path: "",
},
},
},
}
}
|
/*
Description
We remind that the permutation of some final set is a one-to-one mapping of the set onto itself. Less formally, that is a way to reorder elements of the set. For example, one can define a permutation of the set {1,2,3,4,5} as follows:
http://poj.org/images/2369_1.jpg
This record defines a permutation P as follows: P(1) = 4, P(2) = 1, P(3) = 5, etc.
What is the value of the expression P(P(1))? It’s clear, that P(P(1)) = P(4) = 2. And P(P(3)) = P(5) = 3. One can easily see that if P(n) is a permutation then P(P(n)) is a permutation as well. In our example (believe us)
http://poj.org/images/2369_2.jpg
It is natural to denote this permutation by P2(n) = P(P(n)). In a general form the defenition is as follows: P(n) = P1(n), Pk(n) = P(Pk-1(n)). Among the permutations there is a very important one — that moves nothing:
http://poj.org/images/2369_3.jpg
It is clear that for every k the following relation is satisfied: (EN)k = EN. The following less trivial statement is correct (we won't prove it here, you may prove it yourself incidentally): Let P(n) be some permutation of an N elements set. Then there exists a natural number k, that Pk = EN. The least natural k such that Pk = EN is called an order of the permutation P.
The problem that your program should solve is formulated now in a very simple manner: "Given a permutation find its order."
Input
In the first line of the standard input an only natural number N (1 <= N <= 1000) is contained, that is a number of elements in the set that is rearranged by this permutation. In the second line there are N natural numbers of the range from 1 up to N, separated by a space, that define a permutation — the numbers P(1), P(2),…, P(N).
Output
You should write an only natural number to the standard output, that is an order of the permutation. You may consider that an answer shouldn't exceed 109.
Sample Input
5
4 1 5 2 3
Sample Output
6
Source
Ural State University Internal Contest October'2000 Junior Session
*/
package main
import (
"math"
)
func main() {
assert(order([]int{4, 1, 5, 2, 3}) == 6)
assert(order([]int{1, 3, 4, 2}) == 3)
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func order(a []int) int {
x := append([]int{}, a...)
y := make([]int, len(x))
for i := 1; i < math.MaxInt; i++ {
if identity(x) {
return i
}
x, y = apply(x, y, a)
}
return -1
}
func apply(x, y, a []int) ([]int, []int) {
for i := range x {
y[i] = x[a[i]-1]
}
return y, x
}
func identity(a []int) bool {
for i := range a {
if a[i] != i+1 {
return false
}
}
return true
}
|
package exec
func CToF(c C) F {
return F(c*9/5 + 32)
}
func FToC(f F) C {
return C((f-32)*5/9
}
|
package factory
func RandNum() int {
}
|
// package wantlist implements an object for bitswap that contains the keys
// that a given peer wants.
package wantlist
import (
"sort"
"sync"
cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
)
type ThreadSafe struct {
lk sync.RWMutex
set map[cid.Cid]*Entry
}
// not threadsafe
type Wantlist struct {
set map[cid.Cid]*Entry
}
type Entry struct {
Cid cid.Cid
Priority int
SesTrk map[uint64]struct{}
// Trash in a book-keeping field
Trash bool
}
// NewRefEntry creates a new reference tracked wantlist entry.
func NewRefEntry(c cid.Cid, p int) *Entry {
return &Entry{
Cid: c,
Priority: p,
SesTrk: make(map[uint64]struct{}),
}
}
type entrySlice []*Entry
func (es entrySlice) Len() int { return len(es) }
func (es entrySlice) Swap(i, j int) { es[i], es[j] = es[j], es[i] }
func (es entrySlice) Less(i, j int) bool { return es[i].Priority > es[j].Priority }
func NewThreadSafe() *ThreadSafe {
return &ThreadSafe{
set: make(map[cid.Cid]*Entry),
}
}
func New() *Wantlist {
return &Wantlist{
set: make(map[cid.Cid]*Entry),
}
}
// Add adds the given cid to the wantlist with the specified priority, governed
// by the session ID 'ses'. if a cid is added under multiple session IDs, then
// it must be removed by each of those sessions before it is no longer 'in the
// wantlist'. Calls to Add are idempotent given the same arguments. Subsequent
// calls with different values for priority will not update the priority.
// TODO: think through priority changes here
// Add returns true if the cid did not exist in the wantlist before this call
// (even if it was under a different session).
func (w *ThreadSafe) Add(c cid.Cid, priority int, ses uint64) bool {
w.lk.Lock()
defer w.lk.Unlock()
if e, ok := w.set[c]; ok {
e.SesTrk[ses] = struct{}{}
return false
}
w.set[c] = &Entry{
Cid: c,
Priority: priority,
SesTrk: map[uint64]struct{}{ses: struct{}{}},
}
return true
}
// AddEntry adds given Entry to the wantlist. For more information see Add method.
func (w *ThreadSafe) AddEntry(e *Entry, ses uint64) bool {
w.lk.Lock()
defer w.lk.Unlock()
if ex, ok := w.set[e.Cid]; ok {
ex.SesTrk[ses] = struct{}{}
return false
}
w.set[e.Cid] = e
e.SesTrk[ses] = struct{}{}
return true
}
// Remove removes the given cid from being tracked by the given session.
// 'true' is returned if this call to Remove removed the final session ID
// tracking the cid. (meaning true will be returned iff this call caused the
// value of 'Contains(c)' to change from true to false)
func (w *ThreadSafe) Remove(c cid.Cid, ses uint64) bool {
w.lk.Lock()
defer w.lk.Unlock()
e, ok := w.set[c]
if !ok {
return false
}
delete(e.SesTrk, ses)
if len(e.SesTrk) == 0 {
delete(w.set, c)
return true
}
return false
}
// Contains returns true if the given cid is in the wantlist tracked by one or
// more sessions.
func (w *ThreadSafe) Contains(k cid.Cid) (*Entry, bool) {
w.lk.RLock()
defer w.lk.RUnlock()
e, ok := w.set[k]
return e, ok
}
func (w *ThreadSafe) Entries() []*Entry {
w.lk.RLock()
defer w.lk.RUnlock()
es := make([]*Entry, 0, len(w.set))
for _, e := range w.set {
es = append(es, e)
}
return es
}
func (w *ThreadSafe) SortedEntries() []*Entry {
es := w.Entries()
sort.Sort(entrySlice(es))
return es
}
func (w *ThreadSafe) Len() int {
w.lk.RLock()
defer w.lk.RUnlock()
return len(w.set)
}
func (w *Wantlist) Len() int {
return len(w.set)
}
func (w *Wantlist) Add(c cid.Cid, priority int) bool {
if _, ok := w.set[c]; ok {
return false
}
w.set[c] = &Entry{
Cid: c,
Priority: priority,
}
return true
}
func (w *Wantlist) AddEntry(e *Entry) bool {
if _, ok := w.set[e.Cid]; ok {
return false
}
w.set[e.Cid] = e
return true
}
func (w *Wantlist) Remove(c cid.Cid) bool {
_, ok := w.set[c]
if !ok {
return false
}
delete(w.set, c)
return true
}
func (w *Wantlist) Contains(c cid.Cid) (*Entry, bool) {
e, ok := w.set[c]
return e, ok
}
func (w *Wantlist) Entries() []*Entry {
es := make([]*Entry, 0, len(w.set))
for _, e := range w.set {
es = append(es, e)
}
return es
}
func (w *Wantlist) SortedEntries() []*Entry {
es := w.Entries()
sort.Sort(entrySlice(es))
return es
}
|
/**
* Copyright 2017 IBM Corp.
*
* 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 flex
import (
"context"
"fmt"
"github.com/IBM/ubiquity-k8s/utils"
watcher "github.com/IBM/ubiquity-k8s/utils/watcher"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
)
type ServiceSyncer struct {
name, namespace string
kubeClient kubernetes.Interface
ctx context.Context
handler cache.ResourceEventHandler
}
func NewServiceSyncer(kubeClient kubernetes.Interface, ctx context.Context) (*ServiceSyncer, error) {
ns, err := utils.GetCurrentNamespace()
if err != nil {
return nil, err
}
ss := &ServiceSyncer{
name: utils.UbiquityServiceName,
namespace: ns,
kubeClient: kubeClient,
ctx: ctx,
}
h := cache.ResourceEventHandlerFuncs{
AddFunc: ss.processService,
UpdateFunc: ss.processServiceUpdate,
}
ss.handler = h
return ss, nil
}
// Sync watches the ubiquity service and sync its CLusterIP changes to flex config file
func (ss *ServiceSyncer) Sync() error {
ubiquitySvcWatcher, err := watcher.GenerateSvcWatcher(
ss.name, ss.namespace,
ss.kubeClient.CoreV1(),
logger)
if err != nil {
return err
}
// process service for the first time if it is already existing.
svc, err := ss.kubeClient.CoreV1().Services(ss.namespace).Get(ss.name, metav1.GetOptions{})
if err == nil {
ss.processService(svc)
}
err = watcher.Watch(ubiquitySvcWatcher, ss.handler, ss.ctx, logger)
return err
}
// processService compare the ubiquity IP between service and config file and apply
// the new value to flex config file if they are different.
func (ss *ServiceSyncer) processService(obj interface{}) {
currentFlexConfig, err := defaultFlexConfigSyncer.GetCurrentFlexConfig()
if err != nil {
logger.Error(fmt.Sprintf("Can't read flex config file: %v", err))
return
}
ubiquityIP := currentFlexConfig.UbiquityServer.Address
svc := obj.(*v1.Service)
if svc != nil && svc.Spec.ClusterIP != ubiquityIP {
currentFlexConfig.UbiquityServer.Address = svc.Spec.ClusterIP
err := defaultFlexConfigSyncer.UpdateFlexConfig(currentFlexConfig)
if err != nil {
logger.Error(fmt.Sprintf("Can't write flex config file: %v", err))
// revert change
currentFlexConfig.UbiquityServer.Address = ubiquityIP
return
}
}
}
func (ss *ServiceSyncer) processServiceUpdate(old, cur interface{}) {
if old == nil {
ss.processService(cur)
return
}
oldSvc := old.(*v1.Service)
curSvc := cur.(*v1.Service)
if oldSvc.Spec.ClusterIP != curSvc.Spec.ClusterIP {
ss.processService(cur)
}
}
|
package job_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/google/uuid"
"github.com/odpf/optimus/core/tree"
"github.com/odpf/optimus/job"
"github.com/odpf/optimus/mock"
"github.com/odpf/optimus/models"
"github.com/odpf/optimus/store"
"github.com/odpf/salt/log"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)
func TestReplaySyncer(t *testing.T) {
log := log.NewNoop()
ctx := context.TODO()
reqBatchSize := 100
runTimeout := time.Hour * 5
activeReplayUUID := uuid.Must(uuid.NewRandom())
startDate := time.Date(2020, time.Month(8), 22, 0, 0, 0, 0, time.UTC)
endDate := time.Date(2020, time.Month(8), 23, 0, 0, 0, 0, time.UTC)
batchEndDate := endDate.AddDate(0, 0, 1).Add(time.Second * -1)
dagStartTime := time.Date(2020, time.Month(4), 05, 0, 0, 0, 0, time.UTC)
specs := make(map[string]models.JobSpec)
spec1 := "dag1"
spec2 := "dag2"
noDependency := map[string]models.JobSpecDependency{}
twoAMSchedule := models.JobSpecSchedule{
StartDate: dagStartTime,
Interval: "0 2 * * *",
}
oneDayTaskWindow := models.JobSpecTask{
Window: models.JobSpecTaskWindow{
Size: time.Hour * 24,
},
}
threeDayTaskWindow := models.JobSpecTask{
Window: models.JobSpecTaskWindow{
Size: time.Hour * 24 * 3,
},
}
specs[spec1] = models.JobSpec{ID: uuid.Must(uuid.NewRandom()), Name: spec1, Dependencies: noDependency, Schedule: twoAMSchedule, Task: oneDayTaskWindow}
specs[spec2] = models.JobSpec{ID: uuid.Must(uuid.NewRandom()), Name: spec2, Dependencies: getDependencyObject(specs, spec1), Schedule: twoAMSchedule, Task: threeDayTaskWindow}
executionTreeDependent := tree.NewTreeNode(specs[spec2])
executionTreeDependent.Runs.Add(time.Date(2020, time.Month(8), 22, 2, 0, 0, 0, time.UTC))
executionTreeDependent.Runs.Add(time.Date(2020, time.Month(8), 23, 2, 0, 0, 0, time.UTC))
executionTree := tree.NewTreeNode(specs[spec1])
executionTree.Runs.Add(time.Date(2020, time.Month(8), 22, 2, 0, 0, 0, time.UTC))
executionTree.Runs.Add(time.Date(2020, time.Month(8), 23, 2, 0, 0, 0, time.UTC))
executionTree.AddDependent(executionTreeDependent)
activeReplaySpec := []models.ReplaySpec{
{
ID: activeReplayUUID,
Job: specs[spec1],
StartDate: startDate,
EndDate: endDate,
Status: models.ReplayStatusReplayed,
ExecutionTree: executionTree,
},
}
projectSpecs := []models.ProjectSpec{
{
ID: uuid.Must(uuid.NewRandom()),
Name: "project-sample",
Config: map[string]string{
"bucket": "gs://some_folder",
},
},
}
t.Run("Sync", func(t *testing.T) {
t.Run("should not return error when no replay with sync criteria found", func(t *testing.T) {
projectRepository := new(mock.ProjectRepository)
projectRepository.On("GetAll", ctx).Return(projectSpecs, nil)
defer projectRepository.AssertExpectations(t)
projectRepoFactory := new(mock.ProjectRepoFactory)
projectRepoFactory.On("New").Return(projectRepository)
defer projectRepoFactory.AssertExpectations(t)
replayRepository := new(mock.ReplayRepository)
defer replayRepository.AssertExpectations(t)
replayRepository.On("GetByProjectIDAndStatus", ctx, projectSpecs[0].ID, job.ReplayStatusToSynced).Return([]models.ReplaySpec{}, store.ErrResourceNotFound)
replaySpecRepoFac := new(mock.ReplaySpecRepoFactory)
defer replaySpecRepoFac.AssertExpectations(t)
replaySpecRepoFac.On("New").Return(replayRepository)
replaySyncer := job.NewReplaySyncer(log, replaySpecRepoFac, projectRepoFactory, nil, time.Now)
err := replaySyncer.Sync(context.TODO(), runTimeout)
assert.Nil(t, err)
})
t.Run("should return error when fetching replays failed", func(t *testing.T) {
projectRepository := new(mock.ProjectRepository)
projectRepository.On("GetAll", ctx).Return(projectSpecs, nil)
defer projectRepository.AssertExpectations(t)
projectRepoFactory := new(mock.ProjectRepoFactory)
projectRepoFactory.On("New").Return(projectRepository)
defer projectRepoFactory.AssertExpectations(t)
replayRepository := new(mock.ReplayRepository)
defer replayRepository.AssertExpectations(t)
errorMsg := "fetching replay error"
replayRepository.On("GetByProjectIDAndStatus", ctx, projectSpecs[0].ID, job.ReplayStatusToSynced).Return([]models.ReplaySpec{}, errors.New(errorMsg))
replaySpecRepoFac := new(mock.ReplaySpecRepoFactory)
defer replaySpecRepoFac.AssertExpectations(t)
replaySpecRepoFac.On("New").Return(replayRepository)
replaySyncer := job.NewReplaySyncer(log, replaySpecRepoFac, projectRepoFactory, nil, time.Now)
err := replaySyncer.Sync(context.TODO(), runTimeout)
assert.Equal(t, errorMsg, err.Error())
})
t.Run("should mark state of running replay to success if all instances are success", func(t *testing.T) {
projectRepository := new(mock.ProjectRepository)
projectRepository.On("GetAll", ctx).Return(projectSpecs, nil)
defer projectRepository.AssertExpectations(t)
projectRepoFactory := new(mock.ProjectRepoFactory)
projectRepoFactory.On("New").Return(projectRepository)
defer projectRepoFactory.AssertExpectations(t)
replayRepository := new(mock.ReplayRepository)
defer replayRepository.AssertExpectations(t)
replayRepository.On("GetByProjectIDAndStatus", ctx, projectSpecs[0].ID, job.ReplayStatusToSynced).Return(activeReplaySpec, nil)
replaySpecRepoFac := new(mock.ReplaySpecRepoFactory)
defer replaySpecRepoFac.AssertExpectations(t)
replaySpecRepoFac.On("New").Return(replayRepository)
jobStatus := []models.JobStatus{
{
ScheduledAt: time.Date(2020, time.Month(8), 22, 2, 0, 0, 0, time.UTC),
State: models.RunStateSuccess,
},
{
ScheduledAt: time.Date(2020, time.Month(8), 23, 2, 0, 0, 0, time.UTC),
State: models.RunStateSuccess,
},
}
scheduler := new(mock.Scheduler)
defer scheduler.AssertExpectations(t)
scheduler.On("GetJobRunStatus", ctx, projectSpecs[0], specs[spec1].Name, startDate, batchEndDate, reqBatchSize).Return(jobStatus, nil).Once()
scheduler.On("GetJobRunStatus", ctx, projectSpecs[0], specs[spec2].Name, startDate, batchEndDate, reqBatchSize).Return(jobStatus, nil).Once()
successReplayMessage := models.ReplayMessage{
Type: models.ReplayStatusSuccess,
Message: job.ReplayMessageSuccess,
}
replayRepository.On("UpdateStatus", ctx, activeReplayUUID, models.ReplayStatusSuccess, successReplayMessage).Return(nil)
replaySyncer := job.NewReplaySyncer(log, replaySpecRepoFac, projectRepoFactory, scheduler, time.Now)
err := replaySyncer.Sync(context.TODO(), runTimeout)
assert.Nil(t, err)
})
t.Run("should mark state of running replay to failed if no longer running instance and one of instances is failed", func(t *testing.T) {
projectRepository := new(mock.ProjectRepository)
projectRepository.On("GetAll", ctx).Return(projectSpecs, nil)
defer projectRepository.AssertExpectations(t)
projectRepoFactory := new(mock.ProjectRepoFactory)
projectRepoFactory.On("New").Return(projectRepository)
defer projectRepoFactory.AssertExpectations(t)
replayRepository := new(mock.ReplayRepository)
defer replayRepository.AssertExpectations(t)
replayRepository.On("GetByProjectIDAndStatus", ctx, projectSpecs[0].ID, job.ReplayStatusToSynced).Return(activeReplaySpec, nil)
replaySpecRepoFac := new(mock.ReplaySpecRepoFactory)
defer replaySpecRepoFac.AssertExpectations(t)
replaySpecRepoFac.On("New").Return(replayRepository)
jobStatus := []models.JobStatus{
{
ScheduledAt: time.Date(2020, time.Month(8), 22, 2, 0, 0, 0, time.UTC),
State: models.RunStateSuccess,
},
{
ScheduledAt: time.Date(2020, time.Month(8), 23, 2, 0, 0, 0, time.UTC),
State: models.RunStateFailed,
},
}
scheduler := new(mock.Scheduler)
defer scheduler.AssertExpectations(t)
scheduler.On("GetJobRunStatus", ctx, projectSpecs[0], specs[spec1].Name, startDate, batchEndDate, reqBatchSize).Return(jobStatus, nil).Once()
scheduler.On("GetJobRunStatus", ctx, projectSpecs[0], specs[spec2].Name, startDate, batchEndDate, reqBatchSize).Return(jobStatus, nil).Once()
failedReplayMessage := models.ReplayMessage{
Type: models.ReplayStatusFailed,
Message: job.ReplayMessageFailed,
}
replayRepository.On("UpdateStatus", ctx, activeReplayUUID, models.ReplayStatusFailed, failedReplayMessage).Return(nil)
replaySyncer := job.NewReplaySyncer(log, replaySpecRepoFac, projectRepoFactory, scheduler, time.Now)
err := replaySyncer.Sync(context.TODO(), runTimeout)
assert.Nil(t, err)
})
t.Run("should not update replay status if instances are still running", func(t *testing.T) {
projectRepository := new(mock.ProjectRepository)
projectRepository.On("GetAll", ctx).Return(projectSpecs, nil)
defer projectRepository.AssertExpectations(t)
projectRepoFactory := new(mock.ProjectRepoFactory)
projectRepoFactory.On("New").Return(projectRepository)
defer projectRepoFactory.AssertExpectations(t)
replayRepository := new(mock.ReplayRepository)
defer replayRepository.AssertExpectations(t)
replayRepository.On("GetByProjectIDAndStatus", ctx, projectSpecs[0].ID, job.ReplayStatusToSynced).Return(activeReplaySpec, nil)
replaySpecRepoFac := new(mock.ReplaySpecRepoFactory)
defer replaySpecRepoFac.AssertExpectations(t)
replaySpecRepoFac.On("New").Return(replayRepository)
jobStatus := []models.JobStatus{
{
ScheduledAt: time.Date(2020, time.Month(8), 22, 2, 0, 0, 0, time.UTC),
State: models.RunStateSuccess,
},
{
ScheduledAt: time.Date(2020, time.Month(8), 23, 2, 0, 0, 0, time.UTC),
State: models.RunStateRunning,
},
}
scheduler := new(mock.Scheduler)
defer scheduler.AssertExpectations(t)
scheduler.On("GetJobRunStatus", ctx, projectSpecs[0], specs[spec1].Name, startDate, batchEndDate, reqBatchSize).Return(jobStatus, nil).Once()
scheduler.On("GetJobRunStatus", ctx, projectSpecs[0], specs[spec2].Name, startDate, batchEndDate, reqBatchSize).Return(jobStatus, nil).Once()
replaySyncer := job.NewReplaySyncer(log, replaySpecRepoFac, projectRepoFactory, scheduler, time.Now)
err := replaySyncer.Sync(context.TODO(), runTimeout)
assert.Nil(t, err)
})
t.Run("should mark timeout replay as failed", func(t *testing.T) {
projectRepository := new(mock.ProjectRepository)
projectRepository.On("GetAll", ctx).Return(projectSpecs, nil)
defer projectRepository.AssertExpectations(t)
projectRepoFactory := new(mock.ProjectRepoFactory)
projectRepoFactory.On("New").Return(projectRepository)
defer projectRepoFactory.AssertExpectations(t)
replayCreatedAt := time.Now().Add(time.Hour * -5)
replaySpec := []models.ReplaySpec{
{
ID: activeReplayUUID,
Job: specs[spec1],
StartDate: startDate,
EndDate: endDate,
Status: models.ReplayStatusAccepted,
CreatedAt: replayCreatedAt,
},
}
replayRepository := new(mock.ReplayRepository)
defer replayRepository.AssertExpectations(t)
replayRepository.On("GetByProjectIDAndStatus", ctx, projectSpecs[0].ID, job.ReplayStatusToSynced).Return(replaySpec, nil)
replaySpecRepoFac := new(mock.ReplaySpecRepoFactory)
defer replaySpecRepoFac.AssertExpectations(t)
replaySpecRepoFac.On("New").Return(replayRepository)
failedReplayMessage := models.ReplayMessage{
Type: job.ReplayRunTimeout,
Message: fmt.Sprintf("replay has been running since %s", replayCreatedAt.UTC().Format(job.TimestampLogFormat)),
}
replayRepository.On("UpdateStatus", ctx, activeReplayUUID, models.ReplayStatusFailed, failedReplayMessage).Return(nil)
replaySyncer := job.NewReplaySyncer(log, replaySpecRepoFac, projectRepoFactory, nil, time.Now)
err := replaySyncer.Sync(context.TODO(), runTimeout)
assert.Nil(t, err)
})
t.Run("should return error when unable to get dag run status from batchScheduler", func(t *testing.T) {
projectRepository := new(mock.ProjectRepository)
projectRepository.On("GetAll", ctx).Return(projectSpecs, nil)
defer projectRepository.AssertExpectations(t)
projectRepoFactory := new(mock.ProjectRepoFactory)
projectRepoFactory.On("New").Return(projectRepository)
defer projectRepoFactory.AssertExpectations(t)
replayRepository := new(mock.ReplayRepository)
defer replayRepository.AssertExpectations(t)
replayRepository.On("GetByProjectIDAndStatus", ctx, projectSpecs[0].ID, job.ReplayStatusToSynced).Return(activeReplaySpec, nil)
replaySpecRepoFac := new(mock.ReplaySpecRepoFactory)
defer replaySpecRepoFac.AssertExpectations(t)
replaySpecRepoFac.On("New").Return(replayRepository)
scheduler := new(mock.Scheduler)
defer scheduler.AssertExpectations(t)
errorMsg := "fetch dag run status from batchScheduler failed"
scheduler.On("GetJobRunStatus", ctx, projectSpecs[0], specs[spec1].Name, startDate, batchEndDate, reqBatchSize).Return([]models.JobStatus{}, errors.New(errorMsg)).Once()
replaySyncer := job.NewReplaySyncer(log, replaySpecRepoFac, projectRepoFactory, scheduler, time.Now)
err := replaySyncer.Sync(context.TODO(), runTimeout)
assert.Contains(t, err.Error(), errorMsg)
})
})
}
|
/*
* Copyright 2018 Haines Chan
*
* This program is free software; you can redistribute and/or modify it
* under the terms of the standard MIT license. See LICENSE for more details
*/
package app
import (
"strings"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/current"
"github.com/coreos/etcd/pkg/transport"
"github.com/hainesc/anchor/internal/pkg/config"
"github.com/hainesc/anchor/pkg/allocator/anchor"
"github.com/hainesc/anchor/pkg/runtime/k8s"
"github.com/hainesc/anchor/pkg/store/etcd"
)
// CmdAdd allocates IP for pod
func CmdAdd(args *skel.CmdArgs) error {
ipamConf, confVersion, err := config.LoadIPAMConf(args.StdinData, args.Args)
if err != nil { // Error in config file.
return err
}
alloc, err := newAllocator(args, ipamConf)
if err != nil { // Error during init Allocator
return err
}
// Init result here, which will be printed in json format.
result := ¤t.Result{}
// Handle customized network configurations.
if result, err = alloc.CustomizeGateway(result); err != nil {
return err
}
if result, err = alloc.CustomizeRoutes(result); err != nil {
return err
}
if result, err = alloc.CustomizeDNS(result); err != nil {
return err
}
// Add an item of route:
// service-cluster-ip-range -> Node IP
if result, err = alloc.AddServiceRoute(result, ipamConf.ServiceIPNet, ipamConf.NodeIPs); err != nil {
return err
}
ipConf, err := alloc.Allocate(args.ContainerID)
if err != nil {
return err
}
result.IPs = append(result.IPs, ipConf)
return types.PrintResult(result, confVersion)
}
// CmdDel deletes IP for pod
func CmdDel(args *skel.CmdArgs) error {
ipamConf, _, err := config.LoadIPAMConf(args.StdinData, args.Args)
if err != nil { // Error in config file.
return err
}
cleaner, err := newCleaner(args, ipamConf)
return cleaner.Clean(args.ContainerID)
}
func newAllocator(args *skel.CmdArgs, conf *config.IPAMConf) (*anchor.Allocator, error) {
tlsInfo := &transport.TLSInfo{
CertFile: conf.CertFile,
KeyFile: conf.KeyFile,
TrustedCAFile: conf.TrustedCAFile,
}
tlsConfig, _ := tlsInfo.ClientConfig()
// Use etcd as store
store, err := etcd.NewEtcdClient(conf.Name,
strings.Split(conf.Endpoints, ","),
tlsConfig)
defer store.Close()
if err != nil {
return nil, err
}
// 1. Get K8S_POD_NAME and K8S_POD_NAMESPACE.
k8sArgs := k8s.Args{}
if err := types.LoadArgs(args.Args, &k8sArgs); err != nil {
return nil, err
}
// 2. Get conf for k8s client and create a k8s_client
runtime, err := k8s.NewK8sClient(conf.Kubernetes, conf.Policy)
if err != nil {
return nil, err
}
// 3. Get annotations from k8s_client via K8S_POD_NAME and K8S_POD_NAMESPACE.
label, annot, err := k8s.GetK8sPodInfo(runtime, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE))
if err != nil {
return nil, err
}
customized := make(map[string]string)
for k, v := range label {
customized[k] = v
}
for k, v := range annot {
customized[k] = v
}
// It is friendly to show which controller the pods controled by.
// TODO: maybe it is meaningless. the pod name starts with the controller name.
controllerName, _ := k8s.ResourceControllerName(runtime, string(k8sArgs.K8S_POD_NAME), string(k8sArgs.K8S_POD_NAMESPACE))
if controllerName != "" {
customized["cni.anchor.org/controller"] = controllerName
}
return anchor.NewAllocator(store, string(k8sArgs.K8S_POD_NAME),
string(k8sArgs.K8S_POD_NAMESPACE), customized)
}
func newCleaner(args *skel.CmdArgs, ipamConf *config.IPAMConf) (*anchor.Cleaner, error) {
tlsInfo := &transport.TLSInfo{
CertFile: ipamConf.CertFile,
KeyFile: ipamConf.KeyFile,
TrustedCAFile: ipamConf.TrustedCAFile,
}
tlsConfig, _ := tlsInfo.ClientConfig()
store, err := etcd.NewEtcdClient(ipamConf.Name,
strings.Split(ipamConf.Endpoints, ","), tlsConfig)
defer store.Close()
if err != nil {
return nil, err
}
// Read pod name and namespace from args
k8sArgs := k8s.Args{}
if err := types.LoadArgs(args.Args, &k8sArgs); err != nil {
return nil, err
}
return anchor.NewCleaner(store,
string(k8sArgs.K8S_POD_NAME),
string(k8sArgs.K8S_POD_NAMESPACE))
}
|
// test-closure-packet project main.go
package main
import (
"fmt"
)
func playerGen(name string) func() (string, int) {
hp := 150
return func() (string, int) {
return name, hp
}
}
func main() {
fmt.Println("Hello World!")
generator := playerGen("sand and wood")
name, hp := generator()
fmt.Println(name, hp)
name2, hp2 := generator()
fmt.Println(name2, hp2)
}
|
package fwatch
import (
"os"
"path/filepath"
"github.com/BurntSushi/toml"
)
// Config - config data
type Config struct {
path string
Targets []Target
}
// Target - target
type Target struct {
Path string
Script string
Type []string
}
// Load - load config yml file
func Load(path string) (config *Config, err error) {
config = &Config{}
// get absolute path
path, err = filepath.Abs(path)
print("load config: %s", path)
_, err = os.Stat(path)
if os.IsNotExist(err) {
f, _ := os.Create(path)
f.WriteString("Targets = []\n")
f.Close()
}
// load toml to Config struct
if _, err = toml.DecodeFile(path, config); err != nil {
print("error: %v", err)
return nil, err
}
config.path = path
return config, nil
}
// Register -
func (c Config) Register(p, s string, t []string) error {
target := Target{p, s, t}
c.Targets = append(c.Targets, target)
f, err := os.OpenFile(c.path, os.O_WRONLY, os.ModeAppend)
if err != nil {
print("error: %v\n", err)
return err
}
defer f.Close()
enc := toml.NewEncoder(f)
enc.Indent = " "
err = enc.Encode(c)
return err
}
// Unregister -
func (c Config) Unregister(index int) error {
c.Targets = append(c.Targets[:index], c.Targets[index+1:]...)
f, err := os.Create(c.path)
if err != nil {
return err
}
defer f.Close()
enc := toml.NewEncoder(f)
err = enc.Encode(c)
return err
}
|
// Copyright 2015 Matthew Collins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"fmt"
"image"
"image/png"
"net/http"
"strconv"
"golang.org/x/image/draw"
"github.com/gorilla/mux"
)
func rawSkin(rw http.ResponseWriter, rq *http.Request) {
v := mux.Vars(rq)
skin := getSkinForID(v["uuid"])
rw.Write(skin.Data)
}
func basicIcon(rw http.ResponseWriter, rq *http.Request) {
v := mux.Vars(rq)
size, err := strconv.Atoi(v["size"])
if err != nil {
size = 64
}
if size > Config.MaxSize {
size = Config.MaxSize
} else if size < Config.MinSize {
size = Config.MinSize
}
hat := v["hat"]
if hat == "" {
hat = "nohat"
}
id := fmt.Sprintf("head:%d:%s:%s", size, hat, v["uuid"])
rw.Write(getOrCreateEntry(id, func(entry *imageEntry) {
skin := getSkinForID(v["uuid"])
img, err := png.Decode(bytes.NewReader(skin.Data))
if err != nil {
return
}
out := image.NewNRGBA(image.Rect(0, 0, size, size))
fs := size
fo := 0
if hat == "hat" {
fo = int(float64(fs) * (1.0 / 32.0))
fs -= fo
}
draw.NearestNeighbor.Scale(
out,
image.Rect(fo, fo, fs, fs),
img,
image.Rect(8, 8, 8+8, 8+8),
draw.Over,
nil,
)
if hat == "hat" {
draw.NearestNeighbor.Scale(
out,
image.Rect(0, 0, size, size),
img,
image.Rect(32+8, 8, 32+8+8, 8+8),
draw.Over,
nil,
)
}
var buf bytes.Buffer
png.Encode(&buf, out)
entry.Data = buf.Bytes()
}).Data)
}
|
/*
Copyright © 2022 SUSE LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package manage
import (
"fmt"
"os"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc/eventlog"
"golang.org/x/sys/windows/svc/mgr"
)
const (
SECURITY_DESCRIPTOR_REVISION = 1
DACL_SECURITY_INFORMATION = 4
)
var advapi32 = windows.NewLazySystemDLL("advapi32.dll")
// Install Service installs the Rancher Desktop Privileged Service process as Windows Service
func InstallService(name, displayName, desc string) error {
instPath, err := getInstallPath(0)
if err != nil {
return fmt.Errorf("getting installation path for service [%s] failed: %w", name, err)
}
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
// We always need uninstall first to unregister,
// the event logger recreation service can yield to a registry key error
// e.g RancherDesktopPrivilegedService registry key already exists
UninstallService(name)
s, err := m.CreateService(name, instPath, mgr.Config{DisplayName: displayName, Description: desc})
if err != nil {
return fmt.Errorf("service creation failed: %w", err)
}
defer s.Close()
if err := setServiceObjectSecurity(s.Handle); err != nil {
return err
}
err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info)
if err != nil {
s.Delete()
return fmt.Errorf("setup event log for [%s] failed: %w", name, err)
}
return nil
}
func setServiceObjectSecurity(handle windows.Handle) error {
sd, err := initializeSecurityDescriptor()
if err != nil {
return err
}
pSetServiceObjectSecurity := advapi32.NewProc("SetServiceObjectSecurity")
res, _, err := pSetServiceObjectSecurity.Call(uintptr(handle), DACL_SECURITY_INFORMATION, sd.SecurityDescriptor)
if int(res) == 0 {
return os.NewSyscallError("SetServiceObjectSecurity", err)
}
return nil
}
func initializeSecurityDescriptor() (*syscall.SecurityAttributes, error) {
pInitializeSecurityDescriptor := advapi32.NewProc("InitializeSecurityDescriptor")
sd := make([]byte, 4096)
res, _, err := pInitializeSecurityDescriptor.Call(uintptr(unsafe.Pointer(&sd[0])), SECURITY_DESCRIPTOR_REVISION)
if int(res) == 0 {
return nil, os.NewSyscallError("InitializeSecurityDescriptor", err)
}
var sa syscall.SecurityAttributes
sa.Length = uint32(unsafe.Sizeof(sa))
sa.SecurityDescriptor = uintptr(unsafe.Pointer(&sd[0]))
return &sa, nil
}
func getInstallPath(handle windows.Handle) (string, error) {
n := uint32(1024)
var buf []uint16
for {
buf = make([]uint16, n)
r, err := windows.GetModuleFileName(handle, &buf[0], n)
if err != nil {
return "", err
}
if r < n {
break
}
// r == n means n not big enough
n += 1024
}
return syscall.UTF16ToString(buf), nil
}
|
package tmp
import (
"errors"
"github.com/rendau/lily"
lilyHttp "github.com/rendau/lily/http"
"github.com/rendau/lily/zip"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
)
var (
_dirPath string
_dirName string
_dirFullPath string
_timeLimit time.Duration
_cleanupInterval time.Duration
)
func Init(dirPath, dirName string, timeLimit time.Duration, cleanupInterval time.Duration) {
if dirPath == "" || dirName == "" || timeLimit == 0 || cleanupInterval == 0 {
log.Panicln("Bad initial params")
}
_dirPath = dirPath
_dirName = dirName
_dirFullPath = filepath.Join(_dirPath, _dirName)
_timeLimit = timeLimit
_cleanupInterval = cleanupInterval
err := os.MkdirAll(_dirFullPath, os.ModePerm)
lily.ErrPanic(err)
go cleaner()
}
func UploadFileFromHttpRequestForm(r *http.Request, key, fnSuffix string,
requireExt, extractZip bool) (error, string, string, string, string) {
if _dirPath == "" || _dirName == "" {
log.Panicln("Tmp module used befor inited")
}
fn := generateFilename(fnSuffix)
err, newFileName := lilyHttp.UploadFileFromRequestForm(
r,
key,
_dirFullPath,
fn+"_*",
requireExt,
)
if err != nil {
return err, "", "", "", ""
}
fPath := filepath.Join(_dirFullPath, newFileName)
rPath := filepath.Join(_dirName, newFileName)
eFPath := ""
eRPath := ""
if extractZip && strings.ToLower(filepath.Ext(fPath)) == ".zip" {
eFPath, err = ioutil.TempDir(_dirFullPath, fn+"_")
if err == nil {
err = zip.ExtractFromFile(fPath, eFPath)
if err == nil {
eRPath, _ = filepath.Rel(_dirPath, eFPath)
}
}
}
return err, fPath, rPath, eFPath, eRPath
}
func Copy(urlStr string, dirPath, dir string, filename string, requireExt bool) (string, error) {
notFoundError := errors.New("bad_url")
u, err := url.Parse(urlStr)
if err != nil {
return "", err
}
urlPathSlice := strings.SplitN(u.Path, _dirName+"/", 2)
if len(urlPathSlice) != 2 {
return "", notFoundError
}
filePath := filepath.Join(append([]string{_dirFullPath}, strings.Split(urlPathSlice[1], "/")...)...)
fileExt := filepath.Ext(filePath)
if requireExt && fileExt == "" {
return "", errors.New("bad_extension")
}
srcFile, err := os.Open(filePath)
if err != nil {
return "", notFoundError
}
defer srcFile.Close()
finalDstDirPath := filepath.Join(dirPath, dir)
err = os.MkdirAll(finalDstDirPath, os.ModePerm)
if err != nil {
return "", err
}
dstFile, err := ioutil.TempFile(finalDstDirPath, filename+"_*"+fileExt)
if err != nil {
return "", err
}
defer dstFile.Close()
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return "", err
}
newName, err := filepath.Rel(dirPath, dstFile.Name())
if err != nil {
return "", err
}
return newName, nil
}
func generateFilename(suffix string) string {
res := time.Now().UTC().Format("2006_01_02_15_04_05")
if suffix != "" {
res += "_" + suffix
}
return res
}
func parseFilename(src string) *time.Time {
if len(src) > 19 {
t, err := time.Parse("2006_01_02_15_04_05", src[:19])
if err != nil {
return nil
}
return &t
}
return nil
}
func cleaner() {
var err error
var rpath string
var ftime *time.Time
var now time.Time
var deletePaths []string
for {
//fmt.Println("start cleaning temp files...")
now = time.Now()
deletePaths = nil
err = filepath.Walk(
_dirFullPath,
func(path string, f os.FileInfo, err error) error {
if err != nil {
return nil
}
if f == nil {
return nil
}
//fmt.Println(path, rpath, f.Name())
if f.IsDir() {
rpath, err = filepath.Rel(_dirPath, path)
if err != nil {
return nil
}
if rpath == _dirName {
return nil
}
}
ftime = parseFilename(f.Name())
if ftime == nil || ftime.Add(_timeLimit).Before(now) {
deletePaths = append(deletePaths, path)
}
if f.IsDir() {
return filepath.SkipDir
}
return nil
},
)
lily.ErrPanic(err)
// delete old files
for _, x := range deletePaths {
_ = os.RemoveAll(x)
}
//fmt.Printf(" deleted %d paths\n", len(deletePaths))
time.Sleep(_cleanupInterval)
}
}
|
package main
import "fmt"
func main() {
//fmt.Println(2 & 3)
//fmt.Println(2 | 3)
//fmt.Println(2 ^ 3)
fmt.Println(-2 ^ 2)
fmt.Println(-2^3)
//fmt.Println(5 << 1)
//fmt.Println(-5 >> 1)
//fmt.Println(-5 >> 100)
//fmt.Println(-5 << 2)
//fmt.Println(-5 << 4)
//fmt.Println(-4<<2 )
}
|
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to 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 grumpy
import (
"fmt"
"math/big"
"reflect"
"regexp"
"runtime"
"testing"
)
func TestAssert(t *testing.T) {
assert := newBuiltinFunction("TestAssert", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
switch argc := len(args); argc {
case 1:
if raised := Assert(f, args[0], nil); raised != nil {
return nil, raised
}
case 2:
if raised := Assert(f, args[0], args[1]); raised != nil {
return nil, raised
}
default:
return nil, f.RaiseType(SystemErrorType, fmt.Sprintf("Assert expected 1 or 2 args, got %d", argc))
}
return None, nil
}).ToObject()
emptyAssert := toBaseExceptionUnsafe(mustNotRaise(AssertionErrorType.Call(NewRootFrame(), nil, nil)))
cases := []invokeTestCase{
{args: wrapArgs(true), want: None},
{args: wrapArgs(NewTuple(None)), want: None},
{args: wrapArgs(None), wantExc: emptyAssert},
{args: wrapArgs(NewDict()), wantExc: emptyAssert},
{args: wrapArgs(false, "foo"), wantExc: mustCreateException(AssertionErrorType, "foo")},
}
for _, cas := range cases {
if err := runInvokeTestCase(assert, &cas); err != "" {
t.Error(err)
}
}
}
func TestBinaryOps(t *testing.T) {
fooType := newTestClass("Foo", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__add__": newBuiltinFunction("__add__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewStr("foo add").ToObject(), nil
}).ToObject(),
"__radd__": newBuiltinFunction("__add__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewStr("foo radd").ToObject(), nil
}).ToObject(),
}))
barType := newTestClass("Bar", []*Type{fooType}, NewDict())
bazType := newTestClass("Baz", []*Type{IntType}, newStringDict(map[string]*Object{
"__rdiv__": newBuiltinFunction("__rdiv__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
s, raised := ToStr(f, args[1])
if raised != nil {
return nil, raised
}
return s.ToObject(), nil
}).ToObject(),
}))
inplaceType := newTestClass("Inplace", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__iadd__": newBuiltinFunction("__iadd__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__iand__": newBuiltinFunction("__iand__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__idiv__": newBuiltinFunction("__idiv__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__ilshift__": newBuiltinFunction("__ilshift__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__imod__": newBuiltinFunction("__imod__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__imul__": newBuiltinFunction("__imul__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__ior__": newBuiltinFunction("__ior__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__irshift__": newBuiltinFunction("__irshift__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__isub__": newBuiltinFunction("__isub__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
"__ixor__": newBuiltinFunction("__ixor__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[1], nil
}).ToObject(),
}))
cases := []struct {
fun func(f *Frame, v, w *Object) (*Object, *BaseException)
v, w *Object
want *Object
wantExc *BaseException
}{
{Add, NewStr("foo").ToObject(), NewStr("bar").ToObject(), NewStr("foobar").ToObject(), nil},
{Add, NewStr("foo").ToObject(), NewStr("bar").ToObject(), NewStr("foobar").ToObject(), nil},
{Add, newObject(fooType), newObject(ObjectType), NewStr("foo add").ToObject(), nil},
{And, NewInt(-42).ToObject(), NewInt(244).ToObject(), NewInt(212).ToObject(), nil},
{And, NewInt(42).ToObject(), NewStr("foo").ToObject(), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for &: 'int' and 'str'")},
{Add, newObject(fooType), newObject(barType), NewStr("foo add").ToObject(), nil},
{Div, NewInt(123).ToObject(), newObject(bazType), NewStr("123").ToObject(), nil},
{IAdd, NewStr("foo").ToObject(), NewStr("bar").ToObject(), NewStr("foobar").ToObject(), nil},
{IAdd, NewStr("foo").ToObject(), NewStr("bar").ToObject(), NewStr("foobar").ToObject(), nil},
{IAdd, newObject(fooType), newObject(ObjectType), NewStr("foo add").ToObject(), nil},
{IAdd, newObject(inplaceType), NewStr("foo").ToObject(), NewStr("foo").ToObject(), nil},
{IAnd, NewInt(9).ToObject(), NewInt(12).ToObject(), NewInt(8).ToObject(), nil},
{IAnd, newObject(inplaceType), NewStr("foo").ToObject(), NewStr("foo").ToObject(), nil},
{IAnd, newObject(ObjectType), newObject(fooType), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for &: 'object' and 'Foo'")},
{IDiv, NewInt(123).ToObject(), newObject(bazType), NewStr("123").ToObject(), nil},
{IDiv, newObject(inplaceType), NewInt(42).ToObject(), NewInt(42).ToObject(), nil},
{ILShift, newObject(inplaceType), NewInt(123).ToObject(), NewInt(123).ToObject(), nil},
{IMod, NewInt(24).ToObject(), NewInt(6).ToObject(), NewInt(0).ToObject(), nil},
{IMod, newObject(inplaceType), NewFloat(3.14).ToObject(), NewFloat(3.14).ToObject(), nil},
{IMul, NewStr("foo").ToObject(), NewInt(3).ToObject(), NewStr("foofoofoo").ToObject(), nil},
{IMul, newObject(inplaceType), True.ToObject(), True.ToObject(), nil},
{IMul, newObject(ObjectType), newObject(fooType), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for *: 'object' and 'Foo'")},
{IOr, newObject(inplaceType), NewInt(42).ToObject(), NewInt(42).ToObject(), nil},
{IOr, NewInt(9).ToObject(), NewInt(12).ToObject(), NewInt(13).ToObject(), nil},
{IOr, newObject(ObjectType), newObject(fooType), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for |: 'object' and 'Foo'")},
{IRShift, newObject(inplaceType), NewInt(123).ToObject(), NewInt(123).ToObject(), nil},
{ISub, NewInt(3).ToObject(), NewInt(-3).ToObject(), NewInt(6).ToObject(), nil},
{ISub, newObject(inplaceType), None, None, nil},
{IXor, newObject(inplaceType), None, None, nil},
{IXor, NewInt(9).ToObject(), NewInt(12).ToObject(), NewInt(5).ToObject(), nil},
{IXor, newObject(ObjectType), newObject(fooType), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for ^: 'object' and 'Foo'")},
{Mod, NewInt(24).ToObject(), NewInt(6).ToObject(), NewInt(0).ToObject(), nil},
{Mul, NewStr("foo").ToObject(), NewInt(3).ToObject(), NewStr("foofoofoo").ToObject(), nil},
{Mul, newObject(ObjectType), newObject(fooType), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for *: 'object' and 'Foo'")},
{Or, NewInt(-42).ToObject(), NewInt(244).ToObject(), NewInt(-10).ToObject(), nil},
{Or, NewInt(42).ToObject(), NewStr("foo").ToObject(), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for |: 'int' and 'str'")},
{Pow, NewInt(2).ToObject(), NewInt(-2).ToObject(), NewFloat(0.25).ToObject(), nil},
{Pow, NewInt(2).ToObject(), newObject(fooType), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for **: 'int' and 'Foo'")},
{Sub, NewInt(3).ToObject(), NewInt(-3).ToObject(), NewInt(6).ToObject(), nil},
{Xor, NewInt(-42).ToObject(), NewInt(244).ToObject(), NewInt(-222).ToObject(), nil},
{Xor, NewInt(42).ToObject(), NewStr("foo").ToObject(), nil, mustCreateException(TypeErrorType, "unsupported operand type(s) for ^: 'int' and 'str'")},
}
for _, cas := range cases {
testCase := invokeTestCase{wrapArgs(cas.v, cas.w), nil, cas.want, cas.wantExc}
if err := runInvokeTestCase(wrapFuncForTest(cas.fun), &testCase); err != "" {
t.Error(err)
}
}
}
func TestCompare(t *testing.T) {
badCmpType := newTestClass("BadCmp", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__cmp__": newBuiltinFunction("__cmp__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return nil, f.RaiseType(TypeErrorType, "uh oh")
}).ToObject(),
}))
cmpLtType := newTestClass("Lt", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__cmp__": newBuiltinFunction("__cmp__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewInt(-1).ToObject(), nil
}).ToObject(),
}))
cmpEqType := newTestClass("Eq", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__cmp__": newBuiltinFunction("__cmp__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewInt(0).ToObject(), nil
}).ToObject(),
}))
cmpGtType := newTestClass("Gt", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__cmp__": newBuiltinFunction("__cmp__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewInt(1).ToObject(), nil
}).ToObject(),
}))
cmpByEqType := newTestClass("EqCmp", []*Type{IntType}, newStringDict(map[string]*Object{
"__eq__": newBuiltinFunction("__eq__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return True.ToObject(), nil
}).ToObject(),
}))
badCmpByEqType := newTestClass("BadEqCmp", []*Type{IntType}, newStringDict(map[string]*Object{
"__eq__": newBuiltinFunction("__eq__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return nil, f.RaiseType(TypeErrorType, "uh oh")
}).ToObject(),
}))
badNonZeroType := newTestClass("BadNonZeroType", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__nonzero__": newBuiltinFunction("__nonzero__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return nil, f.RaiseType(TypeErrorType, "uh oh")
}).ToObject(),
}))
worseCmpByEqType := newTestClass("WorseEqCmp", []*Type{IntType}, newStringDict(map[string]*Object{
"__eq__": newBuiltinFunction("__eq__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return newObject(badNonZeroType), nil
}).ToObject(),
}))
cmpNonIntResultType := newTestClass("CmpNonIntResult", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__cmp__": newBuiltinFunction("__cmp__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewStr("foo").ToObject(), nil
}).ToObject(),
}))
cases := []invokeTestCase{
// Test `__cmp__` less than.
{args: wrapArgs(newObject(cmpLtType), None), want: NewInt(-1).ToObject()},
{args: wrapArgs(None, newObject(cmpGtType)), want: NewInt(-1).ToObject()},
// Test `__cmp__` equals.
{args: wrapArgs(newObject(cmpEqType), None), want: NewInt(0).ToObject()},
{args: wrapArgs(None, newObject(cmpEqType)), want: NewInt(0).ToObject()},
// Test `__cmp__` greater than.
{args: wrapArgs(newObject(cmpGtType), None), want: NewInt(1).ToObject()},
{args: wrapArgs(None, newObject(cmpLtType)), want: NewInt(1).ToObject()},
// Test `__cmp__` fallback to rich comparison.
{args: wrapArgs(newObject(cmpByEqType), None), want: NewInt(0).ToObject()},
{args: wrapArgs(None, newObject(cmpByEqType)), want: NewInt(0).ToObject()},
// Test bad `__cmp__` fallback to rich comparison.
{args: wrapArgs(newObject(badCmpByEqType), None), wantExc: mustCreateException(TypeErrorType, "uh oh")},
{args: wrapArgs(None, newObject(badCmpByEqType)), wantExc: mustCreateException(TypeErrorType, "uh oh")},
// Test bad `__cmp__` fallback to rich comparison where a bad object is returned from `__eq__`.
{args: wrapArgs(newObject(worseCmpByEqType), None), wantExc: mustCreateException(TypeErrorType, "uh oh")},
{args: wrapArgs(None, newObject(worseCmpByEqType)), wantExc: mustCreateException(TypeErrorType, "uh oh")},
// Test bad `__cmp__`.
{args: wrapArgs(newObject(badCmpType), None), wantExc: mustCreateException(TypeErrorType, "uh oh")},
{args: wrapArgs(None, newObject(badCmpType)), wantExc: mustCreateException(TypeErrorType, "uh oh")},
// Test bad `__cmp__` with non-int result.
{args: wrapArgs(newObject(cmpNonIntResultType), None), wantExc: mustCreateException(TypeErrorType, "an integer is required")},
{args: wrapArgs(None, newObject(cmpNonIntResultType)), wantExc: mustCreateException(TypeErrorType, "an integer is required")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Compare), &cas); err != "" {
t.Error(err)
}
}
}
func TestCompareDefault(t *testing.T) {
o1, o2 := newObject(ObjectType), newObject(ObjectType)
// Make sure uintptr(o1) < uintptr(o2).
if uintptr(o1.toPointer()) > uintptr(o2.toPointer()) {
o1, o2 = o2, o1
}
// When type names are equal, comparison should fall back to comparing
// the pointer values of the types of the objects.
fakeObjectType := newTestClass("object", []*Type{ObjectType}, NewDict())
o3, o4 := newObject(fakeObjectType), newObject(ObjectType)
if uintptr(o3.typ.toPointer()) > uintptr(o4.typ.toPointer()) {
o3, o4 = o4, o3
}
// An int subtype that equals anything, but doesn't override other
// comparison methods.
eqType := newTestClass("Eq", []*Type{IntType}, newStringDict(map[string]*Object{
"__eq__": newBuiltinFunction("__eq__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return True.ToObject(), nil
}).ToObject(),
"__repr__": newBuiltinFunction("__repr__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewStr("<Foo>").ToObject(), nil
}).ToObject(),
}))
cases := []invokeTestCase{
{args: wrapArgs(true, o1), want: compareAllResultLT},
{args: wrapArgs(o1, -306), want: compareAllResultGT},
{args: wrapArgs(-306, o1), want: compareAllResultLT},
{args: wrapArgs(NewList(), None), want: compareAllResultGT},
{args: wrapArgs(None, "foo"), want: compareAllResultLT},
{args: wrapArgs(o1, o1), want: compareAllResultEq},
{args: wrapArgs(o1, o2), want: compareAllResultLT},
{args: wrapArgs(o2, o1), want: compareAllResultGT},
{args: wrapArgs(o3, o4), want: compareAllResultLT},
{args: wrapArgs(o4, o3), want: compareAllResultGT},
// The equality test should dispatch to the eqType instance and
// return true.
{args: wrapArgs(42, newObject(eqType)), want: newTestTuple(false, false, true, true, true, true).ToObject()},
}
for _, cas := range cases {
if err := runInvokeTestCase(compareAll, &cas); err != "" {
t.Error(err)
}
}
}
func TestContains(t *testing.T) {
cases := []invokeTestCase{
{args: wrapArgs(NewTuple(), 42), want: False.ToObject()},
{args: wrapArgs(newTestList("foo", "bar"), "bar"), want: True.ToObject()},
{args: wrapArgs(newTestDict(1, "foo", 2, "bar", 3, "baz"), 2), want: True.ToObject()},
{args: wrapArgs("foobar", "ooba"), want: True.ToObject()},
{args: wrapArgs("qux", "ooba"), want: False.ToObject()},
{args: wrapArgs(3.14, None), wantExc: mustCreateException(TypeErrorType, "'float' object is not iterable")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Contains), &cas); err != "" {
t.Error(err)
}
}
}
// DelAttr is tested in TestObjectDelAttr.
func TestDelItem(t *testing.T) {
delItem := newBuiltinFunction("TestDelItem", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkFunctionArgs(f, "TestDelItem", args, ObjectType, ObjectType); raised != nil {
return nil, raised
}
o := args[0]
if raised := DelItem(f, o, args[1]); raised != nil {
return nil, raised
}
return args[0], nil
}).ToObject()
cases := []invokeTestCase{
{args: wrapArgs(newTestDict("foo", None), "foo"), want: NewDict().ToObject()},
{args: wrapArgs(NewDict(), "foo"), wantExc: mustCreateException(KeyErrorType, "foo")},
{args: wrapArgs(123, "bar"), wantExc: mustCreateException(TypeErrorType, "'int' object does not support item deletion")},
}
for _, cas := range cases {
if err := runInvokeTestCase(delItem, &cas); err != "" {
t.Error(err)
}
}
}
func TestFormatException(t *testing.T) {
fun := wrapFuncForTest(func(f *Frame, t *Type, args ...*Object) (string, *BaseException) {
e, raised := t.Call(f, args, nil)
if raised != nil {
return "", raised
}
f.Raise(e, nil, nil)
s := FormatExc(f)
f.RestoreExc(nil, nil)
return s, nil
})
cases := []invokeTestCase{
{args: wrapArgs(ExceptionType), want: NewStr("Exception\n").ToObject()},
{args: wrapArgs(AttributeErrorType, ""), want: NewStr("AttributeError\n").ToObject()},
{args: wrapArgs(TypeErrorType, 123), want: NewStr("TypeError: 123\n").ToObject()},
{args: wrapArgs(AttributeErrorType, "hello", "there"), want: NewStr("AttributeError: ('hello', 'there')\n").ToObject()},
}
for _, cas := range cases {
if err := runInvokeTestCase(fun, &cas); err != "" {
t.Error(err)
}
}
}
func TestGetAttr(t *testing.T) {
getAttr := newBuiltinFunction("TestGetAttr", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
expectedTypes := []*Type{ObjectType, StrType, ObjectType}
argc := len(args)
if argc == 2 {
expectedTypes = expectedTypes[:2]
}
if raised := checkFunctionArgs(f, "TestGetAttr", args, expectedTypes...); raised != nil {
return nil, raised
}
var def *Object
if argc > 2 {
def = args[2]
}
s, raised := ToStr(f, args[1])
if raised != nil {
return nil, raised
}
return GetAttr(f, args[0], s, def)
}).ToObject()
fooResult := newObject(ObjectType)
fooType := newTestClass("Foo", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__getattribute__": newBuiltinFunction("__getattribute__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return fooResult, nil
}).ToObject(),
}))
barType := newTestClass("Bar", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__getattribute__": newBuiltinFunction("__getattribute__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return nil, f.RaiseType(TypeErrorType, "uh oh")
}).ToObject(),
}))
cases := []invokeTestCase{
{args: wrapArgs(newObject(fooType), "bar"), want: fooResult},
{args: wrapArgs(newObject(fooType), "baz", None), want: fooResult},
{args: wrapArgs(newObject(ObjectType), "qux", None), want: None},
{args: wrapArgs(NewTuple(), "noexist"), wantExc: mustCreateException(AttributeErrorType, "'tuple' object has no attribute 'noexist'")},
{args: wrapArgs(DictType, "noexist"), wantExc: mustCreateException(AttributeErrorType, "type object 'dict' has no attribute 'noexist'")},
{args: wrapArgs(newObject(barType), "noexist"), wantExc: mustCreateException(TypeErrorType, "uh oh")},
}
for _, cas := range cases {
if err := runInvokeTestCase(getAttr, &cas); err != "" {
t.Error(err)
}
}
}
func TestGetItem(t *testing.T) {
cases := []invokeTestCase{
{args: wrapArgs(newStringDict(map[string]*Object{"foo": None}), "foo"), want: None},
{args: wrapArgs(NewDict(), "bar"), wantExc: mustCreateException(KeyErrorType, "bar")},
{args: wrapArgs(true, "baz"), wantExc: mustCreateException(TypeErrorType, "'bool' object has no attribute '__getitem__'")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(GetItem), &cas); err != "" {
t.Error(err)
}
}
}
func TestHash(t *testing.T) {
badHash := newTestClass("badHash", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__hash__": newBuiltinFunction("__hash__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return args[0], nil
}).ToObject(),
}))
o := newObject(ObjectType)
cases := []invokeTestCase{
{args: wrapArgs("foo"), want: hashFoo},
{args: wrapArgs(123), want: NewInt(123).ToObject()},
{args: wrapArgs(o), want: NewInt(int(uintptr(o.toPointer()))).ToObject()},
{args: wrapArgs(NewList()), wantExc: mustCreateException(TypeErrorType, "unhashable type: 'list'")},
{args: wrapArgs(NewDict()), wantExc: mustCreateException(TypeErrorType, "unhashable type: 'dict'")},
{args: wrapArgs(newObject(badHash)), wantExc: mustCreateException(TypeErrorType, "an integer is required")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Hash), &cas); err != "" {
t.Error(err)
}
}
}
func TestHex(t *testing.T) {
badHex := newTestClass("badHex", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__hex__": newBuiltinFunction("__hex__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewInt(123).ToObject(), nil
}).ToObject(),
}))
goodHex := newTestClass("goodHex", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__hex__": newBuiltinFunction("__hex__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) {
return NewStr("0x123").ToObject(), nil
}).ToObject(),
}))
cases := []invokeTestCase{
{args: wrapArgs(-123), want: NewStr("-0x7b").ToObject()},
{args: wrapArgs(123), want: NewStr("0x7b").ToObject()},
{args: wrapArgs(newObject(goodHex)), want: NewStr("0x123").ToObject()},
{args: wrapArgs(NewList()), wantExc: mustCreateException(TypeErrorType, "hex() argument can't be converted to hex")},
{args: wrapArgs(NewDict()), wantExc: mustCreateException(TypeErrorType, "hex() argument can't be converted to hex")},
{args: wrapArgs(newObject(badHex)), wantExc: mustCreateException(TypeErrorType, "__hex__ returned non-string (type int)")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Hex), &cas); err != "" {
t.Error(err)
}
}
}
func TestIndex(t *testing.T) {
goodType := newTestClass("GoodIndex", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__index__": newBuiltinFunction("__index__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) {
return NewInt(123).ToObject(), nil
}).ToObject(),
}))
longType := newTestClass("LongIndex", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__index__": newBuiltinFunction("__index__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) {
return NewLong(big.NewInt(123)).ToObject(), nil
}).ToObject(),
}))
raiseType := newTestClass("RaiseIndex", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__index__": newBuiltinFunction("__index__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) {
return nil, f.RaiseType(RuntimeErrorType, "uh oh")
}).ToObject(),
}))
badType := newTestClass("BadIndex", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__index__": newBuiltinFunction("__index__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) {
return NewFloat(3.14).ToObject(), nil
}).ToObject(),
}))
cases := []invokeTestCase{
{args: wrapArgs(42), want: NewInt(42).ToObject()},
{args: wrapArgs(newObject(goodType)), want: NewInt(123).ToObject()},
{args: wrapArgs(newObject(longType)), want: NewLong(big.NewInt(123)).ToObject()},
{args: wrapArgs(newObject(raiseType)), wantExc: mustCreateException(RuntimeErrorType, "uh oh")},
{args: wrapArgs(newObject(badType)), wantExc: mustCreateException(TypeErrorType, "__index__ returned non-(int,long) (type float)")},
{args: wrapArgs("abc"), want: None},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Index), &cas); err != "" {
t.Error(err)
}
}
cases = []invokeTestCase{
{args: wrapArgs(42), want: NewInt(42).ToObject()},
{args: wrapArgs(newObject(goodType)), want: NewInt(123).ToObject()},
{args: wrapArgs(newObject(raiseType)), wantExc: mustCreateException(RuntimeErrorType, "uh oh")},
}
for _, cas := range cases {
if err := runInvokeMethodTestCase(cas.args[0].typ, "__index__", &cas); err != "" {
t.Error(err)
}
}
}
func TestInvert(t *testing.T) {
cases := []invokeTestCase{
{args: wrapArgs(42), want: NewInt(-43).ToObject()},
{args: wrapArgs(0), want: NewInt(-1).ToObject()},
{args: wrapArgs(-35935), want: NewInt(35934).ToObject()},
{args: wrapArgs("foo"), wantExc: mustCreateException(TypeErrorType, "bad operand type for unary ~: 'str'")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Invert), &cas); err != "" {
t.Error(err)
}
}
}
func TestIsInstanceIsSubclass(t *testing.T) {
fooType := newTestClass("Foo", []*Type{ObjectType}, NewDict())
barType := newTestClass("Bar", []*Type{fooType, IntType}, NewDict())
cases := []struct {
o *Object
classinfo *Object
want *Object
wantExc *BaseException
}{
{newObject(ObjectType), ObjectType.ToObject(), True.ToObject(), nil},
{NewInt(42).ToObject(), StrType.ToObject(), False.ToObject(), nil},
{None, NewTuple(NoneType.ToObject(), IntType.ToObject()).ToObject(), True.ToObject(), nil},
{NewStr("foo").ToObject(), NewTuple(NoneType.ToObject(), IntType.ToObject()).ToObject(), False.ToObject(), nil},
{NewStr("foo").ToObject(), NewTuple(IntType.ToObject(), NoneType.ToObject()).ToObject(), False.ToObject(), nil},
{None, NewTuple().ToObject(), False.ToObject(), nil},
{newObject(barType), fooType.ToObject(), True.ToObject(), nil},
{newObject(barType), IntType.ToObject(), True.ToObject(), nil},
{newObject(fooType), IntType.ToObject(), False.ToObject(), nil},
{newObject(ObjectType), None, nil, mustCreateException(TypeErrorType, "classinfo must be a type or tuple of types")},
{newObject(ObjectType), NewTuple(None).ToObject(), nil, mustCreateException(TypeErrorType, "classinfo must be a type or tuple of types")},
}
for _, cas := range cases {
// IsInstance
testCase := invokeTestCase{args: wrapArgs(cas.o, cas.classinfo), want: cas.want, wantExc: cas.wantExc}
if err := runInvokeTestCase(wrapFuncForTest(IsInstance), &testCase); err != "" {
t.Error(err)
}
// IsSubclass
testCase.args = wrapArgs(cas.o.Type(), cas.classinfo)
if err := runInvokeTestCase(wrapFuncForTest(IsSubclass), &testCase); err != "" {
t.Error(err)
}
}
// Test that IsSubclass raises when first arg is not a type.
testCase := invokeTestCase{args: wrapArgs(None, NoneType), wantExc: mustCreateException(TypeErrorType, "issubclass() arg 1 must be a class")}
if err := runInvokeTestCase(wrapFuncForTest(IsSubclass), &testCase); err != "" {
t.Error(err)
}
}
func TestIsTrue(t *testing.T) {
badNonZeroType := newTestClass("BadNonZeroType", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__nonzero__": newBuiltinFunction("__nonzero__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return None, nil
}).ToObject(),
}))
badLenType := newTestClass("BadLen", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__len__": newBuiltinFunction("__len__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return None, nil
}).ToObject(),
}))
cases := []invokeTestCase{
// Bool
{args: wrapArgs(true), want: True.ToObject()},
{args: wrapArgs(false), want: False.ToObject()},
// Dict
{args: wrapArgs(NewDict()), want: False.ToObject()},
{args: wrapArgs(newStringDict(map[string]*Object{"foo": True.ToObject()})), want: True.ToObject()},
// Int
{args: wrapArgs(0), want: False.ToObject()},
{args: wrapArgs(-1020), want: True.ToObject()},
{args: wrapArgs(1698391283), want: True.ToObject()},
// None
{args: wrapArgs(None), want: False.ToObject()},
// Object
{args: wrapArgs(newObject(ObjectType)), want: True.ToObject()},
// Str
{args: wrapArgs(""), want: False.ToObject()},
{args: wrapArgs("\x00"), want: True.ToObject()},
{args: wrapArgs("foo"), want: True.ToObject()},
// Tuple
{args: wrapArgs(NewTuple()), want: False.ToObject()},
{args: wrapArgs(newTestTuple("foo", None)), want: True.ToObject()},
// Funky types
{args: wrapArgs(newObject(badNonZeroType)), wantExc: mustCreateException(TypeErrorType, "__nonzero__ should return bool, returned NoneType")},
{args: wrapArgs(newObject(badLenType)), wantExc: mustCreateException(TypeErrorType, "an integer is required")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(IsTrue), &cas); err != "" {
t.Error(err)
}
}
}
func TestIter(t *testing.T) {
fun := newBuiltinFunction("TestIter", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if argc := len(args); argc != 1 {
return nil, f.RaiseType(SystemErrorType, fmt.Sprintf("Iter expected 1 arg, got %d", argc))
}
i, raised := Iter(f, args[0])
if raised != nil {
return nil, raised
}
return Next(f, i)
}).ToObject()
cases := []invokeTestCase{
{args: wrapArgs(NewTuple()), wantExc: mustCreateException(StopIterationType, "")},
{args: wrapArgs(newTestTuple(42, "foo")), want: NewInt(42).ToObject()},
{args: wrapArgs(newTestList("foo")), want: NewStr("foo").ToObject()},
{args: wrapArgs("foo"), want: NewStr("f").ToObject()},
{args: wrapArgs(123), wantExc: mustCreateException(TypeErrorType, "'int' object is not iterable")},
}
for _, cas := range cases {
if err := runInvokeTestCase(fun, &cas); err != "" {
t.Error(err)
}
}
}
func TestNeg(t *testing.T) {
cases := []invokeTestCase{
{args: wrapArgs(42), want: NewInt(-42).ToObject()},
{args: wrapArgs(1.2), want: NewFloat(-1.2).ToObject()},
{args: wrapArgs(NewLong(big.NewInt(123))), want: NewLong(big.NewInt(-123)).ToObject()},
{args: wrapArgs("foo"), wantExc: mustCreateException(TypeErrorType, "bad operand type for unary -: 'str'")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Neg), &cas); err != "" {
t.Error(err)
}
}
}
func TestNext(t *testing.T) {
fun := newBuiltinFunction("TestNext", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if argc := len(args); argc != 1 {
return nil, f.RaiseType(SystemErrorType, fmt.Sprintf("Next expected 1 arg, got %d", argc))
}
iter := args[0]
var elems []*Object
elem, raised := Next(f, iter)
for ; raised == nil; elem, raised = Next(f, iter) {
elems = append(elems, elem)
}
if !raised.isInstance(StopIterationType) {
return nil, raised
}
f.RestoreExc(nil, nil)
return NewTuple(elems...).ToObject(), nil
}).ToObject()
testElems := []*Object{NewInt(42).ToObject(), NewStr("foo").ToObject(), newObject(ObjectType)}
cases := []invokeTestCase{
{args: wrapArgs(mustNotRaise(Iter(NewRootFrame(), NewTuple().ToObject()))), want: NewTuple().ToObject()},
{args: wrapArgs(mustNotRaise(Iter(NewRootFrame(), NewTuple(testElems...).ToObject()))), want: NewTuple(testElems...).ToObject()},
{args: wrapArgs(mustNotRaise(Iter(NewRootFrame(), NewList(testElems...).ToObject()))), want: NewTuple(testElems...).ToObject()},
{args: wrapArgs(123), wantExc: mustCreateException(TypeErrorType, "int object is not an iterator")},
}
for _, cas := range cases {
if err := runInvokeTestCase(fun, &cas); err != "" {
t.Error(err)
}
}
}
func TestLen(t *testing.T) {
badLenType := newTestClass("BadLen", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__len__": newBuiltinFunction("__len__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return None, nil
}).ToObject(),
}))
cases := []invokeTestCase{
{args: wrapArgs(NewDict()), want: NewInt(0).ToObject()},
{args: wrapArgs(newStringDict(map[string]*Object{"foo": NewStr("foo value").ToObject(), "bar": NewStr("bar value").ToObject()})), want: NewInt(2).ToObject()},
{args: wrapArgs(NewTuple()), want: NewInt(0).ToObject()},
{args: wrapArgs(NewTuple(None, None, None)), want: NewInt(3).ToObject()},
{args: wrapArgs(10), wantExc: mustCreateException(TypeErrorType, "object of type 'int' has no len()")},
{args: wrapArgs(newObject(badLenType)), wantExc: mustCreateException(TypeErrorType, "an integer is required")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Len), &cas); err != "" {
t.Error(err)
}
}
}
func TestLenRaise(t *testing.T) {
testTypes := []*Type{
DictType,
TupleType,
}
for _, typ := range testTypes {
cases := []invokeTestCase{
{args: wrapArgs(), wantExc: mustCreateException(TypeErrorType, fmt.Sprintf("unbound method __len__() must be called with %s instance as first argument (got nothing instead)", typ.Name()))},
{args: wrapArgs(newObject(ObjectType)), wantExc: mustCreateException(TypeErrorType, fmt.Sprintf("unbound method __len__() must be called with %s instance as first argument (got object instance instead)", typ.Name()))},
{args: wrapArgs(newObject(ObjectType), newObject(ObjectType)), wantExc: mustCreateException(TypeErrorType, fmt.Sprintf("unbound method __len__() must be called with %s instance as first argument (got object instance instead)", typ.Name()))},
}
for _, cas := range cases {
if err := runInvokeMethodTestCase(typ, "__len__", &cas); err != "" {
t.Error(err)
}
}
}
}
func TestInvokePositionalArgs(t *testing.T) {
fun := newBuiltinFunction("TestInvokePositionalArgs", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
return NewTuple(args.makeCopy()...).ToObject(), nil
}).ToObject()
cases := []struct {
varargs *Object
args Args
want *Object
}{
{nil, nil, NewTuple().ToObject()},
{NewTuple(NewInt(2).ToObject()).ToObject(), nil, NewTuple(NewInt(2).ToObject()).ToObject()},
{nil, []*Object{NewStr("foo").ToObject()}, NewTuple(NewStr("foo").ToObject()).ToObject()},
{NewTuple(NewFloat(3.14).ToObject()).ToObject(), []*Object{NewStr("foo").ToObject()}, NewTuple(NewStr("foo").ToObject(), NewFloat(3.14).ToObject()).ToObject()},
{NewList(NewFloat(3.14).ToObject()).ToObject(), []*Object{NewStr("foo").ToObject()}, NewTuple(NewStr("foo").ToObject(), NewFloat(3.14).ToObject()).ToObject()},
}
for _, cas := range cases {
got, raised := Invoke(NewRootFrame(), fun, cas.args, cas.varargs, nil, nil)
switch checkResult(got, cas.want, raised, nil) {
case checkInvokeResultExceptionMismatch:
t.Errorf("PackArgs(%v, %v) raised %v, want nil", cas.args, cas.varargs, raised)
case checkInvokeResultReturnValueMismatch:
t.Errorf("PackArgs(%v, %v) = %v, want %v", cas.args, cas.varargs, got, cas.want)
}
}
}
func TestInvokeKeywordArgs(t *testing.T) {
fun := newBuiltinFunction("TestInvokeKeywordArgs", func(f *Frame, _ Args, kwargs KWArgs) (*Object, *BaseException) {
got := map[string]*Object{}
for _, kw := range kwargs {
got[kw.Name] = kw.Value
}
return newStringDict(got).ToObject(), nil
}).ToObject()
d := NewDict()
d.SetItem(NewRootFrame(), NewInt(123).ToObject(), None)
cases := []struct {
keywords KWArgs
kwargs *Object
want *Object
wantExc *BaseException
}{
{nil, nil, NewDict().ToObject(), nil},
{wrapKWArgs("foo", 42), nil, newTestDict("foo", 42).ToObject(), nil},
{nil, newTestDict("foo", None).ToObject(), newTestDict("foo", None).ToObject(), nil},
{wrapKWArgs("foo", 42), newTestDict("bar", None).ToObject(), newTestDict("foo", 42, "bar", None).ToObject(), nil},
{nil, NewList().ToObject(), nil, mustCreateException(TypeErrorType, "argument after ** must be a dict, not list")},
{nil, d.ToObject(), nil, mustCreateException(TypeErrorType, "keywords must be strings")},
}
for _, cas := range cases {
got, raised := Invoke(NewRootFrame(), fun, nil, nil, cas.keywords, cas.kwargs)
switch checkResult(got, cas.want, raised, cas.wantExc) {
case checkInvokeResultExceptionMismatch:
t.Errorf("PackKwargs(%v, %v) raised %v, want %v", cas.keywords, cas.kwargs, raised, cas.wantExc)
case checkInvokeResultReturnValueMismatch:
t.Errorf("PackKwargs(%v, %v) = %v, want %v", cas.keywords, cas.kwargs, got, cas.want)
}
}
}
func TestOct(t *testing.T) {
badOct := newTestClass("badOct", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__oct__": newBuiltinFunction("__oct__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewInt(123).ToObject(), nil
}).ToObject(),
}))
goodOct := newTestClass("goodOct", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__oct__": newBuiltinFunction("__oct__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) {
return NewStr("0123").ToObject(), nil
}).ToObject(),
}))
cases := []invokeTestCase{
{args: wrapArgs(-123), want: NewStr("-0173").ToObject()},
{args: wrapArgs(123), want: NewStr("0173").ToObject()},
{args: wrapArgs(newObject(goodOct)), want: NewStr("0123").ToObject()},
{args: wrapArgs(NewList()), wantExc: mustCreateException(TypeErrorType, "oct() argument can't be converted to oct")},
{args: wrapArgs(NewDict()), wantExc: mustCreateException(TypeErrorType, "oct() argument can't be converted to oct")},
{args: wrapArgs(newObject(badOct)), wantExc: mustCreateException(TypeErrorType, "__oct__ returned non-string (type int)")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Oct), &cas); err != "" {
t.Error(err)
}
}
}
func TestPos(t *testing.T) {
pos := newTestClass("pos", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__pos__": newBuiltinFunction("__pos__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) {
return NewInt(-42).ToObject(), nil
}).ToObject(),
}))
cases := []invokeTestCase{
{args: wrapArgs(42), want: NewInt(42).ToObject()},
{args: wrapArgs(1.2), want: NewFloat(1.2).ToObject()},
{args: wrapArgs(NewLong(big.NewInt(123))), want: NewLong(big.NewInt(123)).ToObject()},
{args: wrapArgs(newObject(pos)), want: NewInt(-42).ToObject()},
{args: wrapArgs("foo"), wantExc: mustCreateException(TypeErrorType, "bad operand type for unary +: 'str'")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(Pos), &cas); err != "" {
t.Error(err)
}
}
}
func TestPyPrint(t *testing.T) {
fun := wrapFuncForTest(func(f *Frame, args *Tuple, sep, end string) (string, *BaseException) {
return captureStdout(f, func() *BaseException {
return pyPrint(NewRootFrame(), args.elems, sep, end, Stdout)
})
})
cases := []invokeTestCase{
{args: wrapArgs(NewTuple(), "", "\n"), want: NewStr("\n").ToObject()},
{args: wrapArgs(NewTuple(), "", ""), want: NewStr("").ToObject()},
{args: wrapArgs(newTestTuple("abc", 123), " ", "\n"), want: NewStr("abc 123\n").ToObject()},
{args: wrapArgs(newTestTuple("foo"), "", " "), want: NewStr("foo ").ToObject()},
}
for _, cas := range cases {
if err := runInvokeTestCase(fun, &cas); err != "" {
t.Error(err)
}
}
}
// TODO(corona10): Re-enable once #282 is addressed.
/*func TestPrint(t *testing.T) {
fun := wrapFuncForTest(func(f *Frame, args *Tuple, nl bool) (string, *BaseException) {
return captureStdout(f, func() *BaseException {
return Print(NewRootFrame(), args.elems, nl)
})
})
cases := []invokeTestCase{
{args: wrapArgs(NewTuple(), true), want: NewStr("\n").ToObject()},
{args: wrapArgs(NewTuple(), false), want: NewStr("").ToObject()},
{args: wrapArgs(newTestTuple("abc", 123), true), want: NewStr("abc 123\n").ToObject()},
{args: wrapArgs(newTestTuple("foo"), false), want: NewStr("foo ").ToObject()},
}
for _, cas := range cases {
if err := runInvokeTestCase(fun, &cas); err != "" {
t.Error(err)
}
}
}*/
func TestReprRaise(t *testing.T) {
testTypes := []*Type{
BaseExceptionType,
BoolType,
DictType,
IntType,
FunctionType,
StrType,
TupleType,
TypeType,
}
for _, typ := range testTypes {
cases := []invokeTestCase{
{args: wrapArgs(), wantExc: mustCreateException(TypeErrorType, fmt.Sprintf("unbound method __repr__() must be called with %s instance as first argument (got nothing instead)", typ.Name()))},
{args: wrapArgs(newObject(ObjectType)), wantExc: mustCreateException(TypeErrorType, fmt.Sprintf("unbound method __repr__() must be called with %s instance as first argument (got object instance instead)", typ.Name()))},
}
for _, cas := range cases {
if err := runInvokeMethodTestCase(typ, "__repr__", &cas); err != "" {
t.Error(err)
}
}
}
}
func TestReprMethodReturnsNonStr(t *testing.T) {
// Don't use runInvokeTestCase since it takes repr(args) and in this
// case repr will raise.
typ := newTestClass("Foo", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__repr__": newBuiltinFunction("__repr__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return None, nil
}).ToObject(),
}))
_, raised := Repr(NewRootFrame(), newObject(typ))
wantExc := mustCreateException(TypeErrorType, "__repr__ returned non-string (type NoneType)")
if !exceptionsAreEquivalent(raised, wantExc) {
t.Errorf(`Repr() raised %v, want %v`, raised, wantExc)
}
}
func TestResolveClass(t *testing.T) {
f := NewRootFrame()
cases := []struct {
class *Dict
local *Object
globals *Dict
name string
want *Object
wantExc *BaseException
}{
{newStringDict(map[string]*Object{"foo": NewStr("bar").ToObject()}), NewStr("baz").ToObject(), NewDict(), "foo", NewStr("bar").ToObject(), nil},
{newStringDict(map[string]*Object{"str": NewInt(42).ToObject()}), nil, NewDict(), "str", NewInt(42).ToObject(), nil},
{NewDict(), nil, newStringDict(map[string]*Object{"foo": NewStr("bar").ToObject()}), "foo", NewStr("bar").ToObject(), nil},
{NewDict(), nil, NewDict(), "str", StrType.ToObject(), nil},
{NewDict(), nil, NewDict(), "foo", nil, mustCreateException(NameErrorType, "name 'foo' is not defined")},
}
for _, cas := range cases {
f.globals = cas.globals
got, raised := ResolveClass(f, cas.class, cas.local, NewStr(cas.name))
switch checkResult(got, cas.want, raised, cas.wantExc) {
case checkInvokeResultExceptionMismatch:
t.Errorf("ResolveClass(%v, %q) raised %v, want %v", cas.globals, cas.name, raised, cas.wantExc)
case checkInvokeResultReturnValueMismatch:
t.Errorf("ResolveClass(%v, %q) = %v, want %v", cas.globals, cas.name, got, cas.want)
}
}
}
func TestResolveGlobal(t *testing.T) {
fun := wrapFuncForTest(func(f *Frame, globals *Dict, name *Str) (*Object, *BaseException) {
f.globals = globals
return ResolveGlobal(f, name)
})
cases := []invokeTestCase{
{args: wrapArgs(newStringDict(map[string]*Object{"foo": NewStr("bar").ToObject()}), "foo"), want: NewStr("bar").ToObject()},
{args: wrapArgs(NewDict(), "str"), want: StrType.ToObject()},
{args: wrapArgs(NewDict(), "foo"), wantExc: mustCreateException(NameErrorType, "name 'foo' is not defined")},
}
for _, cas := range cases {
if err := runInvokeTestCase(fun, &cas); err != "" {
t.Error(err)
}
}
}
func TestRichCompare(t *testing.T) {
badCmpType := newTestClass("BadCmp", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__cmp__": newBuiltinFunction("__cmp__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return nil, f.RaiseType(TypeErrorType, "uh oh")
}).ToObject(),
}))
cmpEqType := newTestClass("BadCmp", []*Type{ObjectType}, newStringDict(map[string]*Object{
"__cmp__": newBuiltinFunction("__cmp__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NewInt(0).ToObject(), nil
}).ToObject(),
}))
cmpByEqType := newTestClass("Eq", []*Type{IntType}, newStringDict(map[string]*Object{
"__eq__": newBuiltinFunction("__eq__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return True.ToObject(), nil
}).ToObject(),
"__cmp__": newBuiltinFunction("__cmp__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return NotImplemented, nil
}).ToObject(),
}))
badCmpEqType := newTestClass("Eq", []*Type{IntType}, newStringDict(map[string]*Object{
"__eq__": newBuiltinFunction("__eq__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
return nil, f.RaiseType(TypeErrorType, "uh oh")
}).ToObject(),
}))
cases := []invokeTestCase{
// Test `__eq__` fallback to `__cmp__`.
{args: wrapArgs(newObject(cmpEqType), newObject(cmpEqType)), want: compareAllResultEq},
// Test `__cmp__` fallback to `__eq__`.
{args: wrapArgs(newObject(cmpByEqType), newObject(cmpByEqType)), want: compareAllResultEq},
// Test rich compare fallback to bad `__cmp__`.
{args: wrapArgs(newObject(badCmpType), newObject(badCmpType)), wantExc: mustCreateException(TypeErrorType, "uh oh")},
// Test bad `__eq__` where the second object being compared is a subclass of the first.
{args: wrapArgs(NewInt(13).ToObject(), newObject(badCmpEqType)), wantExc: mustCreateException(TypeErrorType, "uh oh")},
}
for _, cas := range cases {
if err := runInvokeTestCase(compareAll, &cas); err != "" {
t.Error(err)
}
}
}
func TestCheckLocal(t *testing.T) {
o := newObject(ObjectType)
cases := []invokeTestCase{
{args: wrapArgs(o, "foo"), want: None},
{args: wrapArgs(UnboundLocal, "bar"), wantExc: mustCreateException(UnboundLocalErrorType, "local variable 'bar' referenced before assignment")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(CheckLocal), &cas); err != "" {
t.Error(err)
}
}
}
func TestSetItem(t *testing.T) {
setItem := newBuiltinFunction("TestSetItem", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkFunctionArgs(f, "TestSetItem", args, ObjectType, ObjectType, ObjectType); raised != nil {
return nil, raised
}
o := args[0]
if raised := SetItem(f, o, args[1], args[2]); raised != nil {
return nil, raised
}
return o, nil
}).ToObject()
cases := []invokeTestCase{
{args: wrapArgs(NewDict(), "bar", None), want: newTestDict("bar", None).ToObject()},
{args: wrapArgs(123, "bar", None), wantExc: mustCreateException(TypeErrorType, "'int' object has no attribute '__setitem__'")},
}
for _, cas := range cases {
if err := runInvokeTestCase(setItem, &cas); err != "" {
t.Error(err)
}
}
}
func TestStartThread(t *testing.T) {
c := make(chan bool)
callable := newBuiltinFunction("TestStartThread", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
close(c)
return None, nil
}).ToObject()
StartThread(callable)
// Deadlock indicates the thread didn't start.
<-c
}
func TestStartThreadRaises(t *testing.T) {
// Since there's no way to notify that the goroutine has returned we
// can't actually test the exception output but we can at least make
// sure the callable ran and didn't blow up the rest of the program.
c := make(chan bool)
callable := newBuiltinFunction("TestStartThreadRaises", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
defer close(c)
return nil, f.RaiseType(ExceptionType, "foo")
}).ToObject()
StartThread(callable)
<-c
}
func TestTie(t *testing.T) {
targets := make([]*Object, 3)
cases := []struct {
t TieTarget
o *Object
want *Object
wantExc *BaseException
}{
{TieTarget{Target: &targets[0]}, NewInt(42).ToObject(), NewTuple(NewInt(42).ToObject()).ToObject(), nil},
{TieTarget{Target: &targets[0]}, NewTuple().ToObject(), NewTuple(NewTuple().ToObject()).ToObject(), nil},
{
TieTarget{
Children: []TieTarget{{Target: &targets[0]}, {Target: &targets[1]}},
},
NewList(NewStr("foo").ToObject(), NewStr("bar").ToObject()).ToObject(),
NewTuple(NewStr("foo").ToObject(), NewStr("bar").ToObject()).ToObject(),
nil,
},
{
TieTarget{
Children: []TieTarget{
{Target: &targets[0]},
{Children: []TieTarget{{Target: &targets[1]}, {Target: &targets[2]}}},
},
},
NewTuple(NewStr("foo").ToObject(), NewTuple(NewStr("bar").ToObject(), NewStr("baz").ToObject()).ToObject()).ToObject(),
NewTuple(NewStr("foo").ToObject(), NewStr("bar").ToObject(), NewStr("baz").ToObject()).ToObject(),
nil,
},
{
TieTarget{
Children: []TieTarget{
{Target: &targets[0]},
{Target: &targets[1]},
},
},
NewList(NewStr("foo").ToObject()).ToObject(),
nil,
mustCreateException(ValueErrorType, "need more than 1 values to unpack"),
},
{
TieTarget{Children: []TieTarget{{Target: &targets[0]}}},
NewTuple(NewInt(1).ToObject(), NewInt(2).ToObject()).ToObject(),
nil,
mustCreateException(ValueErrorType, "too many values to unpack"),
},
}
for _, cas := range cases {
for i := range targets {
targets[i] = nil
}
var got *Object
raised := Tie(NewRootFrame(), cas.t, cas.o)
if raised == nil {
var elems []*Object
for _, t := range targets {
if t == nil {
break
}
elems = append(elems, t)
}
got = NewTuple(elems...).ToObject()
}
switch checkResult(got, cas.want, raised, cas.wantExc) {
case checkInvokeResultExceptionMismatch:
t.Errorf("Tie(%+v, %v) raised %v, want %v", cas.t, cas.o, raised, cas.wantExc)
case checkInvokeResultReturnValueMismatch:
t.Errorf("Tie(%+v, %v) = %v, want %v", cas.t, cas.o, got, cas.want)
}
}
}
func TestToInt(t *testing.T) {
fun := wrapFuncForTest(func(f *Frame, o *Object) (*Tuple, *BaseException) {
i, raised := ToInt(f, o)
if raised != nil {
return nil, raised
}
return newTestTuple(i, i.Type()), nil
})
cases := []invokeTestCase{
{args: wrapArgs(42), want: newTestTuple(42, IntType).ToObject()},
{args: wrapArgs(big.NewInt(123)), want: newTestTuple(123, LongType).ToObject()},
}
for _, cas := range cases {
if err := runInvokeTestCase(fun, &cas); err != "" {
t.Error(err)
}
}
}
func TestToIntValue(t *testing.T) {
cases := []invokeTestCase{
{args: wrapArgs(42), want: NewInt(42).ToObject()},
{args: wrapArgs(big.NewInt(123)), want: NewInt(123).ToObject()},
{args: wrapArgs(overflowLong), wantExc: mustCreateException(OverflowErrorType, "Python int too large to convert to a Go int")},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(ToIntValue), &cas); err != "" {
t.Error(err)
}
}
}
func TestToNative(t *testing.T) {
foo := newObject(ObjectType)
cases := []struct {
o *Object
want interface{}
wantExc *BaseException
}{
{True.ToObject(), true, nil},
{NewInt(42).ToObject(), 42, nil},
{NewStr("bar").ToObject(), "bar", nil},
{foo, foo, nil},
}
for _, cas := range cases {
got, raised := ToNative(NewRootFrame(), cas.o)
if !exceptionsAreEquivalent(raised, cas.wantExc) {
t.Errorf("ToNative(%v) raised %v, want %v", cas.o, raised, cas.wantExc)
} else if raised == nil && (!got.IsValid() || !reflect.DeepEqual(got.Interface(), cas.want)) {
t.Errorf("ToNative(%v) = %v, want %v", cas.o, got, cas.want)
}
}
}
func BenchmarkGetAttr(b *testing.B) {
f := NewRootFrame()
attr := NewStr("bar")
fooType := newTestClass("Foo", []*Type{ObjectType}, NewDict())
foo := newObject(fooType)
if raised := SetAttr(f, foo, attr, NewInt(123).ToObject()); raised != nil {
panic(raised)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
mustNotRaise(GetAttr(f, foo, attr, nil))
}
}
// SetAttr is tested in TestObjectSetAttr.
func exceptionsAreEquivalent(e1 *BaseException, e2 *BaseException) bool {
if e1 == nil && e2 == nil {
return true
}
if e1 == nil || e2 == nil {
return false
}
if e1.typ != e2.typ {
return false
}
if e1.args == nil && e2.args == nil {
return true
}
if e1.args == nil || e2.args == nil {
return false
}
f := NewRootFrame()
b, raised := IsTrue(f, mustNotRaise(Eq(f, e1.args.ToObject(), e2.args.ToObject())))
if raised != nil {
panic(raised)
}
return b
}
func getFuncName(f interface{}) string {
s := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
return regexp.MustCompile(`\w+$`).FindString(s)
}
// wrapFuncForTest creates a callable object that invokes fun, passing the
// current frame as its first argument followed by caller provided args.
func wrapFuncForTest(fun interface{}) *Object {
return newBuiltinFunction(getFuncName(fun), func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
callable, raised := WrapNative(f, reflect.ValueOf(fun))
if raised != nil {
return nil, raised
}
argc := len(args)
nativeArgs := make(Args, argc+1, argc+1)
nativeArgs[0] = f.ToObject()
copy(nativeArgs[1:], args)
return callable.Call(f, nativeArgs, nil)
}).ToObject()
}
func mustCreateException(t *Type, msg string) *BaseException {
if !t.isSubclass(BaseExceptionType) {
panic(fmt.Sprintf("type does not inherit from BaseException: %s", t.Name()))
}
e := toBaseExceptionUnsafe(newObject(t))
if msg == "" {
e.args = NewTuple()
} else {
e.args = NewTuple(NewStr(msg).ToObject())
}
return e
}
func mustNotRaise(o *Object, raised *BaseException) *Object {
if raised != nil {
panic(raised)
}
return o
}
var (
compareAll = wrapFuncForTest(func(f *Frame, v, w *Object) (*Object, *BaseException) {
lt, raised := LT(f, v, w)
if raised != nil {
return nil, raised
}
le, raised := LE(f, v, w)
if raised != nil {
return nil, raised
}
eq, raised := Eq(f, v, w)
if raised != nil {
return nil, raised
}
ne, raised := NE(f, v, w)
if raised != nil {
return nil, raised
}
ge, raised := GE(f, v, w)
if raised != nil {
return nil, raised
}
gt, raised := GT(f, v, w)
if raised != nil {
return nil, raised
}
return NewTuple(lt, le, eq, ne, ge, gt).ToObject(), nil
})
compareAllResultLT = newTestTuple(true, true, false, true, false, false).ToObject()
compareAllResultEq = newTestTuple(false, true, true, false, true, false).ToObject()
compareAllResultGT = newTestTuple(false, false, false, true, true, true).ToObject()
)
|
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Blue Oak Model License
// that can be found in the LICENSE file.
package cache
import (
"context"
docker "github.com/docker/docker/client"
)
// Wrap returns a wrapped copy of the Docker client that
// collects details about image use and sorts the disk usage
// report based on the image last used date, ascending.
func Wrap(ctx context.Context, api docker.APIClient) docker.APIClient {
c := newCache(DefaultCacheSize)
l := &listener{
client: api,
cache: c,
}
go l.listen(ctx) // nolint: errcheck
return &client{
APIClient: api,
cache: c,
}
}
|
package main
import (
"os"
"fmt"
"bufio"
//"sort"
)
func main() {
reader := bufio.NewReader(os.Stdin)
var n int
fmt.Fscan(reader, &n)
a := make([]int, n)
ps := make([]int, n)
for i:=0; i<n; i++ {
fmt.Fscan(reader, &a[i])
}
for i:=0; i<n; i++ {
var sum120, bt120 int
var sum50, bt50 int
for j:=i-1; j>=0; j-- {
if a[i] - a[j] >= 1440 {
break
}
if a[i] - a[j] < 1440 {
sum120 += ps[j]
bt120 = a[j]
}
if a[i] - a[j] < 90 {
sum50 += ps[j]
bt50 = a[j]
}
}
// j50 := sort.Search(i-1, fun(j0 int) bool {
// return a[j0] > a[i] - 90
// })
// j120 := sort.Search(i-1, fun(j0 int) bool {
// return a[j0] > a[i] - 1440
// })
// if j50 != i {
// sum50 +=
// }
//fmt.Println(a[i], bt120, sum120, bt50, sum50)
if (a[i] - bt50 < 90 && sum50 >= 50) ||
(a[i] - bt120 < 1440 && sum120 >= 120) {
fmt.Println(0)
} else {
v1 := 120 - sum120
v2 := 50 - sum50
v3 := 20
ps[i] = min(min(v1,v2), v3)
fmt.Println(ps[i])
}
}
}
func min(a int, b int) int {
if a > b {
return b
} else {
return a
}
}
|
package superhero
import (
"context"
"github.com/go-kit/kit/log"
"github.com/jace-ys/go-library/postgres"
pb "github.com/jace-ys/super-smash-heroes/services/superhero/api/superhero"
)
type Server interface {
Init(ctx context.Context, server pb.SuperheroServiceServer) error
Serve() error
Shutdown(ctx context.Context) error
}
type SuperheroService struct {
pb.UnimplementedSuperheroServiceServer
logger log.Logger
database *postgres.Client
registry SuperheroRegistry
}
func NewService(logger log.Logger, postgres *postgres.Client, registry SuperheroRegistry) (*SuperheroService, error) {
return &SuperheroService{
logger: logger,
database: postgres,
registry: registry,
}, nil
}
func (s *SuperheroService) StartServer(ctx context.Context, server Server) error {
if err := server.Init(ctx, s); err != nil {
return err
}
if err := server.Serve(); err != nil {
return err
}
return nil
}
func (s *SuperheroService) Teardown() error {
if err := s.database.Close(); err != nil {
return err
}
return nil
}
|
package cleanup
import (
"github.com/devspace-cloud/devspace/cmd/flags"
"github.com/devspace-cloud/devspace/pkg/util/factory"
"github.com/spf13/cobra"
)
// NewCleanupCmd creates a new cobra command
func NewCleanupCmd(f factory.Factory, globalFlags *flags.GlobalFlags) *cobra.Command {
cleanupCmd := &cobra.Command{
Use: "cleanup",
Short: "Cleans up resources",
Long: `
#######################################################
################## devspace cleanup ###################
#######################################################
`,
Args: cobra.NoArgs,
}
cleanupCmd.AddCommand(newImagesCmd(f, globalFlags))
return cleanupCmd
}
|
package caozuoliang
import (
"sort"
"time"
)
type Data struct {
Bawu_un string
ThreadCount int
PostCount int
SameThreads map[int]*SameThread
SameAccounts map[string][]*PostLog
OldPosts OldPosts
Distribution []int //以小时为单位
Speed []int
RecoveredThreads []Recovered
RecoveredPosts []Recovered
//1m,2m,3m,4m,5m,6m,7m,8m,9m,10m,15m,20m,25m,30m,40m,50m,1h,1.5h,2h,2.5h,3h,4h,5h,6h,12h,1d,2d,3d,5d,10d,30d
/*
ChThreadCount chan int
ChPostCount chan int
ChSameThread chan orzorzorzA
ChSameAccount chan orzorzorzB
ChOldPosts chan orzorzorzC
*/
}
func NewData(hour int) *Data {
var data Data
data.Speed = make([]int, len(SpeedClass)+1)
data.Distribution = make([]int, hour)
data.SameThreads = make(map[int]*SameThread)
data.SameAccounts = make(map[string][]*PostLog)
return &data
}
/*
type orzorzorzA struct {
Tid int
Ptr *PostLog
}
type orzorzorzB struct {
Un string
Ptr *PostLog
}
type orzorzorzC struct {
Ptr *PostLog
Interval time.Duration
}
*/
type Account struct {
username string
}
type Post struct {
PostType int
Title string
Content string
Author string
}
/*
func (data *Data) AddCount(posttype int) {
log("AddCount:进入")
if posttype == 主题 {
data.ChThreadCount <- 1
} else {
data.ChPostCount <- 1
}
log("AddCount:退出")
}
func (data *Data) AddSameThread(tid int, pl *PostLog) {
data.ChSameThread <- orzorzorzA{tid, pl}
}
func (data *Data) AddSameAccount(un string, pl *PostLog) {
data.ChSameAccount <- orzorzorzB{un, pl}
}
func (data *Data) AddOldPosts(pl *PostLog, t time.Duration) {
log2("收到")
data.ChOldPosts <- orzorzorzC{pl, t}
}
*/
type SortedData struct {
Bawu_un string
ThreadCount int
PostCount int
SameThreads SameThreads
SameAccounts SameAccounts
OldPosts OldPosts
Distribution []int //以小时为单位
Speed []int
RecoveredThreads []Recovered
RecoveredPosts []Recovered
//1m,2m,3m,4m,5m,6m,7m,8m,9m,10m,15m,20m,25m,30m,40m,50m,1h,1.5h,2h,2.5h,3h,4h,5h,6h,12h,1d,2d,3d,5d,10d,30d
/*
ChThreadCount chan int
ChPostCount chan int
ChSameThread chan orzorzorzA
ChSameAccount chan orzorzorzB
ChOldPosts chan orzorzorzC
*/
}
type SameThreads []SameThread
type Recovered struct {
recovertime *time.Time
recoverby string
pl *PostLog
}
type SameThread struct {
//PostLogs []*PostLog
ThreadTitle string
Count int
ThreadIsDeletedByTheOperator bool
}
func (t SameThreads) Len() int {
return len(t)
}
func (t SameThreads) Less(i, j int) bool {
if t[i].ThreadIsDeletedByTheOperator {
if t[j].ThreadIsDeletedByTheOperator {
return t[i].Count > t[j].Count
}
return true
} else if t[j].ThreadIsDeletedByTheOperator {
return false
}
return t[i].Count > t[j].Count
}
func (t SameThreads) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
type SameAccounts [][]*PostLog
func (t SameAccounts) Len() int {
return len(t)
}
func (t SameAccounts) Less(i, j int) bool {
return len(t[i]) > len(t[j])
}
func (t SameAccounts) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
type OldPosts []*PostLog
func (t OldPosts) Len() int {
return len(t)
}
func (t OldPosts) Less(i, j int) bool {
return t[i].Duration > t[j].Duration
}
func (t OldPosts) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func SortData(data *Data) *SortedData {
var sd SortedData
sd.Bawu_un = data.Bawu_un
sd.PostCount = data.PostCount
sd.ThreadCount = data.ThreadCount
sd.Distribution = data.Distribution
sd.Speed = data.Speed
sd.OldPosts = data.OldPosts
sd.RecoveredPosts = data.RecoveredPosts
sd.RecoveredThreads = data.RecoveredThreads
for _, v := range data.SameThreads {
sd.SameThreads = append(sd.SameThreads, *v)
}
for _, v := range data.SameAccounts {
sd.SameAccounts = append(sd.SameAccounts, []*PostLog(v))
}
sort.Sort(sd.SameThreads)
sort.Sort(sd.SameAccounts)
sort.Sort(sd.OldPosts)
return &sd
}
|
package main
import (
"context"
"io"
"log"
"net/http"
"os"
"runtime/debug"
"github.com/julienschmidt/httprouter"
"github.com/justinas/alice"
)
var (
Version string
BuildTime string
)
const (
defaultLogFile = "/tmp/apiserver.log"
defaultListenPort = ":9090"
defaultMemcacheHost = "127.0.0.1:11211"
paramsCtxKey = "params"
)
func main() {
{
f, err := os.OpenFile(getOrDefault("LOG_FILE", defaultLogFile), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Println(err)
}
log.SetOutput(io.MultiWriter(f, os.Stdout))
}
lp := getOrDefault("LISTEN_PORT", defaultListenPort)
log.Printf("Starting listening in '%v' Version: %q BuildTime: %q", lp, Version, BuildTime)
err := http.ListenAndServe(lp, createRouter())
if err != nil {
log.Fatal("Error ListenAndServe: ", err)
}
}
func createRouter() http.Handler {
router := httprouter.New()
// panic recover
router.PanicHandler = func(w http.ResponseWriter, r *http.Request, val interface{}) {
log.Printf("[+] Recovering: %+v\nRequest %s %q Remote IP: %q\n", val, r.Method, r.URL, r.RemoteAddr)
debug.PrintStack()
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
// not found handler
router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Detected Not Found: Request %s %q Remote IP: %q\n", r.Method, r.URL, r.RemoteAddr)
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
})
mainChain := alice.New(loggerMW, commonMW)
// routers:
{
router.Handler(http.MethodGet, "/api/health", mainChain.ThenFunc(health))
router.Handler(http.MethodPost, "/api/game", mainChain.ThenFunc(createGame))
router.GET("/api/invitation/:gameID", wrap(mainChain.ThenFunc(invitation)))
}
return router
}
func wrap(h http.Handler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ctx := context.WithValue(r.Context(), paramsCtxKey, p)
h.ServeHTTP(w, r.WithContext(ctx))
}
}
func getOrDefault(varName, defaultVal string) string {
val := os.Getenv(varName)
if val == "" {
val = defaultVal
}
return val
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//355. Design Twitter
//Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:
//postTweet(userId, tweetId): Compose a new tweet.
//getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
//follow(followerId, followeeId): Follower follows a followee.
//unfollow(followerId, followeeId): Follower unfollows a followee.
//Example:
//Twitter twitter = new Twitter();
//// User 1 posts a new tweet (id = 5).
//twitter.postTweet(1, 5);
//// User 1's news feed should return a list with 1 tweet id -> [5].
//twitter.getNewsFeed(1);
//// User 1 follows user 2.
//twitter.follow(1, 2);
//// User 2 posts a new tweet (id = 6).
//twitter.postTweet(2, 6);
//// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
//// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
//twitter.getNewsFeed(1);
//// User 1 unfollows user 2.
//twitter.unfollow(1, 2);
//// User 1's news feed should return a list with 1 tweet id -> [5],
//// since user 1 is no longer following user 2.
//twitter.getNewsFeed(1);
//type Twitter struct {
//}
///** Initialize your data structure here. */
//func Constructor() Twitter {
//}
///** Compose a new tweet. */
//func (this *Twitter) PostTweet(userId int, tweetId int) {
//}
///** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
//func (this *Twitter) GetNewsFeed(userId int) []int {
//}
///** Follower follows a followee. If the operation is invalid, it should be a no-op. */
//func (this *Twitter) Follow(followerId int, followeeId int) {
//}
///** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
//func (this *Twitter) Unfollow(followerId int, followeeId int) {
//}
///**
// * Your Twitter object will be instantiated and called as such:
// * obj := Constructor();
// * obj.PostTweet(userId,tweetId);
// * param_2 := obj.GetNewsFeed(userId);
// * obj.Follow(followerId,followeeId);
// * obj.Unfollow(followerId,followeeId);
// */
// Time Is Money |
package commands
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/serverlib"
)
// NewAppShowCommand will show current application config
func NewAppShowCommand(ioStreams cmdutil.IOStreams) *cobra.Command {
cmd := &cobra.Command{
Use: "show APP_NAME",
Short: "Show details of an application",
Long: "Show details of an application",
Example: `vela show APP_NAME`,
RunE: func(cmd *cobra.Command, args []string) error {
argsLength := len(args)
if argsLength == 0 {
ioStreams.Errorf("Hint: please specify the application name\n")
os.Exit(1)
}
appName := args[0]
env, err := GetEnv(cmd)
if err != nil {
ioStreams.Errorf("Error: failed to get Env: %s", err)
return err
}
return showApplication(cmd, env, appName)
},
Annotations: map[string]string{
types.TagCommandType: types.TypeApp,
},
}
cmd.Flags().StringP("svc", "s", "", "service name")
cmd.SetOut(ioStreams.Out)
return cmd
}
func showApplication(cmd *cobra.Command, env *types.EnvMeta, appName string) error {
app, err := application.Load(env.Name, appName)
if err != nil {
return err
}
targetServices, err := serverlib.GetServicesWhenDescribingApplication(cmd, app)
if err != nil {
return err
}
cmd.Printf("About:\n\n")
table := newUITable()
table.AddRow(" Name:", appName)
table.AddRow(" Created at:", app.CreateTime.String())
table.AddRow(" Updated at:", app.UpdateTime.String())
cmd.Printf("%s\n\n", table.String())
cmd.Println()
cmd.Printf("Environment:\n\n")
cmd.Printf(" Namespace:\t%s\n", env.Namespace)
cmd.Println()
table = newUITable()
cmd.Printf("Services:\n\n")
for _, svcName := range targetServices {
if err := showComponent(cmd, env, svcName, appName); err != nil {
return err
}
}
cmd.Println(table.String())
cmd.Println()
return nil
}
func showComponent(cmd *cobra.Command, env *types.EnvMeta, compName, appName string) error {
var app *driver.Application
var err error
if appName != "" {
app, err = application.Load(env.Name, appName)
} else {
app, err = application.MatchAppByComp(env.Name, compName)
}
if err != nil {
return err
}
for cname := range app.Services {
if cname != compName {
continue
}
wtype, data := application.GetWorkload(app, compName)
table := newUITable()
table.AddRow(" - Name:", compName)
table.AddRow(" WorkloadType:", wtype)
cmd.Printf(table.String())
cmd.Printf("\n Arguments:\n")
table = newUITable()
for k, v := range data {
table.AddRow(fmt.Sprintf(" %s: ", k), v)
}
cmd.Printf("%s", table.String())
traits, err := application.GetTraits(app, compName)
if err != nil {
cmd.PrintErr(err)
continue
}
cmd.Println()
cmd.Printf(" Traits:\n")
for k, v := range traits {
cmd.Printf(" - %s:\n", k)
table = newUITable()
for kk, vv := range v {
table.AddRow(fmt.Sprintf(" %s:", kk), vv)
}
cmd.Printf("%s\n", table.String())
}
cmd.Println()
}
return nil
}
|
package postgres
import (
"database/sql"
"github.com/idena-network/idena-go/common"
"github.com/idena-network/idena-indexer/explorer/types"
"math/big"
"time"
)
const (
addressQuery = "address.sql"
addressPenaltiesCountQuery = "addressPenaltiesCount.sql"
addressPenaltiesQuery = "addressPenalties.sql"
addressMiningRewardsCountQuery = "addressMiningRewardsCount.sql"
addressMiningRewardsQuery = "addressMiningRewards.sql"
addressBlockMiningRewardsCountQuery = "addressBlockMiningRewardsCount.sql"
addressBlockMiningRewardsQuery = "addressBlockMiningRewards.sql"
addressStatesCountQuery = "addressStatesCount.sql"
addressStatesQuery = "addressStates.sql"
addressTotalLatestMiningRewardQuery = "addressTotalLatestMiningReward.sql"
addressTotalLatestBurntCoinsQuery = "addressTotalLatestBurntCoins.sql"
addressBadAuthorsCountQuery = "addressBadAuthorsCount.sql"
addressBadAuthorsQuery = "addressBadAuthors.sql"
)
func (a *postgresAccessor) Address(address string) (types.Address, error) {
res := types.Address{}
err := a.db.QueryRow(a.getQuery(addressQuery), address).Scan(&res.Address, &res.Balance, &res.Stake, &res.TxCount)
if err == sql.ErrNoRows {
err = NoDataFound
}
if err != nil {
return types.Address{}, err
}
return res, nil
}
func (a *postgresAccessor) AddressPenaltiesCount(address string) (uint64, error) {
return a.count(addressPenaltiesCountQuery, address)
}
func (a *postgresAccessor) AddressPenalties(address string, startIndex uint64, count uint64) ([]types.Penalty, error) {
rows, err := a.db.Query(a.getQuery(addressPenaltiesQuery), address, startIndex, count)
if err != nil {
return nil, err
}
defer rows.Close()
var res []types.Penalty
for rows.Next() {
item := types.Penalty{}
var timestamp int64
err = rows.Scan(&item.Address,
&item.Penalty,
&item.Paid,
&item.BlockHeight,
&item.BlockHash,
×tamp,
&item.Epoch)
if err != nil {
return nil, err
}
item.Timestamp = common.TimestampToTime(big.NewInt(timestamp))
res = append(res, item)
}
return res, nil
}
func (a *postgresAccessor) AddressMiningRewardsCount(address string) (uint64, error) {
return a.count(addressMiningRewardsCountQuery, address)
}
func (a *postgresAccessor) AddressMiningRewards(address string, startIndex uint64, count uint64) (
[]types.Reward, error) {
return a.rewards(addressMiningRewardsQuery, address, startIndex, count)
}
func (a *postgresAccessor) AddressBlockMiningRewardsCount(address string) (uint64, error) {
return a.count(addressBlockMiningRewardsCountQuery, address)
}
func (a *postgresAccessor) AddressBlockMiningRewards(address string, startIndex uint64, count uint64) (
[]types.BlockRewards, error) {
rows, err := a.db.Query(a.getQuery(addressBlockMiningRewardsQuery), address, startIndex, count)
if err != nil {
return nil, err
}
defer rows.Close()
var res []types.BlockRewards
var item *types.BlockRewards
for rows.Next() {
reward := types.Reward{}
var blockHeight, epoch uint64
if err := rows.Scan(&blockHeight, &epoch, &reward.Balance, &reward.Stake, &reward.Type); err != nil {
return nil, err
}
if item == nil || item.Height != blockHeight {
if item != nil {
res = append(res, *item)
}
item = &types.BlockRewards{
Height: blockHeight,
Epoch: epoch,
}
}
item.Rewards = append(item.Rewards, reward)
}
if item != nil {
res = append(res, *item)
}
return res, nil
}
func (a *postgresAccessor) AddressStatesCount(address string) (uint64, error) {
return a.count(addressStatesCountQuery, address)
}
func (a *postgresAccessor) AddressStates(address string, startIndex uint64, count uint64) ([]types.AddressState, error) {
rows, err := a.db.Query(a.getQuery(addressStatesQuery), address, startIndex, count)
if err != nil {
return nil, err
}
defer rows.Close()
var res []types.AddressState
for rows.Next() {
item := types.AddressState{}
var timestamp int64
err = rows.Scan(&item.State,
&item.Epoch,
&item.BlockHeight,
&item.BlockHash,
&item.TxHash,
×tamp,
&item.IsValidation)
if err != nil {
return nil, err
}
item.Timestamp = common.TimestampToTime(big.NewInt(timestamp))
res = append(res, item)
}
return res, nil
}
func (a *postgresAccessor) AddressTotalLatestMiningReward(afterTime time.Time, address string) (types.TotalMiningReward, error) {
res := types.TotalMiningReward{}
err := a.db.QueryRow(a.getQuery(addressTotalLatestMiningRewardQuery), afterTime.Unix(), address).
Scan(&res.Balance, &res.Stake, &res.Proposer, &res.FinalCommittee)
if err != nil {
return types.TotalMiningReward{}, err
}
return res, nil
}
func (a *postgresAccessor) AddressTotalLatestBurntCoins(afterTime time.Time, address string) (types.AddressBurntCoins, error) {
res := types.AddressBurntCoins{}
err := a.db.QueryRow(a.getQuery(addressTotalLatestBurntCoinsQuery), afterTime.Unix(), address).
Scan(&res.Amount)
if err != nil {
return types.AddressBurntCoins{}, err
}
return res, nil
}
func (a *postgresAccessor) AddressBadAuthorsCount(address string) (uint64, error) {
return a.count(addressBadAuthorsCountQuery, address)
}
func (a *postgresAccessor) AddressBadAuthors(address string, startIndex uint64, count uint64) ([]types.BadAuthor, error) {
rows, err := a.db.Query(a.getQuery(addressBadAuthorsQuery), address, startIndex, count)
if err != nil {
return nil, err
}
return readBadAuthors(rows)
}
|
package ksqlparser
import "fmt"
type aliasedExpression struct {
Expression Expression
Alias string
}
func (e aliasedExpression) String() string {
if e.Alias != "" {
return fmt.Sprintf("%s %s %s", e.Expression.String(), ReservedAs, e.Alias)
}
return e.Expression.String()
}
|
package rsrch
import (
"fmt"
"reflect"
"testing"
)
func TestReflectInvariants(t *testing.T) {
describe := func(thing interface{}) {
rt := reflect.TypeOf(thing)
fmt.Printf("type: %#v (%q)\n", rt, rt)
fmt.Printf("kind: %#v (%q)\n", rt.Kind(), rt.Kind())
fmt.Printf("name: %q\n", rt.Name())
fmt.Printf("PkgPath: %q\n", rt.PkgPath())
}
describe("")
fmt.Println()
type StrTypedef string
describe(StrTypedef(""))
fmt.Println()
// I guess the cheapest and sanest way to check if something is one of the
// builtin primitives is just checking the rtid pointer equality outright?
//
// I think `PkgPath() == "" && (... kind is not slice, etc...)` might also work,
// but the documentation doesn't make it very clear if that's an intended use
// of the PkgPath function, and this seems much harder and less reliable
// than the "hack".
fmt.Printf("str rtid: %v\n", reflect.ValueOf(reflect.TypeOf("")).Pointer()) // Strings are ofc consistent.
fmt.Printf("str rtid: %v\n", reflect.ValueOf(reflect.TypeOf("")).Pointer())
fmt.Printf("typedstr rtid: %v\n", reflect.ValueOf(reflect.TypeOf(StrTypedef(""))).Pointer()) // Typedefs are consistent, and neq builtin string.
fmt.Printf("typedstr rtid: %v\n", reflect.ValueOf(reflect.TypeOf(StrTypedef(""))).Pointer())
fmt.Printf("nillarystruct rtid: %v\n", reflect.ValueOf(reflect.TypeOf(struct{}{})).Pointer()) // Nillary structs are consistent.
fmt.Printf("nillarystruct rtid: %v\n", reflect.ValueOf(reflect.TypeOf(struct{}{})).Pointer())
fmt.Printf("anonstruct rtid: %v\n", reflect.ValueOf(reflect.TypeOf(struct{ string }{})).Pointer()) // Anon structs with members are, remarkably, all considered the same.
fmt.Printf("anonstruct rtid: %v\n", reflect.ValueOf(reflect.TypeOf(struct{ string }{})).Pointer())
fmt.Printf("[]byte rtid: %v\n", reflect.ValueOf(reflect.TypeOf([]byte{})).Pointer()) // byte slice and uint8 slice are an alias.
fmt.Printf("[]uint8 rtid: %v\n", reflect.ValueOf(reflect.TypeOf([]uint8(nil))).Pointer())
}
func TestMapSetSemanitcsLiterallyEven(t *testing.T) {
anInt := 0
rv := reflect.ValueOf(anInt)
anMap := make(map[string]int)
map_rv := reflect.ValueOf(anMap)
key := "asdf"
key_rv := reflect.ValueOf(key)
map_rv.SetMapIndex(key_rv, rv)
fmt.Printf("themap: %v\n", anMap)
}
|
package config
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
log "github.com/golang/glog"
"lib/config"
)
type Config struct {
XMLName xml.Name `xml:"config"`
ServerConf *config.ServerConfig `xml:"serverconfig"`
ClientConf *config.ClientConfig `xml:"clientconfig"`
ShmCacheConf *config.ShmCacheConfig `xml:"shmcacheconfig"`
LogConf *config.LogConfig `xml:"logconfig"`
}
func (conf *Config)Init(filePath *string) error {
file, err := os.Open(*filePath) // For read access.
if err != nil {
log.Errorf(err.Error())
fmt.Println(err.Error())
return err
}
data, err := ioutil.ReadAll(file)
file.Close()
if err != nil {
log.Errorf(err.Error())
fmt.Println(err.Error())
return err
}
err = xml.Unmarshal(data, conf)
if err != nil {
log.Errorf("xml unmarshal error")
fmt.Println(err.Error())
return err
}
return nil
}
var Conf = &Config{}
|
package flags
type Byte byte
func (f Byte) Add(b ...Byte) Byte {
for i := 0; i < len(b); i++ {
f = f | b[i]
}
return f
}
func (f Byte) Remove(b ...Byte) Byte {
for i := 0; i < len(b); i++ {
f = f ^ b[i]
}
return f
}
func (f Byte) Intersect(b ...Byte) Byte {
s := Byte(0).Add(b...)
return f & s
}
func (f Byte) IsAny(b ...Byte) bool {
return f.Intersect(b...) > 0
}
func (f Byte) IsAll(b ...Byte) bool {
return f.Intersect(b...) == f
}
|
package inversions
import (
"io/ioutil"
"strconv"
"strings"
)
func Inversions(lines []int) ([]int, int) {
n := len(lines)
if n < 2 {
return lines, 0
}
left, leftInv := Inversions(lines[0:(n / 2)])
right, rightInv := Inversions(lines[(n / 2):])
combined, splitInv := countSplitInversions(left, right)
return combined, leftInv + rightInv + splitInv
}
func countSplitInversions(a, b []int) ([]int, int) {
lenA := len(a)
aI := 0
lenB := len(b)
bI := 0
c := []int{}
splitInv := 0
for k := 0; k < lenA+lenB; k++ {
if aI >= lenA {
c = append(c, b[bI])
bI++
continue
}
if bI >= lenB {
c = append(c, a[aI])
aI++
continue
}
if a[aI] < b[bI] {
c = append(c, a[aI])
aI++
} else {
c = append(c, b[bI])
bI++
splitInv += ((lenA+lenB)/2 - aI)
}
}
return c, splitInv
}
func FileToInversions(filePath string) (int, error) {
stringLines, err := fileToStringSlice(filePath)
if err != nil {
return 0, err
}
intLines, err := StringSliceToIntSlice(stringLines)
if err != nil {
return 0, err
}
_, inversions := Inversions(intLines)
return inversions, nil
}
func fileToStringSlice(filePath string) ([]string, error) {
content, err := ioutil.ReadFile(filePath)
if err != nil {
return []string{}, err
}
lines := strings.Split(string(content), "\n")
return lines, nil
}
func StringSliceToIntSlice(stringLines []string) ([]int, error) {
intSlice := []int{}
for _, s := range stringLines {
// strings.Split adds an empty string at the end of the slice.
if s == "" {
continue
}
i, err := strconv.Atoi(s)
if err != nil {
return intSlice, err
}
intSlice = append(intSlice, i)
}
return intSlice, nil
}
|
package app
import (
"github.com/tarm/serial"
)
// Connect opens and returns serial port as defined in config
func Connect(config *serial.Config) (*serial.Port, error) {
conn, err := serial.OpenPort(config)
return conn, err
}
|
package command
type VersionCommand struct {
*baseCommand
Version string
}
func (c *VersionCommand) Help() string {
return ""
}
func (c *VersionCommand) Name() string { return "version" }
func (c *VersionCommand) Run(_ []string) int {
c.ui.Output(c.Version)
return 0
}
func (c *VersionCommand) Synopsis() string {
return "Prints the client version"
}
|
package futures
import (
"log"
"testing"
"github.com/stretchr/testify/suite"
)
type commissionRateServiceTestSuite struct {
baseTestSuite
}
func TestCommissionRateService(t *testing.T) {
suite.Run(t, new(commissionRateServiceTestSuite))
}
func (commissionRateService *commissionRateServiceTestSuite) TestCommissionRate() {
data := []byte(`
{
"symbol": "BTCUSDT",
"makerCommissionRate": "0.001",
"takerCommissionRate": "0.001"
}
`)
commissionRateService.mockDo(data, nil)
defer commissionRateService.assertDo()
symbol := "BTCUSDT"
commissionRateService.assertReq(func(request *request) {
requestParams := newSignedRequest().setParam("symbol", symbol)
commissionRateService.assertRequestEqual(requestParams, request)
})
res, err := commissionRateService.client.NewCommissionRateService().Symbol(symbol).Do(newContext())
commissionRateService.r().NoError(err)
expectation := &CommissionRate{
Symbol: symbol,
MakerCommissionRate: "0.001",
TakerCommissionRate: "0.001",
}
commissionRateService.assertCommissionRateResponseEqual(expectation, res)
}
func (commissionRateServiceTestSuite *commissionRateServiceTestSuite) assertCommissionRateResponseEqual(expectation, assertedData *CommissionRate) {
assertion := commissionRateServiceTestSuite.r()
log.Printf("TEST 1 %#v\n", expectation)
log.Printf("TEST 2 %#v\n", assertedData)
log.Printf("TEST 3 %#v\n", assertion)
assertion.Equal(expectation.Symbol, assertedData.Symbol, "Symbol")
assertion.Equal(expectation.MakerCommissionRate, assertedData.MakerCommissionRate, "MakerCommissionRate")
assertion.Equal(expectation.TakerCommissionRate, assertedData.TakerCommissionRate, "TakerCommissionRate")
}
|
// Copyright 2018 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package wifi
import "unsafe" // yuck
// This file is from the linux wifi definitions. We leave the
// original in here for reference. We'll probably remove it later.
var _ = `
/*
* This file define a set of standard wireless extensions
*
* Version : 22 16.3.07
*
* Authors : Jean Tourrilhes - HPL - <jt@hpl.hp.com>
* Copyright (c) 1997-2007 Jean Tourrilhes, All Rights Reserved.
*/
#ifndef _LINUX_WIRELESS_H
#define _LINUX_WIRELESS_H
/************************** DOCUMENTATION **************************/
/*
* Initial APIs (1996 -> onward) :
* -----------------------------
* Basically, the wireless extensions are for now a set of standard ioctl
* call + /proc/net/wireless
*
* The entry /proc/net/wireless give statistics and information on the
* driver.
* This is better than having each driver having its entry because
* its centralised and we may remove the driver module safely.
*
* Ioctl are used to configure the driver and issue commands. This is
* better than command line options of insmod because we may want to
* change dynamically (while the driver is running) some parameters.
*
* The ioctl mechanimsm are copied from standard devices ioctl.
* We have the list of command plus a structure descibing the
* data exchanged...
* Note that to add these ioctl, I was obliged to modify :
* # net/core/dev.c (two place + add include)
* # net/ipv4/af_inet.c (one place + add include)
*
* /proc/net/wireless is a copy of /proc/net/dev.
* We have a structure for data passed from the driver to /proc/net/wireless
* Too add this, I've modified :
* # net/core/dev.c (two other places)
* # include/linux/netdevice.h (one place)
* # include/linux/proc_fs.h (one place)
*
* New driver API (2002 -> onward) :
* -------------------------------
* This file is only concerned with the user space API and common definitions.
* The new driver API is defined and documented in :
* # include/net/iw_handler.h
*
* Note as well that /proc/net/wireless implementation has now moved in :
* # net/core/wireless.c
*
* Wireless Events (2002 -> onward) :
* --------------------------------
* Events are defined at the end of this file, and implemented in :
* # net/core/wireless.c
*
* Other comments :
* --------------
* Do not add here things that are redundant with other mechanisms
* (drivers init, ifconfig, /proc/net/dev, ...) and with are not
* wireless specific.
*
* These wireless extensions are not magic : each driver has to provide
* support for them...
*
* IMPORTANT NOTE : As everything in the kernel, this is very much a
* work in progress. Contact me if you have ideas of improvements...
*/
/***************************** INCLUDES *****************************/
#include <linux/types.h> /* for __u* and __s* typedefs */
#include <linux/socket.h> /* for "struct sockaddr" et al */
#include <linux/if.h> /* for IFNAMSIZ and co... */
/***************************** VERSION *****************************/
/*
* This constant is used to know the availability of the wireless
* extensions and to know which version of wireless extensions it is
* (there is some stuff that will be added in the future...)
* I just plan to increment with each new version.
*/
#define WIRELESS_EXT 22
/*
* Changes :
*
* V2 to V3
* --------
* Alan Cox start some incompatibles changes. I've integrated a bit more.
* - Encryption renamed to Encode to avoid US regulation problems
* - Frequency changed from float to struct to avoid problems on old 386
*
* V3 to V4
* --------
* - Add sensitivity
*
* V4 to V5
* --------
* - Missing encoding definitions in range
* - Access points stuff
*
* V5 to V6
* --------
* - 802.11 support (ESSID ioctls)
*
* V6 to V7
* --------
* - define IW_ESSID_MAX_SIZE and IW_MAX_AP
*
* V7 to V8
* --------
* - Changed my e-mail address
* - More 802.11 support (nickname, rate, rts, frag)
* - List index in frequencies
*
* V8 to V9
* --------
* - Support for 'mode of operation' (ad-hoc, managed...)
* - Support for unicast and multicast power saving
* - Change encoding to support larger tokens (>64 bits)
* - Updated iw_params (disable, flags) and use it for NWID
* - Extracted iw_point from iwreq for clarity
*
* V9 to V10
* ---------
* - Add PM capability to range structure
* - Add PM modifier : MAX/MIN/RELATIVE
* - Add encoding option : IW_ENCODE_NOKEY
* - Add TxPower ioctls (work like TxRate)
*
* V10 to V11
* ----------
* - Add WE version in range (help backward/forward compatibility)
* - Add retry ioctls (work like PM)
*
* V11 to V12
* ----------
* - Add SIOCSIWSTATS to get /proc/net/wireless programatically
* - Add DEV PRIVATE IOCTL to avoid collisions in SIOCDEVPRIVATE space
* - Add new statistics (frag, retry, beacon)
* - Add average quality (for user space calibration)
*
* V12 to V13
* ----------
* - Document creation of new driver API.
* - Extract union iwreq_data from struct iwreq (for new driver API).
* - Rename SIOCSIWNAME as SIOCSIWCOMMIT
*
* V13 to V14
* ----------
* - Wireless Events support : define struct iw_event
* - Define additional specific event numbers
* - Add "addr" and "param" fields in union iwreq_data
* - AP scanning stuff (SIOCSIWSCAN and friends)
*
* V14 to V15
* ----------
* - Add IW_PRIV_TYPE_ADDR for struct sockaddr private arg
* - Make struct iw_freq signed (both m & e), add explicit padding
* - Add IWEVCUSTOM for driver specific event/scanning token
* - Add IW_MAX_GET_SPY for driver returning a lot of addresses
* - Add IW_TXPOW_RANGE for range of Tx Powers
* - Add IWEVREGISTERED & IWEVEXPIRED events for Access Points
* - Add IW_MODE_MONITOR for passive monitor
*
* V15 to V16
* ----------
* - Increase the number of bitrates in iw_range to 32 (for 802.11g)
* - Increase the number of frequencies in iw_range to 32 (for 802.11b+a)
* - Reshuffle struct iw_range for increases, add filler
* - Increase IW_MAX_AP to 64 for driver returning a lot of addresses
* - Remove IW_MAX_GET_SPY because conflict with enhanced spy support
* - Add SIOCSIWTHRSPY/SIOCGIWTHRSPY and "struct iw_thrspy"
* - Add IW_ENCODE_TEMP and iw_range->encoding_login_index
*
* V16 to V17
* ----------
* - Add flags to frequency -> auto/fixed
* - Document (struct iw_quality *)->updated, add new flags (INVALID)
* - Wireless Event capability in struct iw_range
* - Add support for relative TxPower (yick !)
*
* V17 to V18 (From Jouni Malinen <j@w1.fi>)
* ----------
* - Add support for WPA/WPA2
* - Add extended encoding configuration (SIOCSIWENCODEEXT and
* SIOCGIWENCODEEXT)
* - Add SIOCSIWGENIE/SIOCGIWGENIE
* - Add SIOCSIWMLME
* - Add SIOCSIWPMKSA
* - Add struct iw_range bit field for supported encoding capabilities
* - Add optional scan request parameters for SIOCSIWSCAN
* - Add SIOCSIWAUTH/SIOCGIWAUTH for setting authentication and WPA
* related parameters (extensible up to 4096 parameter values)
* - Add wireless events: IWEVGENIE, IWEVMICHAELMICFAILURE,
* IWEVASSOCREQIE, IWEVASSOCRESPIE, IWEVPMKIDCAND
*
* V18 to V19
* ----------
* - Remove (struct iw_point *)->pointer from events and streams
* - Remove header includes to help user space
* - Increase IW_ENCODING_TOKEN_MAX from 32 to 64
* - Add IW_QUAL_ALL_UPDATED and IW_QUAL_ALL_INVALID macros
* - Add explicit flag to tell stats are in dBm : IW_QUAL_DBM
* - Add IW_IOCTL_IDX() and IW_EVENT_IDX() macros
*
* V19 to V20
* ----------
* - RtNetlink requests support (SET/GET)
*
* V20 to V21
* ----------
* - Remove (struct net_device *)->get_wireless_stats()
* - Change length in ESSID and NICK to strlen() instead of strlen()+1
* - Add IW_RETRY_SHORT/IW_RETRY_LONG retry modifiers
* - Power/Retry relative values no longer * 100000
* - Add explicit flag to tell stats are in 802.11k RCPI : IW_QUAL_RCPI
*
* V21 to V22
* ----------
* - Prevent leaking of kernel space in stream on 64 bits.
*/
/**************************** CONSTANTS ****************************/
/* -------------------------- IOCTL LIST -------------------------- */
/* Wireless Identification */
#define SIOCSIWCOMMIT 0x8B00 /* Commit pending changes to driver */
#define SIOCGIWNAME 0x8B01 /* get name == wireless protocol */
/* SIOCGIWNAME is used to verify the presence of Wireless Extensions.
* Common values : "IEEE 802.11-DS", "IEEE 802.11-FH", "IEEE 802.11b"...
* Don't put the name of your driver there, it's useless. */
/* Basic operations */
#define SIOCSIWNWID 0x8B02 /* set network id (pre-802.11) */
#define SIOCGIWNWID 0x8B03 /* get network id (the cell) */
#define SIOCSIWFREQ 0x8B04 /* set channel/frequency (Hz) */
#define SIOCGIWFREQ 0x8B05 /* get channel/frequency (Hz) */
#define SIOCSIWMODE 0x8B06 /* set operation mode */
#define SIOCGIWMODE 0x8B07 /* get operation mode */
#define SIOCSIWSENS 0x8B08 /* set sensitivity (dBm) */
#define SIOCGIWSENS 0x8B09 /* get sensitivity (dBm) */
/* Informative stuff */
#define SIOCSIWRANGE 0x8B0A /* Unused */
#define SIOCGIWRANGE 0x8B0B /* Get range of parameters */
#define SIOCSIWPRIV 0x8B0C /* Unused */
#define SIOCGIWPRIV 0x8B0D /* get private ioctl interface info */
#define SIOCSIWSTATS 0x8B0E /* Unused */
#define SIOCGIWSTATS 0x8B0F /* Get /proc/net/wireless stats */
/* SIOCGIWSTATS is strictly used between user space and the kernel, and
* is never passed to the driver (i.e. the driver will never see it). */
/* Spy support (statistics per MAC address - used for Mobile IP support) */
#define SIOCSIWSPY 0x8B10 /* set spy addresses */
#define SIOCGIWSPY 0x8B11 /* get spy info (quality of link) */
#define SIOCSIWTHRSPY 0x8B12 /* set spy threshold (spy event) */
#define SIOCGIWTHRSPY 0x8B13 /* get spy threshold */
/* Access Point manipulation */
#define SIOCSIWAP 0x8B14 /* set access point MAC addresses */
#define SIOCGIWAP 0x8B15 /* get access point MAC addresses */
#define SIOCGIWAPLIST 0x8B17 /* Deprecated in favor of scanning */
#define SIOCSIWSCAN 0x8B18 /* trigger scanning (list cells) */
#define SIOCGIWSCAN 0x8B19 /* get scanning results */
/* 802.11 specific support */
#define SIOCSIWESSID 0x8B1A /* set ESSID (network name) */
#define SIOCGIWESSID 0x8B1B /* get ESSID */
#define SIOCSIWNICKN 0x8B1C /* set node name/nickname */
#define SIOCGIWNICKN 0x8B1D /* get node name/nickname */
/* As the ESSID and NICKN are strings up to 32 bytes long, it doesn't fit
* within the 'iwreq' structure, so we need to use the 'data' member to
* point to a string in user space, like it is done for RANGE... */
/* Other parameters useful in 802.11 and some other devices */
#define SIOCSIWRATE 0x8B20 /* set default bit rate (bps) */
#define SIOCGIWRATE 0x8B21 /* get default bit rate (bps) */
#define SIOCSIWRTS 0x8B22 /* set RTS/CTS threshold (bytes) */
#define SIOCGIWRTS 0x8B23 /* get RTS/CTS threshold (bytes) */
#define SIOCSIWFRAG 0x8B24 /* set fragmentation thr (bytes) */
#define SIOCGIWFRAG 0x8B25 /* get fragmentation thr (bytes) */
#define SIOCSIWTXPOW 0x8B26 /* set transmit power (dBm) */
#define SIOCGIWTXPOW 0x8B27 /* get transmit power (dBm) */
#define SIOCSIWRETRY 0x8B28 /* set retry limits and lifetime */
#define SIOCGIWRETRY 0x8B29 /* get retry limits and lifetime */
/* Encoding stuff (scrambling, hardware security, WEP...) */
#define SIOCSIWENCODE 0x8B2A /* set encoding token & mode */
#define SIOCGIWENCODE 0x8B2B /* get encoding token & mode */
/* Power saving stuff (power management, unicast and multicast) */
#define SIOCSIWPOWER 0x8B2C /* set Power Management settings */
#define SIOCGIWPOWER 0x8B2D /* get Power Management settings */
/* WPA : Generic IEEE 802.11 informatiom element (e.g., for WPA/RSN/WMM).
* This ioctl uses struct iw_point and data buffer that includes IE id and len
* fields. More than one IE may be included in the request. Setting the generic
* IE to empty buffer (len=0) removes the generic IE from the driver. Drivers
* are allowed to generate their own WPA/RSN IEs, but in these cases, drivers
* are required to report the used IE as a wireless event, e.g., when
* associating with an AP. */
#define SIOCSIWGENIE 0x8B30 /* set generic IE */
#define SIOCGIWGENIE 0x8B31 /* get generic IE */
/* WPA : IEEE 802.11 MLME requests */
#define SIOCSIWMLME 0x8B16 /* request MLME operation; uses
* struct iw_mlme */
/* WPA : Authentication mode parameters */
#define SIOCSIWAUTH 0x8B32 /* set authentication mode params */
#define SIOCGIWAUTH 0x8B33 /* get authentication mode params */
/* WPA : Extended version of encoding configuration */
#define SIOCSIWENCODEEXT 0x8B34 /* set encoding token & mode */
#define SIOCGIWENCODEEXT 0x8B35 /* get encoding token & mode */
/* WPA2 : PMKSA cache management */
#define SIOCSIWPMKSA 0x8B36 /* PMKSA cache operation */
/* -------------------- DEV PRIVATE IOCTL LIST -------------------- */
/* These 32 ioctl are wireless device private, for 16 commands.
* Each driver is free to use them for whatever purpose it chooses,
* however the driver *must* export the description of those ioctls
* with SIOCGIWPRIV and *must* use arguments as defined below.
* If you don't follow those rules, DaveM is going to hate you (reason :
* it make mixed 32/64bit operation impossible).
*/
#define SIOCIWFIRSTPRIV 0x8BE0
#define SIOCIWLASTPRIV 0x8BFF
/* Previously, we were using SIOCDEVPRIVATE, but we now have our
* separate range because of collisions with other tools such as
* 'mii-tool'.
* We now have 32 commands, so a bit more space ;-).
* Also, all 'even' commands are only usable by root and don't return the
* content of ifr/iwr to user (but you are not obliged to use the set/get
* convention, just use every other two command). More details in iwpriv.c.
* And I repeat : you are not forced to use them with iwpriv, but you
* must be compliant with it.
*/
/* ------------------------- IOCTL STUFF ------------------------- */
/* The first and the last (range) */
#define SIOCIWFIRST 0x8B00
#define SIOCIWLAST SIOCIWLASTPRIV /* 0x8BFF */
#define IW_IOCTL_IDX(cmd) ((cmd) - SIOCIWFIRST)
#define IW_HANDLER(id, func) \
[IW_IOCTL_IDX(id)] = func
/* Odd : get (world access), even : set (root access) */
#define IW_IS_SET(cmd) (!((cmd) & 0x1))
#define IW_IS_GET(cmd) ((cmd) & 0x1)
/* ----------------------- WIRELESS EVENTS ----------------------- */
/* Those are *NOT* ioctls, do not issue request on them !!! */
/* Most events use the same identifier as ioctl requests */
#define IWEVTXDROP 0x8C00 /* Packet dropped to excessive retry */
#define IWEVQUAL 0x8C01 /* Quality part of statistics (scan) */
#define IWEVCUSTOM 0x8C02 /* Driver specific ascii string */
#define IWEVREGISTERED 0x8C03 /* Discovered a new node (AP mode) */
#define IWEVEXPIRED 0x8C04 /* Expired a node (AP mode) */
#define IWEVGENIE 0x8C05 /* Generic IE (WPA, RSN, WMM, ..)
* (scan results); This includes id and
* length fields. One IWEVGENIE may
* contain more than one IE. Scan
* results may contain one or more
* IWEVGENIE events. */
#define IWEVMICHAELMICFAILURE 0x8C06 /* Michael MIC failure
* (struct iw_michaelmicfailure)
*/
#define IWEVASSOCREQIE 0x8C07 /* IEs used in (Re)Association Request.
* The data includes id and length
* fields and may contain more than one
* IE. This event is required in
* Managed mode if the driver
* generates its own WPA/RSN IE. This
* should be sent just before
* IWEVREGISTERED event for the
* association. */
#define IWEVASSOCRESPIE 0x8C08 /* IEs used in (Re)Association
* Response. The data includes id and
* length fields and may contain more
* than one IE. This may be sent
* between IWEVASSOCREQIE and
* IWEVREGISTERED events for the
* association. */
#define IWEVPMKIDCAND 0x8C09 /* PMKID candidate for RSN
* pre-authentication
* (struct iw_pmkid_cand) */
#define IWEVFIRST 0x8C00
#define IW_EVENT_IDX(cmd) ((cmd) - IWEVFIRST)
/* ------------------------- PRIVATE INFO ------------------------- */
/*
* The following is used with SIOCGIWPRIV. It allow a driver to define
* the interface (name, type of data) for its private ioctl.
* Privates ioctl are SIOCIWFIRSTPRIV -> SIOCIWLASTPRIV
*/
#define IW_PRIV_TYPE_MASK 0x7000 /* Type of arguments */
#define IW_PRIV_TYPE_NONE 0x0000
#define IW_PRIV_TYPE_BYTE 0x1000 /* Char as number */
#define IW_PRIV_TYPE_CHAR 0x2000 /* Char as character */
#define IW_PRIV_TYPE_INT 0x4000 /* 32 bits int */
#define IW_PRIV_TYPE_FLOAT 0x5000 /* struct iw_freq */
#define IW_PRIV_TYPE_ADDR 0x6000 /* struct sockaddr */
#define IW_PRIV_SIZE_FIXED 0x0800 /* Variable or fixed number of args */
#define IW_PRIV_SIZE_MASK 0x07FF /* Max number of those args */
/*
* Note : if the number of args is fixed and the size < 16 octets,
* instead of passing a pointer we will put args in the iwreq struct...
*/
/* ----------------------- OTHER CONSTANTS ----------------------- */
/* Maximum frequencies in the range struct */
#define IW_MAX_FREQUENCIES 32
/* Note : if you have something like 80 frequencies,
* don't increase this constant and don't fill the frequency list.
* The user will be able to set by channel anyway... */
/* Maximum bit rates in the range struct */
#define IW_MAX_BITRATES 32
/* Maximum tx powers in the range struct */
#define IW_MAX_TXPOWER 8
/* Note : if you more than 8 TXPowers, just set the max and min or
* a few of them in the struct iw_range. */
/* Maximum of address that you may set with SPY */
#define IW_MAX_SPY 8
/* Maximum of address that you may get in the
list of access points in range */
#define IW_MAX_AP 64
/* Maximum size of the ESSID and NICKN strings */
#define IW_ESSID_MAX_SIZE 32
/* Modes of operation */
#define IW_MODE_AUTO 0 /* Let the driver decides */
#define IW_MODE_ADHOC 1 /* Single cell network */
#define IW_MODE_INFRA 2 /* Multi cell network, roaming, ... */
#define IW_MODE_MASTER 3 /* Synchronisation master or Access Point */
#define IW_MODE_REPEAT 4 /* Wireless Repeater (forwarder) */
#define IW_MODE_SECOND 5 /* Secondary master/repeater (backup) */
#define IW_MODE_MONITOR 6 /* Passive monitor (listen only) */
#define IW_MODE_MESH 7 /* Mesh (IEEE 802.11s) network */
/* Statistics flags (bitmask in updated) */
#define IW_QUAL_QUAL_UPDATED 0x01 /* Value was updated since last read */
#define IW_QUAL_LEVEL_UPDATED 0x02
#define IW_QUAL_NOISE_UPDATED 0x04
#define IW_QUAL_ALL_UPDATED 0x07
#define IW_QUAL_DBM 0x08 /* Level + Noise are dBm */
#define IW_QUAL_QUAL_INVALID 0x10 /* Driver doesn't provide value */
#define IW_QUAL_LEVEL_INVALID 0x20
#define IW_QUAL_NOISE_INVALID 0x40
#define IW_QUAL_RCPI 0x80 /* Level + Noise are 802.11k RCPI */
#define IW_QUAL_ALL_INVALID 0x70
/* Frequency flags */
#define IW_FREQ_AUTO 0x00 /* Let the driver decides */
#define IW_FREQ_FIXED 0x01 /* Force a specific value */
/* Maximum number of size of encoding token available
* they are listed in the range structure */
#define IW_MAX_ENCODING_SIZES 8
/* Maximum size of the encoding token in bytes */
#define IW_ENCODING_TOKEN_MAX 64 /* 512 bits (for now) */
/* Flags for encoding (along with the token) */
#define IW_ENCODE_INDEX 0x00FF /* Token index (if needed) */
#define IW_ENCODE_FLAGS 0xFF00 /* Flags defined below */
#define IW_ENCODE_MODE 0xF000 /* Modes defined below */
#define IW_ENCODE_DISABLED 0x8000 /* Encoding disabled */
#define IW_ENCODE_ENABLED 0x0000 /* Encoding enabled */
#define IW_ENCODE_RESTRICTED 0x4000 /* Refuse non-encoded packets */
#define IW_ENCODE_OPEN 0x2000 /* Accept non-encoded packets */
#define IW_ENCODE_NOKEY 0x0800 /* Key is write only, so not present */
#define IW_ENCODE_TEMP 0x0400 /* Temporary key */
/* Power management flags available (along with the value, if any) */
#define IW_POWER_ON 0x0000 /* No details... */
#define IW_POWER_TYPE 0xF000 /* Type of parameter */
#define IW_POWER_PERIOD 0x1000 /* Value is a period/duration of */
#define IW_POWER_TIMEOUT 0x2000 /* Value is a timeout (to go asleep) */
#define IW_POWER_MODE 0x0F00 /* Power Management mode */
#define IW_POWER_UNICAST_R 0x0100 /* Receive only unicast messages */
#define IW_POWER_MULTICAST_R 0x0200 /* Receive only multicast messages */
#define IW_POWER_ALL_R 0x0300 /* Receive all messages though PM */
#define IW_POWER_FORCE_S 0x0400 /* Force PM procedure for sending unicast */
#define IW_POWER_REPEATER 0x0800 /* Repeat broadcast messages in PM period */
#define IW_POWER_MODIFIER 0x000F /* Modify a parameter */
#define IW_POWER_MIN 0x0001 /* Value is a minimum */
#define IW_POWER_MAX 0x0002 /* Value is a maximum */
#define IW_POWER_RELATIVE 0x0004 /* Value is not in seconds/ms/us */
/* Transmit Power flags available */
#define IW_TXPOW_TYPE 0x00FF /* Type of value */
#define IW_TXPOW_DBM 0x0000 /* Value is in dBm */
#define IW_TXPOW_MWATT 0x0001 /* Value is in mW */
#define IW_TXPOW_RELATIVE 0x0002 /* Value is in arbitrary units */
#define IW_TXPOW_RANGE 0x1000 /* Range of value between min/max */
/* Retry limits and lifetime flags available */
#define IW_RETRY_ON 0x0000 /* No details... */
#define IW_RETRY_TYPE 0xF000 /* Type of parameter */
#define IW_RETRY_LIMIT 0x1000 /* Maximum number of retries*/
#define IW_RETRY_LIFETIME 0x2000 /* Maximum duration of retries in us */
#define IW_RETRY_MODIFIER 0x00FF /* Modify a parameter */
#define IW_RETRY_MIN 0x0001 /* Value is a minimum */
#define IW_RETRY_MAX 0x0002 /* Value is a maximum */
#define IW_RETRY_RELATIVE 0x0004 /* Value is not in seconds/ms/us */
#define IW_RETRY_SHORT 0x0010 /* Value is for short packets */
#define IW_RETRY_LONG 0x0020 /* Value is for long packets */
/* Scanning request flags */
#define IW_SCAN_DEFAULT 0x0000 /* Default scan of the driver */
#define IW_SCAN_ALL_ESSID 0x0001 /* Scan all ESSIDs */
#define IW_SCAN_THIS_ESSID 0x0002 /* Scan only this ESSID */
#define IW_SCAN_ALL_FREQ 0x0004 /* Scan all Frequencies */
#define IW_SCAN_THIS_FREQ 0x0008 /* Scan only this Frequency */
#define IW_SCAN_ALL_MODE 0x0010 /* Scan all Modes */
#define IW_SCAN_THIS_MODE 0x0020 /* Scan only this Mode */
#define IW_SCAN_ALL_RATE 0x0040 /* Scan all Bit-Rates */
#define IW_SCAN_THIS_RATE 0x0080 /* Scan only this Bit-Rate */
/* struct iw_scan_req scan_type */
#define IW_SCAN_TYPE_ACTIVE 0
#define IW_SCAN_TYPE_PASSIVE 1
/* Maximum size of returned data */
#define IW_SCAN_MAX_DATA 4096 /* In bytes */
/* Scan capability flags - in (struct iw_range *)->scan_capa */
#define IW_SCAN_CAPA_NONE 0x00
#define IW_SCAN_CAPA_ESSID 0x01
#define IW_SCAN_CAPA_BSSID 0x02
#define IW_SCAN_CAPA_CHANNEL 0x04
#define IW_SCAN_CAPA_MODE 0x08
#define IW_SCAN_CAPA_RATE 0x10
#define IW_SCAN_CAPA_TYPE 0x20
#define IW_SCAN_CAPA_TIME 0x40
/* Max number of char in custom event - use multiple of them if needed */
#define IW_CUSTOM_MAX 256 /* In bytes */
/* Generic information element */
#define IW_GENERIC_IE_MAX 1024
/* MLME requests (SIOCSIWMLME / struct iw_mlme) */
#define IW_MLME_DEAUTH 0
#define IW_MLME_DISASSOC 1
#define IW_MLME_AUTH 2
#define IW_MLME_ASSOC 3
/* SIOCSIWAUTH/SIOCGIWAUTH struct iw_param flags */
#define IW_AUTH_INDEX 0x0FFF
#define IW_AUTH_FLAGS 0xF000
/* SIOCSIWAUTH/SIOCGIWAUTH parameters (0 .. 4095)
* (IW_AUTH_INDEX mask in struct iw_param flags; this is the index of the
* parameter that is being set/get to; value will be read/written to
* struct iw_param value field) */
#define IW_AUTH_WPA_VERSION 0
#define IW_AUTH_CIPHER_PAIRWISE 1
#define IW_AUTH_CIPHER_GROUP 2
#define IW_AUTH_KEY_MGMT 3
#define IW_AUTH_TKIP_COUNTERMEASURES 4
#define IW_AUTH_DROP_UNENCRYPTED 5
#define IW_AUTH_80211_AUTH_ALG 6
#define IW_AUTH_WPA_ENABLED 7
#define IW_AUTH_RX_UNENCRYPTED_EAPOL 8
#define IW_AUTH_ROAMING_CONTROL 9
#define IW_AUTH_PRIVACY_INVOKED 10
#define IW_AUTH_CIPHER_GROUP_MGMT 11
#define IW_AUTH_MFP 12
/* IW_AUTH_WPA_VERSION values (bit field) */
#define IW_AUTH_WPA_VERSION_DISABLED 0x00000001
#define IW_AUTH_WPA_VERSION_WPA 0x00000002
#define IW_AUTH_WPA_VERSION_WPA2 0x00000004
/* IW_AUTH_PAIRWISE_CIPHER, IW_AUTH_GROUP_CIPHER, and IW_AUTH_CIPHER_GROUP_MGMT
* values (bit field) */
#define IW_AUTH_CIPHER_NONE 0x00000001
#define IW_AUTH_CIPHER_WEP40 0x00000002
#define IW_AUTH_CIPHER_TKIP 0x00000004
#define IW_AUTH_CIPHER_CCMP 0x00000008
#define IW_AUTH_CIPHER_WEP104 0x00000010
#define IW_AUTH_CIPHER_AES_CMAC 0x00000020
/* IW_AUTH_KEY_MGMT values (bit field) */
#define IW_AUTH_KEY_MGMT_802_1X 1
#define IW_AUTH_KEY_MGMT_PSK 2
/* IW_AUTH_80211_AUTH_ALG values (bit field) */
#define IW_AUTH_ALG_OPEN_SYSTEM 0x00000001
#define IW_AUTH_ALG_SHARED_KEY 0x00000002
#define IW_AUTH_ALG_LEAP 0x00000004
/* IW_AUTH_ROAMING_CONTROL values */
#define IW_AUTH_ROAMING_ENABLE 0 /* driver/firmware based roaming */
#define IW_AUTH_ROAMING_DISABLE 1 /* user space program used for roaming
* control */
/* IW_AUTH_MFP (management frame protection) values */
#define IW_AUTH_MFP_DISABLED 0 /* MFP disabled */
#define IW_AUTH_MFP_OPTIONAL 1 /* MFP optional */
#define IW_AUTH_MFP_REQUIRED 2 /* MFP required */
/* SIOCSIWENCODEEXT definitions */
#define IW_ENCODE_SEQ_MAX_SIZE 8
/* struct iw_encode_ext ->alg */
#define IW_ENCODE_ALG_NONE 0
#define IW_ENCODE_ALG_WEP 1
#define IW_ENCODE_ALG_TKIP 2
#define IW_ENCODE_ALG_CCMP 3
#define IW_ENCODE_ALG_PMK 4
#define IW_ENCODE_ALG_AES_CMAC 5
/* struct iw_encode_ext ->ext_flags */
#define IW_ENCODE_EXT_TX_SEQ_VALID 0x00000001
#define IW_ENCODE_EXT_RX_SEQ_VALID 0x00000002
#define IW_ENCODE_EXT_GROUP_KEY 0x00000004
#define IW_ENCODE_EXT_SET_TX_KEY 0x00000008
/* IWEVMICHAELMICFAILURE : struct iw_michaelmicfailure ->flags */
#define IW_MICFAILURE_KEY_ID 0x00000003 /* Key ID 0..3 */
#define IW_MICFAILURE_GROUP 0x00000004
#define IW_MICFAILURE_PAIRWISE 0x00000008
#define IW_MICFAILURE_STAKEY 0x00000010
#define IW_MICFAILURE_COUNT 0x00000060 /* 1 or 2 (0 = count not supported)
*/
/* Bit field values for enc_capa in struct iw_range */
#define IW_ENC_CAPA_WPA 0x00000001
#define IW_ENC_CAPA_WPA2 0x00000002
#define IW_ENC_CAPA_CIPHER_TKIP 0x00000004
#define IW_ENC_CAPA_CIPHER_CCMP 0x00000008
#define IW_ENC_CAPA_4WAY_HANDSHAKE 0x00000010
/* Event capability macros - in (struct iw_range *)->event_capa
* Because we have more than 32 possible events, we use an array of
* 32 bit bitmasks. Note : 32 bits = 0x20 = 2^5. */
#define IW_EVENT_CAPA_BASE(cmd) ((cmd >= SIOCIWFIRSTPRIV) ? \
(cmd - SIOCIWFIRSTPRIV + 0x60) : \
(cmd - SIOCIWFIRST))
#define IW_EVENT_CAPA_INDEX(cmd) (IW_EVENT_CAPA_BASE(cmd) >> 5)
#define IW_EVENT_CAPA_MASK(cmd) (1 << (IW_EVENT_CAPA_BASE(cmd) & 0x1F))
/* Event capability constants - event autogenerated by the kernel
* This list is valid for most 802.11 devices, customise as needed... */
#define IW_EVENT_CAPA_K_0 (IW_EVENT_CAPA_MASK(0x8B04) | \
IW_EVENT_CAPA_MASK(0x8B06) | \
IW_EVENT_CAPA_MASK(0x8B1A))
#define IW_EVENT_CAPA_K_1 (IW_EVENT_CAPA_MASK(0x8B2A))
/* "Easy" macro to set events in iw_range (less efficient) */
#define IW_EVENT_CAPA_SET(event_capa, cmd) (event_capa[IW_EVENT_CAPA_INDEX(cmd)] |= IW_EVENT_CAPA_MASK(cmd))
#define IW_EVENT_CAPA_SET_KERNEL(event_capa) {event_capa[0] |= IW_EVENT_CAPA_K_0; event_capa[1] |= IW_EVENT_CAPA_K_1; }
/****************************** TYPES ******************************/
/* --------------------------- SUBTYPES --------------------------- */
/*
* Generic format for most parameters that fit in an int
*/
struct iw_param {
__s32 value; /* The value of the parameter itself */
__u8 fixed; /* Hardware should not use auto select */
__u8 disabled; /* Disable the feature */
__u16 flags; /* Various specifc flags (if any) */
};
/*
* For all data larger than 16 octets, we need to use a
* pointer to memory allocated in user space.
*/
struct iw_point {
void *pointer; /* Pointer to the data (in user space) */
__u16 length; /* number of fields or size in bytes */
__u16 flags; /* Optional params */
};
/*
* A frequency
* For numbers lower than 10^9, we encode the number in 'm' and
* set 'e' to 0
* For number greater than 10^9, we divide it by the lowest power
* of 10 to get 'm' lower than 10^9, with 'm'= f / (10^'e')...
* The power of 10 is in 'e', the result of the division is in 'm'.
*/
struct iw_freq {
__s32 m; /* Mantissa */
__s16 e; /* Exponent */
__u8 i; /* List index (when in range struct) */
__u8 flags; /* Flags (fixed/auto) */
};
/*
* Quality of the link
*/
struct iw_quality {
__u8 qual; /* link quality (%retries, SNR,
%missed beacons or better...) */
__u8 level; /* signal level (dBm) */
__u8 noise; /* noise level (dBm) */
__u8 updated; /* Flags to know if updated */
};
/*
* Packet discarded in the wireless adapter due to
* "wireless" specific problems...
* Note : the list of counter and statistics in net_device_stats
* is already pretty exhaustive, and you should use that first.
* This is only additional stats...
*/
struct iw_discarded {
__u32 nwid; /* Rx : Wrong nwid/essid */
__u32 code; /* Rx : Unable to code/decode (WEP) */
__u32 fragment; /* Rx : Can't perform MAC reassembly */
__u32 retries; /* Tx : Max MAC retries num reached */
__u32 misc; /* Others cases */
};
/*
* Packet/Time period missed in the wireless adapter due to
* "wireless" specific problems...
*/
struct iw_missed {
__u32 beacon; /* Missed beacons/superframe */
};
/*
* Quality range (for spy threshold)
*/
struct iw_thrspy {
struct sockaddr addr; /* Source address (hw/mac) */
struct iw_quality qual; /* Quality of the link */
struct iw_quality low; /* Low threshold */
struct iw_quality high; /* High threshold */
};
/*
* Optional data for scan request
*
* Note: these optional parameters are controlling parameters for the
* scanning behavior, these do not apply to getting scan results
* (SIOCGIWSCAN). Drivers are expected to keep a local BSS table and
* provide a merged results with all BSSes even if the previous scan
* request limited scanning to a subset, e.g., by specifying an SSID.
* Especially, scan results are required to include an entry for the
* current BSS if the driver is in Managed mode and associated with an AP.
*/
struct iw_scan_req {
__u8 scan_type; /* IW_SCAN_TYPE_{ACTIVE,PASSIVE} */
__u8 essid_len;
__u8 num_channels; /* num entries in channel_list;
* 0 = scan all allowed channels */
__u8 flags; /* reserved as padding; use zero, this may
* be used in the future for adding flags
* to request different scan behavior */
struct sockaddr bssid; /* ff:ff:ff:ff:ff:ff for broadcast BSSID or
* individual address of a specific BSS */
/*
* Use this ESSID if IW_SCAN_THIS_ESSID flag is used instead of using
* the current ESSID. This allows scan requests for specific ESSID
* without having to change the current ESSID and potentially breaking
* the current association.
*/
__u8 essid[IW_ESSID_MAX_SIZE];
/*
* Optional parameters for changing the default scanning behavior.
* These are based on the MLME-SCAN.request from IEEE Std 802.11.
* TU is 1.024 ms. If these are set to 0, driver is expected to use
* reasonable default values. min_channel_time defines the time that
* will be used to wait for the first reply on each channel. If no
* replies are received, next channel will be scanned after this. If
* replies are received, total time waited on the channel is defined by
* max_channel_time.
*/
__u32 min_channel_time; /* in TU */
__u32 max_channel_time; /* in TU */
struct iw_freq channel_list[IW_MAX_FREQUENCIES];
};
/* ------------------------- WPA SUPPORT ------------------------- */
/*
* Extended data structure for get/set encoding (this is used with
* SIOCSIWENCODEEXT/SIOCGIWENCODEEXT. struct iw_point and IW_ENCODE_*
* flags are used in the same way as with SIOCSIWENCODE/SIOCGIWENCODE and
* only the data contents changes (key data -> this structure, including
* key data).
*
* If the new key is the first group key, it will be set as the default
* TX key. Otherwise, default TX key index is only changed if
* IW_ENCODE_EXT_SET_TX_KEY flag is set.
*
* Key will be changed with SIOCSIWENCODEEXT in all cases except for
* special "change TX key index" operation which is indicated by setting
* key_len = 0 and ext_flags |= IW_ENCODE_EXT_SET_TX_KEY.
*
* tx_seq/rx_seq are only used when respective
* IW_ENCODE_EXT_{TX,RX}_SEQ_VALID flag is set in ext_flags. Normal
* TKIP/CCMP operation is to set RX seq with SIOCSIWENCODEEXT and start
* TX seq from zero whenever key is changed. SIOCGIWENCODEEXT is normally
* used only by an Authenticator (AP or an IBSS station) to get the
* current TX sequence number. Using TX_SEQ_VALID for SIOCSIWENCODEEXT and
* RX_SEQ_VALID for SIOCGIWENCODEEXT are optional, but can be useful for
* debugging/testing.
*/
struct iw_encode_ext {
__u32 ext_flags; /* IW_ENCODE_EXT_* */
__u8 tx_seq[IW_ENCODE_SEQ_MAX_SIZE]; /* LSB first */
__u8 rx_seq[IW_ENCODE_SEQ_MAX_SIZE]; /* LSB first */
struct sockaddr addr; /* ff:ff:ff:ff:ff:ff for broadcast/multicast
* (group) keys or unicast address for
* individual keys */
__u16 alg; /* IW_ENCODE_ALG_* */
__u16 key_len;
__u8 key[0];
};
/* SIOCSIWMLME data */
struct iw_mlme {
__u16 cmd; /* IW_MLME_* */
__u16 reason_code;
struct sockaddr addr;
};
/* SIOCSIWPMKSA data */
#define IW_PMKSA_ADD 1
#define IW_PMKSA_REMOVE 2
#define IW_PMKSA_FLUSH 3
#define IW_PMKID_LEN 16
struct iw_pmksa {
__u32 cmd; /* IW_PMKSA_* */
struct sockaddr bssid;
__u8 pmkid[IW_PMKID_LEN];
};
/* IWEVMICHAELMICFAILURE data */
struct iw_michaelmicfailure {
__u32 flags;
struct sockaddr src_addr;
__u8 tsc[IW_ENCODE_SEQ_MAX_SIZE]; /* LSB first */
};
/* IWEVPMKIDCAND data */
#define IW_PMKID_CAND_PREAUTH 0x00000001 /* RNS pre-authentication enabled */
struct iw_pmkid_cand {
__u32 flags; /* IW_PMKID_CAND_* */
__u32 index; /* the smaller the index, the higher the
* priority */
struct sockaddr bssid;
};
/* ------------------------ WIRELESS STATS ------------------------ */
/*
* Wireless statistics (used for /proc/net/wireless)
*/
struct iw_statistics {
__u16 status; /* Status
* - device dependent for now */
struct iw_quality qual; /* Quality of the link
* (instant/mean/max) */
struct iw_discarded discard; /* Packet discarded counts */
struct iw_missed miss; /* Packet missed counts */
};
/* ------------------------ IOCTL REQUEST ------------------------ */
/*
* This structure defines the payload of an ioctl, and is used
* below.
*
* Note that this structure should fit on the memory footprint
* of iwreq (which is the same as ifreq), which mean a max size of
* 16 octets = 128 bits. Warning, pointers might be 64 bits wide...
* You should check this when increasing the structures defined
* above in this file...
*/
union iwreq_data {
/* Config - generic */
char name[IFNAMSIZ];
/* Name : used to verify the presence of wireless extensions.
* Name of the protocol/provider... */
struct iw_point essid; /* Extended network name */
struct iw_param nwid; /* network id (or domain - the cell) */
struct iw_freq freq; /* frequency or channel :
* 0-1000 = channel
* > 1000 = frequency in Hz */
struct iw_param sens; /* signal level threshold */
struct iw_param bitrate; /* default bit rate */
struct iw_param txpower; /* default transmit power */
struct iw_param rts; /* RTS threshold threshold */
struct iw_param frag; /* Fragmentation threshold */
__u32 mode; /* Operation mode */
struct iw_param retry; /* Retry limits & lifetime */
struct iw_point encoding; /* Encoding stuff : tokens */
struct iw_param power; /* PM duration/timeout */
struct iw_quality qual; /* Quality part of statistics */
struct sockaddr ap_addr; /* Access point address */
struct sockaddr addr; /* Destination address (hw/mac) */
struct iw_param param; /* Other small parameters */
struct iw_point data; /* Other large parameters */
};
/*
* The structure to exchange data for ioctl.
* This structure is the same as 'struct ifreq', but (re)defined for
* convenience...
* Do I need to remind you about structure size (32 octets) ?
*/
struct iwreq {
union
{
char ifrn_name[IFNAMSIZ]; /* if name, e.g. "eth0" */
} ifr_ifrn;
/* Data part (defined just above) */
union iwreq_data u;
};
/* -------------------------- IOCTL DATA -------------------------- */
/*
* For those ioctl which want to exchange mode data that what could
* fit in the above structure...
*/
/*
* Range of parameters
*/
struct iw_range {
/* Informative stuff (to choose between different interface) */
__u32 throughput; /* To give an idea... */
/* In theory this value should be the maximum benchmarked
* TCP/IP throughput, because with most of these devices the
* bit rate is meaningless (overhead an co) to estimate how
* fast the connection will go and pick the fastest one.
* I suggest people to play with Netperf or any benchmark...
*/
/* NWID (or domain id) */
__u32 min_nwid; /* Minimal NWID we are able to set */
__u32 max_nwid; /* Maximal NWID we are able to set */
/* Old Frequency (backward compat - moved lower ) */
__u16 old_num_channels;
__u8 old_num_frequency;
/* Scan capabilities */
__u8 scan_capa; /* IW_SCAN_CAPA_* bit field */
/* Wireless event capability bitmasks */
__u32 event_capa[6];
/* signal level threshold range */
__s32 sensitivity;
/* Quality of link & SNR stuff */
/* Quality range (link, level, noise)
* If the quality is absolute, it will be in the range [0 ; max_qual],
* if the quality is dBm, it will be in the range [max_qual ; 0].
* Don't forget that we use 8 bit arithmetics... */
struct iw_quality max_qual; /* Quality of the link */
/* This should contain the average/typical values of the quality
* indicator. This should be the threshold between a "good" and
* a "bad" link (example : monitor going from green to orange).
* Currently, user space apps like quality monitors don't have any
* way to calibrate the measurement. With this, they can split
* the range between 0 and max_qual in different quality level
* (using a geometric subdivision centered on the average).
* I expect that people doing the user space apps will feedback
* us on which value we need to put in each driver... */
struct iw_quality avg_qual; /* Quality of the link */
/* Rates */
__u8 num_bitrates; /* Number of entries in the list */
__s32 bitrate[IW_MAX_BITRATES]; /* list, in bps */
/* RTS threshold */
__s32 min_rts; /* Minimal RTS threshold */
__s32 max_rts; /* Maximal RTS threshold */
/* Frag threshold */
__s32 min_frag; /* Minimal frag threshold */
__s32 max_frag; /* Maximal frag threshold */
/* Power Management duration & timeout */
__s32 min_pmp; /* Minimal PM period */
__s32 max_pmp; /* Maximal PM period */
__s32 min_pmt; /* Minimal PM timeout */
__s32 max_pmt; /* Maximal PM timeout */
__u16 pmp_flags; /* How to decode max/min PM period */
__u16 pmt_flags; /* How to decode max/min PM timeout */
__u16 pm_capa; /* What PM options are supported */
/* Encoder stuff */
__u16 encoding_size[IW_MAX_ENCODING_SIZES]; /* Different token sizes */
__u8 num_encoding_sizes; /* Number of entry in the list */
__u8 max_encoding_tokens; /* Max number of tokens */
/* For drivers that need a "login/passwd" form */
__u8 encoding_login_index; /* token index for login token */
/* Transmit power */
__u16 txpower_capa; /* What options are supported */
__u8 num_txpower; /* Number of entries in the list */
__s32 txpower[IW_MAX_TXPOWER]; /* list, in bps */
/* Wireless Extension version info */
__u8 we_version_compiled; /* Must be WIRELESS_EXT */
__u8 we_version_source; /* Last update of source */
/* Retry limits and lifetime */
__u16 retry_capa; /* What retry options are supported */
__u16 retry_flags; /* How to decode max/min retry limit */
__u16 r_time_flags; /* How to decode max/min retry life */
__s32 min_retry; /* Minimal number of retries */
__s32 max_retry; /* Maximal number of retries */
__s32 min_r_time; /* Minimal retry lifetime */
__s32 max_r_time; /* Maximal retry lifetime */
/* Frequency */
__u16 num_channels; /* Number of channels [0; num - 1] */
__u8 num_frequency; /* Number of entry in the list */
struct iw_freq freq[IW_MAX_FREQUENCIES]; /* list */
/* Note : this frequency list doesn't need to fit channel numbers,
* because each entry contain its channel index */
__u32 enc_capa; /* IW_ENC_CAPA_* bit field */
};
/*
* Private ioctl interface information
*/
struct iw_priv_args {
__u32 cmd; /* Number of the ioctl to issue */
__u16 set_args; /* Type and number of args */
__u16 get_args; /* Type and number of args */
char name[IFNAMSIZ]; /* Name of the extension */
};
/* ----------------------- WIRELESS EVENTS ----------------------- */
/*
* Wireless events are carried through the rtnetlink socket to user
* space. They are encapsulated in the IFLA_WIRELESS field of
* a RTM_NEWLINK message.
*/
/*
* A Wireless Event. Contains basically the same data as the ioctl...
*/
struct iw_event {
__u16 len; /* Real length of this stuff */
__u16 cmd; /* Wireless IOCTL */
union iwreq_data u; /* IOCTL fixed payload */
};
/* Size of the Event prefix (including padding and alignement junk) */
#define IW_EV_LCP_LEN (sizeof(struct iw_event) - sizeof(union iwreq_data))
/* Size of the various events */
#define IW_EV_CHAR_LEN (IW_EV_LCP_LEN + IFNAMSIZ)
#define IW_EV_UINT_LEN (IW_EV_LCP_LEN + sizeof(__u32))
#define IW_EV_FREQ_LEN (IW_EV_LCP_LEN + sizeof(struct iw_freq))
#define IW_EV_PARAM_LEN (IW_EV_LCP_LEN + sizeof(struct iw_param))
#define IW_EV_ADDR_LEN (IW_EV_LCP_LEN + sizeof(struct sockaddr))
#define IW_EV_QUAL_LEN (IW_EV_LCP_LEN + sizeof(struct iw_quality))
/* iw_point events are special. First, the payload (extra data) come at
* the end of the event, so they are bigger than IW_EV_POINT_LEN. Second,
* we omit the pointer, so start at an offset. */
#define IW_EV_POINT_OFF (((char *) &(((struct iw_point *) NULL)->length)) - \
(char *) NULL)
#define IW_EV_POINT_LEN (IW_EV_LCP_LEN + sizeof(struct iw_point) - \
IW_EV_POINT_OFF)
/* Size of the Event prefix when packed in stream */
#define IW_EV_LCP_PK_LEN (4)
/* Size of the various events when packed in stream */
#define IW_EV_CHAR_PK_LEN (IW_EV_LCP_PK_LEN + IFNAMSIZ)
#define IW_EV_UINT_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(__u32))
#define IW_EV_FREQ_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(struct iw_freq))
#define IW_EV_PARAM_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(struct iw_param))
#define IW_EV_ADDR_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(struct sockaddr))
#define IW_EV_QUAL_PK_LEN (IW_EV_LCP_PK_LEN + sizeof(struct iw_quality))
#define IW_EV_POINT_PK_LEN (IW_EV_LCP_PK_LEN + 4)
#endif /* _LINUX_WIRELESS_H */
`
// This is the standard Unix style binary blob interface with all the
// conversion fun that implies. Bummer.
/*
* This file define a set of standard wireless extensions
*
* Version : 22 16.3.07
*
* Authors : Jean Tourrilhes - HPL - <jt@hpl.hp.com>
* Copyright (c) 1997-2007 Jean Tourrilhes, All Rights Reserved.
*/
/************************** DOCUMENTATION **************************/
/*
* Initial APIs (1996 -> onward) :
* -----------------------------
* Basically, the wireless extensions are for now a set of standard ioctl
* call + /proc/net/wireless
*
* The entry /proc/net/wireless give statistics and information on the
* driver.
* This is better than having each driver having its entry because
* its centralised and we may remove the driver module safely.
*
* Ioctl are used to configure the driver and issue commands. This is
* better than command line options of insmod because we may want to
* change dynamically (while the driver is running) some parameters.
*
* The ioctl mechanimsm are copied from standard devices ioctl.
* We have the list of command plus a structure descibing the
* data exchanged...
* Note that to add these ioctl, I was obliged to modify :
* # net/core/dev.c (two place + add include)
* # net/ipv4/af_inet.c (one place + add include)
*
* /proc/net/wireless is a copy of /proc/net/dev.
* We have a structure for data passed from the driver to /proc/net/wireless
* Too add this, I've modified :
* # net/core/dev.c (two other places)
* # include/linux/netdevice.h (one place)
* # include/linux/proc_fs.h (one place)
*
* New driver API (2002 -> onward) :
* -------------------------------
* This file is only concerned with the user space API and common definitions.
* The new driver API is defined and documented in :
* # include/net/iw_handler.h
*
* Note as well that /proc/net/wireless implementation has now moved in :
* # net/core/wireless.c
*
* Wireless Events (2002 -> onward) :
* --------------------------------
* Events are defined at the end of this file, and implemented in :
* # net/core/wireless.c
*
* Other comments :
* --------------
* Do not add here things that are redundant with other mechanisms
* (drivers init, ifconfig, /proc/net/dev, ...) and with are not
* wireless specific.
*
* These wireless extensions are not magic : each driver has to provide
* support for them...
*
* IMPORTANT NOTE : As everything in the kernel, this is very much a
* work in progress. Contact me if you have ideas of improvements...
*/
/***************************** VERSION *****************************/
/*
* This constant is used to know the availability of the wireless
* extensions and to know which version of wireless extensions it is
* (there is some stuff that will be added in the future...)
* I just plan to increment with each new version.
*/
const WIRELESS_EXT = 22
/*
* Changes :
*
* V2 to V3
* --------
* Alan Cox start some incompatibles changes. I've integrated a bit more.
* - Encryption renamed to Encode to avoid US regulation problems
* - Frequency changed from float to struct to avoid problems on old 386
*
* V3 to V4
* --------
* - Add sensitivity
*
* V4 to V5
* --------
* - Missing encoding definitions in range
* - Access points stuff
*
* V5 to V6
* --------
* - 802.11 support (ESSID ioctls)
*
* V6 to V7
* --------
* - define IW_ESSID_MAX_SIZE and IW_MAX_AP
*
* V7 to V8
* --------
* - Changed my e-mail address
* - More 802.11 support (nickname, rate, rts, frag)
* - List index in frequencies
*
* V8 to V9
* --------
* - Support for 'mode of operation' (ad-hoc, managed...)
* - Support for unicast and multicast power saving
* - Change encoding to support larger tokens (>64 bits)
* - Updated iw_params (disable, flags) and use it for NWID
* - Extracted iw_point from iwreq for clarity
*
* V9 to V10
* ---------
* - Add PM capability to range structure
* - Add PM modifier : MAX/MIN/RELATIVE
* - Add encoding option : IW_ENCODE_NOKEY
* - Add TxPower ioctls (work like TxRate)
*
* V10 to V11
* ----------
* - Add WE version in range (help backward/forward compatibility)
* - Add retry ioctls (work like PM)
*
* V11 to V12
* ----------
* - Add SIOCSIWSTATS to get /proc/net/wireless programatically
* - Add DEV PRIVATE IOCTL to avoid collisions in SIOCDEVPRIVATE space
* - Add new statistics (frag, retry, beacon)
* - Add average quality (for user space calibration)
*
* V12 to V13
* ----------
* - Document creation of new driver API.
* - Extract union iwreq_data from struct iwreq (for new driver API).
* - Rename SIOCSIWNAME as SIOCSIWCOMMIT
*
* V13 to V14
* ----------
* - Wireless Events support : define struct iw_event
* - Define additional specific event numbers
* - Add "addr" and "param" fields in union iwreq_data
* - AP scanning stuff (SIOCSIWSCAN and friends)
*
* V14 to V15
* ----------
* - Add IW_PRIV_TYPE_ADDR for struct sockaddr private arg
* - Make struct iw_freq signed (both m & e), add explicit padding
* - Add IWEVCUSTOM for driver specific event/scanning token
* - Add IW_MAX_GET_SPY for driver returning a lot of addresses
* - Add IW_TXPOW_RANGE for range of Tx Powers
* - Add IWEVREGISTERED & IWEVEXPIRED events for Access Points
* - Add IW_MODE_MONITOR for passive monitor
*
* V15 to V16
* ----------
* - Increase the number of bitrates in iw_range to 32 (for 802.11g)
* - Increase the number of frequencies in iw_range to 32 (for 802.11b+a)
* - Reshuffle struct iw_range for increases, add filler
* - Increase IW_MAX_AP to 64 for driver returning a lot of addresses
* - Remove IW_MAX_GET_SPY because conflict with enhanced spy support
* - Add SIOCSIWTHRSPY/SIOCGIWTHRSPY and "struct iw_thrspy"
* - Add IW_ENCODE_TEMP and iw_range->encoding_login_index
*
* V16 to V17
* ----------
* - Add flags to frequency -> auto/fixed
* - Document (struct iw_quality *)->updated, add new flags (INVALID)
* - Wireless Event capability in struct iw_range
* - Add support for relative TxPower (yick !)
*
* V17 to V18 (From Jouni Malinen <j@w1.fi>)
* ----------
* - Add support for WPA/WPA2
* - Add extended encoding configuration (SIOCSIWENCODEEXT and
* SIOCGIWENCODEEXT)
* - Add SIOCSIWGENIE/SIOCGIWGENIE
* - Add SIOCSIWMLME
* - Add SIOCSIWPMKSA
* - Add struct iw_range bit field for supported encoding capabilities
* - Add optional scan request parameters for SIOCSIWSCAN
* - Add SIOCSIWAUTH/SIOCGIWAUTH for setting authentication and WPA
* related parameters (extensible up to 4096 parameter values)
* - Add wireless events: IWEVGENIE, IWEVMICHAELMICFAILURE,
* IWEVASSOCREQIE, IWEVASSOCRESPIE, IWEVPMKIDCAND
*
* V18 to V19
* ----------
* - Remove (struct iw_point *)->pointer from events and streams
* - Remove header includes to help user space
* - Increase IW_ENCODING_TOKEN_MAX from 32 to 64
* - Add IW_QUAL_ALL_UPDATED and IW_QUAL_ALL_INVALID macros
* - Add explicit flag to tell stats are in dBm : IW_QUAL_DBM
* - Add IW_IOCTL_IDX() and IW_EVENT_IDX() macros
*
* V19 to V20
* ----------
* - RtNetlink requests support (SET/GET)
*
* V20 to V21
* ----------
* - Remove (struct net_device *)->get_wireless_stats()
* - Change length in ESSID and NICK to strlen() instead of strlen()+1
* - Add IW_RETRY_SHORT/IW_RETRY_LONG retry modifiers
* - Power/Retry relative values no longer * 100000
* - Add explicit flag to tell stats are in 802.11k RCPI : IW_QUAL_RCPI
*
* V21 to V22
* ----------
* - Prevent leaking of kernel space in stream on 64 bits.
*/
/**************************** CONSTANTS ****************************/
/* -------------------------- IOCTL LIST -------------------------- */
/* Wireless Identification */
const SIOCSIWCOMMIT = 0x8B00 /* Commit pending changes to driver */
const SIOCGIWNAME = 0x8B01 /* get name == wireless protocol */
/* SIOCGIWNAME is used to verify the presence of Wireless Extensions.
* Common values : "IEEE 802.11-DS", "IEEE 802.11-FH", "IEEE 802.11b"...
* Don't put the name of your driver there, it's useless. */
/* Basic operations */
const SIOCSIWNWID = 0x8B02 /* set network id (pre-802.11) */
const SIOCGIWNWID = 0x8B03 /* get network id (the cell) */
const SIOCSIWFREQ = 0x8B04 /* set channel/frequency (Hz) */
const SIOCGIWFREQ = 0x8B05 /* get channel/frequency (Hz) */
const SIOCSIWMODE = 0x8B06 /* set operation mode */
const SIOCGIWMODE = 0x8B07 /* get operation mode */
const SIOCSIWSENS = 0x8B08 /* set sensitivity (dBm) */
const SIOCGIWSENS = 0x8B09 /* get sensitivity (dBm) */
/* Informative stuff */
const SIOCSIWRANGE = 0x8B0A /* Unused */
const SIOCGIWRANGE = 0x8B0B /* Get range of parameters */
const SIOCSIWPRIV = 0x8B0C /* Unused */
const SIOCGIWPRIV = 0x8B0D /* get private ioctl interface info */
const SIOCSIWSTATS = 0x8B0E /* Unused */
const SIOCGIWSTATS = 0x8B0F /* Get /proc/net/wireless stats */
/* SIOCGIWSTATS is strictly used between user space and the kernel, and
* is never passed to the driver (i.e. the driver will never see it). */
/* Spy support (statistics per MAC address - used for Mobile IP support) */
const SIOCSIWSPY = 0x8B10 /* set spy addresses */
const SIOCGIWSPY = 0x8B11 /* get spy info (quality of link) */
const SIOCSIWTHRSPY = 0x8B12 /* set spy threshold (spy event) */
const SIOCGIWTHRSPY = 0x8B13 /* get spy threshold */
/* Access Point manipulation */
const SIOCSIWAP = 0x8B14 /* set access point MAC addresses */
const SIOCGIWAP = 0x8B15 /* get access point MAC addresses */
const SIOCGIWAPLIST = 0x8B17 /* Deprecated in favor of scanning */
const SIOCSIWSCAN = 0x8B18 /* trigger scanning (list cells) */
const SIOCGIWSCAN = 0x8B19 /* get scanning results */
/* 802.11 specific support */
const SIOCSIWESSID = 0x8B1A /* set ESSID (network name) */
const SIOCGIWESSID = 0x8B1B /* get ESSID */
const SIOCSIWNICKN = 0x8B1C /* set node name/nickname */
const SIOCGIWNICKN = 0x8B1D /* get node name/nickname */
/* As the ESSID and NICKN are strings up to 32 bytes long, it doesn't fit
* within the 'iwreq' structure, so we need to use the 'data' member to
* point to a string in user space, like it is done for RANGE... */
/* Other parameters useful in 802.11 and some other devices */
const SIOCSIWRATE = 0x8B20 /* set default bit rate (bps) */
const SIOCGIWRATE = 0x8B21 /* get default bit rate (bps) */
const SIOCSIWRTS = 0x8B22 /* set RTS/CTS threshold (bytes) */
const SIOCGIWRTS = 0x8B23 /* get RTS/CTS threshold (bytes) */
const SIOCSIWFRAG = 0x8B24 /* set fragmentation thr (bytes) */
const SIOCGIWFRAG = 0x8B25 /* get fragmentation thr (bytes) */
const SIOCSIWTXPOW = 0x8B26 /* set transmit power (dBm) */
const SIOCGIWTXPOW = 0x8B27 /* get transmit power (dBm) */
const SIOCSIWRETRY = 0x8B28 /* set retry limits and lifetime */
const SIOCGIWRETRY = 0x8B29 /* get retry limits and lifetime */
/* Encoding stuff (scrambling, hardware security, WEP...) */
const SIOCSIWENCODE = 0x8B2A /* set encoding token & mode */
const SIOCGIWENCODE = 0x8B2B /* get encoding token & mode */
/* Power saving stuff (power management, unicast and multicast) */
const SIOCSIWPOWER = 0x8B2C /* set Power Management settings */
const SIOCGIWPOWER = 0x8B2D /* get Power Management settings */
/* WPA : Generic IEEE 802.11 informatiom element (e.g., for WPA/RSN/WMM).
* This ioctl uses struct iw_point and data buffer that includes IE id and len
* fields. More than one IE may be included in the request. Setting the generic
* IE to empty buffer (len=0) removes the generic IE from the driver. Drivers
* are allowed to generate their own WPA/RSN IEs, but in these cases, drivers
* are required to report the used IE as a wireless event, e.g., when
* associating with an AP. */
const SIOCSIWGENIE = 0x8B30 /* set generic IE */
const SIOCGIWGENIE = 0x8B31 /* get generic IE */
/* WPA : IEEE 802.11 MLME requests */
const SIOCSIWMLME = 0x8B16 /* request MLME operation; uses
* struct iw_mlme */
/* WPA : Authentication mode parameters */
const SIOCSIWAUTH = 0x8B32 /* set authentication mode params */
const SIOCGIWAUTH = 0x8B33 /* get authentication mode params */
/* WPA : Extended version of encoding configuration */
const SIOCSIWENCODEEXT = 0x8B34 /* set encoding token & mode */
const SIOCGIWENCODEEXT = 0x8B35 /* get encoding token & mode */
/* WPA2 : PMKSA cache management */
const SIOCSIWPMKSA = 0x8B36 /* PMKSA cache operation */
/* -------------------- DEV PRIVATE IOCTL LIST -------------------- */
/* These 32 ioctl are wireless device private, for 16 commands.
* Each driver is free to use them for whatever purpose it chooses,
* however the driver *must* export the description of those ioctls
* with SIOCGIWPRIV and *must* use arguments as defined below.
* If you don't follow those rules, DaveM is going to hate you (reason :
* it make mixed 32/64bit operation impossible).
*/
const SIOCIWFIRSTPRIV = 0x8BE0
const SIOCIWLASTPRIV = 0x8BFF
/* Previously, we were using SIOCDEVPRIVATE, but we now have our
* separate range because of collisions with other tools such as
* 'mii-tool'.
* We now have 32 commands, so a bit more space ;-).
* Also, all 'even' commands are only usable by root and don't return the
* content of ifr/iwr to user (but you are not obliged to use the set/get
* convention, just use every other two command). More details in iwpriv.c.
* And I repeat : you are not forced to use them with iwpriv, but you
* must be compliant with it.
*/
/* ------------------------- IOCTL STUFF ------------------------- */
/* The first and the last (range) */
const SIOCIWFIRST = 0x8B00
const SIOCIWLAST = SIOCIWLASTPRIV /* 0x8BFF */
//const IW_IOCTL_IDX(cmd) = ((cmd) - SIOCIWFIRST)
//const IW_HANDLER(id, = func) [IW_IOCTL_IDX(id)] = func
// What is this stuff?
// Odd is right.
/* Odd : get (world access), even : set (root access) */
func IW_IS_SET(cmd uint32) bool {
return !(((cmd) & 0x1) != 0)
}
func IW_IS_GET(cmd uint32) bool {
return ((cmd) & 0x1) != 0
}
/* ----------------------- WIRELESS EVENTS ----------------------- */
/* Those are *NOT* ioctls, do not issue request on them !!! */
/* Most events use the same identifier as ioctl requests */
const IWEVTXDROP = 0x8C00 /* Packet dropped to excessive retry */
const IWEVQUAL = 0x8C01 /* Quality part of statistics (scan) */
const IWEVCUSTOM = 0x8C02 /* Driver specific ascii string */
const IWEVREGISTERED = 0x8C03 /* Discovered a new node (AP mode) */
const IWEVEXPIRED = 0x8C04 /* Expired a node (AP mode) */
const IWEVGENIE = 0x8C05 /* Generic IE (WPA, RSN, WMM, ..)
* (scan results); This includes id and
* length fields. One IWEVGENIE may
* contain more than one IE. Scan
* results may contain one or more
* IWEVGENIE events. */
const IWEVMICHAELMICFAILURE = 0x8C06 /* Michael MIC failure
* (struct iw_michaelmicfailure)
*/
const IWEVASSOCREQIE = 0x8C07 /* IEs used in (Re)Association Request.
* The data includes id and length
* fields and may contain more than one
* IE. This event is required in
* Managed mode if the driver
* generates its own WPA/RSN IE. This
* should be sent just before
* IWEVREGISTERED event for the
* association. */
const IWEVASSOCRESPIE = 0x8C08 /* IEs used in (Re)Association
* Response. The data includes id and
* length fields and may contain more
* than one IE. This may be sent
* between IWEVASSOCREQIE and
* IWEVREGISTERED events for the
* association. */
const IWEVPMKIDCAND = 0x8C09 /* PMKID candidate for RSN
* pre-authentication
* (struct iw_pmkid_cand) */
const IWEVFIRST = 0x8C00
func IW_EVENT_IDX(cmd uint32) uint32 {
return cmd - IWEVFIRST
}
/* ------------------------- PRIVATE INFO ------------------------- */
/*
* The following is used with SIOCGIWPRIV. It allow a driver to define
* the interface (name, type of data) for its private ioctl.
* Privates ioctl are SIOCIWFIRSTPRIV -> SIOCIWLASTPRIV
*/
const IW_PRIV_TYPE_MASK = 0x7000 /* Type of arguments */
const IW_PRIV_TYPE_NONE = 0x0000
const IW_PRIV_TYPE_BYTE = 0x1000 /* Char as number */
const IW_PRIV_TYPE_CHAR = 0x2000 /* Char as character */
const IW_PRIV_TYPE_INT = 0x4000 /* 32 bits int */
const IW_PRIV_TYPE_FLOAT = 0x5000 /* struct iw_freq */
const IW_PRIV_TYPE_ADDR = 0x6000 /* struct sockaddr */
const IW_PRIV_SIZE_FIXED = 0x0800 /* Variable or fixed number of args */
const IW_PRIV_SIZE_MASK = 0x07FF /* Max number of those args */
/*
* Note : if the number of args is fixed and the size < 16 octets,
* instead of passing a pointer we will put args in the iwreq struct...
*/
/* ----------------------- OTHER CONSTANTS ----------------------- */
/* Maximum frequencies in the range struct */
const IW_MAX_FREQUENCIES = 32
/* Note : if you have something like 80 frequencies,
* don't increase this constant and don't fill the frequency list.
* The user will be able to set by channel anyway... */
/* Maximum bit rates in the range struct */
const IW_MAX_BITRATES = 32
/* Maximum tx powers in the range struct */
const IW_MAX_TXPOWER = 8
/* Note : if you more than 8 TXPowers, just set the max and min or
* a few of them in the struct iw_range. */
/* Maximum of address that you may set with SPY */
const IW_MAX_SPY = 8
/* Maximum of address that you may get in the
list of access points in range */
const IW_MAX_AP = 64
/* Maximum size of the ESSID and NICKN strings */
const IW_ESSID_MAX_SIZE = 32
/* Modes of operation */
const IW_MODE_AUTO = 0 /* Let the driver decides */
const IW_MODE_ADHOC = 1 /* Single cell network */
const IW_MODE_INFRA = 2 /* Multi cell network, roaming, ... */
const IW_MODE_MASTER = 3 /* Synchronisation master or Access Point */
const IW_MODE_REPEAT = 4 /* Wireless Repeater (forwarder) */
const IW_MODE_SECOND = 5 /* Secondary master/repeater (backup) */
const IW_MODE_MONITOR = 6 /* Passive monitor (listen only) */
const IW_MODE_MESH = 7 /* Mesh (IEEE 802.11s) network */
/* Statistics flags (bitmask in updated) */
const IW_QUAL_QUAL_UPDATED = 0x01 /* Value was updated since last read */
const IW_QUAL_LEVEL_UPDATED = 0x02
const IW_QUAL_NOISE_UPDATED = 0x04
const IW_QUAL_ALL_UPDATED = 0x07
const IW_QUAL_DBM = 0x08 /* Level + Noise are dBm */
const IW_QUAL_QUAL_INVALID = 0x10 /* Driver doesn't provide value */
const IW_QUAL_LEVEL_INVALID = 0x20
const IW_QUAL_NOISE_INVALID = 0x40
const IW_QUAL_RCPI = 0x80 /* Level + Noise are 802.11k RCPI */
const IW_QUAL_ALL_INVALID = 0x70
/* Frequency flags */
const IW_FREQ_AUTO = 0x00 /* Let the driver decides */
const IW_FREQ_FIXED = 0x01 /* Force a specific value */
/* Maximum number of size of encoding token available
* they are listed in the range structure */
const IW_MAX_ENCODING_SIZES = 8
/* Maximum size of the encoding token in bytes */
const IW_ENCODING_TOKEN_MAX = 64 /* 512 bits (for now) */
/* Flags for encoding (along with the token) */
const IW_ENCODE_INDEX = 0x00FF /* Token index (if needed) */
const IW_ENCODE_FLAGS = 0xFF00 /* Flags defined below */
const IW_ENCODE_MODE = 0xF000 /* Modes defined below */
const IW_ENCODE_DISABLED = 0x8000 /* Encoding disabled */
const IW_ENCODE_ENABLED = 0x0000 /* Encoding enabled */
const IW_ENCODE_RESTRICTED = 0x4000 /* Refuse non-encoded packets */
const IW_ENCODE_OPEN = 0x2000 /* Accept non-encoded packets */
const IW_ENCODE_NOKEY = 0x0800 /* Key is write only, so not present */
const IW_ENCODE_TEMP = 0x0400 /* Temporary key */
/* Power management flags available (along with the value, if any) */
const IW_POWER_ON = 0x0000 /* No details... */
const IW_POWER_TYPE = 0xF000 /* Type of parameter */
const IW_POWER_PERIOD = 0x1000 /* Value is a period/duration of */
const IW_POWER_TIMEOUT = 0x2000 /* Value is a timeout (to go asleep) */
const IW_POWER_MODE = 0x0F00 /* Power Management mode */
const IW_POWER_UNICAST_R = 0x0100 /* Receive only unicast messages */
const IW_POWER_MULTICAST_R = 0x0200 /* Receive only multicast messages */
const IW_POWER_ALL_R = 0x0300 /* Receive all messages though PM */
const IW_POWER_FORCE_S = 0x0400 /* Force PM procedure for sending unicast */
const IW_POWER_REPEATER = 0x0800 /* Repeat broadcast messages in PM period */
const IW_POWER_MODIFIER = 0x000F /* Modify a parameter */
const IW_POWER_MIN = 0x0001 /* Value is a minimum */
const IW_POWER_MAX = 0x0002 /* Value is a maximum */
const IW_POWER_RELATIVE = 0x0004 /* Value is not in seconds/ms/us */
/* Transmit Power flags available */
const IW_TXPOW_TYPE = 0x00FF /* Type of value */
const IW_TXPOW_DBM = 0x0000 /* Value is in dBm */
const IW_TXPOW_MWATT = 0x0001 /* Value is in mW */
const IW_TXPOW_RELATIVE = 0x0002 /* Value is in arbitrary units */
const IW_TXPOW_RANGE = 0x1000 /* Range of value between min/max */
/* Retry limits and lifetime flags available */
const IW_RETRY_ON = 0x0000 /* No details... */
const IW_RETRY_TYPE = 0xF000 /* Type of parameter */
const IW_RETRY_LIMIT = 0x1000 /* Maximum number of retries*/
const IW_RETRY_LIFETIME = 0x2000 /* Maximum duration of retries in us */
const IW_RETRY_MODIFIER = 0x00FF /* Modify a parameter */
const IW_RETRY_MIN = 0x0001 /* Value is a minimum */
const IW_RETRY_MAX = 0x0002 /* Value is a maximum */
const IW_RETRY_RELATIVE = 0x0004 /* Value is not in seconds/ms/us */
const IW_RETRY_SHORT = 0x0010 /* Value is for short packets */
const IW_RETRY_LONG = 0x0020 /* Value is for long packets */
/* Scanning request flags */
const IW_SCAN_DEFAULT = 0x0000 /* Default scan of the driver */
const IW_SCAN_ALL_ESSID = 0x0001 /* Scan all ESSIDs */
const IW_SCAN_THIS_ESSID = 0x0002 /* Scan only this ESSID */
const IW_SCAN_ALL_FREQ = 0x0004 /* Scan all Frequencies */
const IW_SCAN_THIS_FREQ = 0x0008 /* Scan only this Frequency */
const IW_SCAN_ALL_MODE = 0x0010 /* Scan all Modes */
const IW_SCAN_THIS_MODE = 0x0020 /* Scan only this Mode */
const IW_SCAN_ALL_RATE = 0x0040 /* Scan all Bit-Rates */
const IW_SCAN_THIS_RATE = 0x0080 /* Scan only this Bit-Rate */
/* struct iw_scan_req scan_type */
const IW_SCAN_TYPE_ACTIVE = 0
const IW_SCAN_TYPE_PASSIVE = 1
/* Maximum size of returned data */
const IW_SCAN_MAX_DATA = 4096 /* In bytes */
/* Scan capability flags - in (struct iw_range *)->scan_capa */
const IW_SCAN_CAPA_NONE = 0x00
const IW_SCAN_CAPA_ESSID = 0x01
const IW_SCAN_CAPA_BSSID = 0x02
const IW_SCAN_CAPA_CHANNEL = 0x04
const IW_SCAN_CAPA_MODE = 0x08
const IW_SCAN_CAPA_RATE = 0x10
const IW_SCAN_CAPA_TYPE = 0x20
const IW_SCAN_CAPA_TIME = 0x40
/* Max number of char in custom event - use multiple of them if needed */
const IW_CUSTOM_MAX = 256 /* In bytes */
/* Generic information element */
const IW_GENERIC_IE_MAX = 1024
/* MLME requests (SIOCSIWMLME / struct iw_mlme) */
const IW_MLME_DEAUTH = 0
const IW_MLME_DISASSOC = 1
const IW_MLME_AUTH = 2
const IW_MLME_ASSOC = 3
/* SIOCSIWAUTH/SIOCGIWAUTH struct iw_param flags */
const IW_AUTH_INDEX = 0x0FFF
const IW_AUTH_FLAGS = 0xF000
/* SIOCSIWAUTH/SIOCGIWAUTH parameters (0 .. 4095)
* (IW_AUTH_INDEX mask in struct iw_param flags; this is the index of the
* parameter that is being set/get to; value will be read/written to
* struct iw_param value field) */
const IW_AUTH_WPA_VERSION = 0
const IW_AUTH_CIPHER_PAIRWISE = 1
const IW_AUTH_CIPHER_GROUP = 2
const IW_AUTH_KEY_MGMT = 3
const IW_AUTH_TKIP_COUNTERMEASURES = 4
const IW_AUTH_DROP_UNENCRYPTED = 5
const IW_AUTH_80211_AUTH_ALG = 6
const IW_AUTH_WPA_ENABLED = 7
const IW_AUTH_RX_UNENCRYPTED_EAPOL = 8
const IW_AUTH_ROAMING_CONTROL = 9
const IW_AUTH_PRIVACY_INVOKED = 10
const IW_AUTH_CIPHER_GROUP_MGMT = 11
const IW_AUTH_MFP = 12
/* IW_AUTH_WPA_VERSION values (bit field) */
const IW_AUTH_WPA_VERSION_DISABLED = 0x00000001
const IW_AUTH_WPA_VERSION_WPA = 0x00000002
const IW_AUTH_WPA_VERSION_WPA2 = 0x00000004
/* IW_AUTH_PAIRWISE_CIPHER, IW_AUTH_GROUP_CIPHER, and IW_AUTH_CIPHER_GROUP_MGMT
* values (bit field) */
const IW_AUTH_CIPHER_NONE = 0x00000001
const IW_AUTH_CIPHER_WEP40 = 0x00000002
const IW_AUTH_CIPHER_TKIP = 0x00000004
const IW_AUTH_CIPHER_CCMP = 0x00000008
const IW_AUTH_CIPHER_WEP104 = 0x00000010
const IW_AUTH_CIPHER_AES_CMAC = 0x00000020
/* IW_AUTH_KEY_MGMT values (bit field) */
const IW_AUTH_KEY_MGMT_802_1X = 1
const IW_AUTH_KEY_MGMT_PSK = 2
/* IW_AUTH_80211_AUTH_ALG values (bit field) */
const IW_AUTH_ALG_OPEN_SYSTEM = 0x00000001
const IW_AUTH_ALG_SHARED_KEY = 0x00000002
const IW_AUTH_ALG_LEAP = 0x00000004
/* IW_AUTH_ROAMING_CONTROL values */
const IW_AUTH_ROAMING_ENABLE = 0 /* driver/firmware based roaming */
const IW_AUTH_ROAMING_DISABLE = 1 /* user space program used for roaming
* control */
/* IW_AUTH_MFP (management frame protection) values */
const IW_AUTH_MFP_DISABLED = 0 /* MFP disabled */
const IW_AUTH_MFP_OPTIONAL = 1 /* MFP optional */
const IW_AUTH_MFP_REQUIRED = 2 /* MFP required */
/* SIOCSIWENCODEEXT definitions */
const IW_ENCODE_SEQ_MAX_SIZE = 8
/* struct iw_encode_ext ->alg */
const IW_ENCODE_ALG_NONE = 0
const IW_ENCODE_ALG_WEP = 1
const IW_ENCODE_ALG_TKIP = 2
const IW_ENCODE_ALG_CCMP = 3
const IW_ENCODE_ALG_PMK = 4
const IW_ENCODE_ALG_AES_CMAC = 5
/* struct iw_encode_ext ->ext_flags */
const IW_ENCODE_EXT_TX_SEQ_VALID = 0x00000001
const IW_ENCODE_EXT_RX_SEQ_VALID = 0x00000002
const IW_ENCODE_EXT_GROUP_KEY = 0x00000004
const IW_ENCODE_EXT_SET_TX_KEY = 0x00000008
/* IWEVMICHAELMICFAILURE : struct iw_michaelmicfailure ->flags */
const IW_MICFAILURE_KEY_ID = 0x00000003 /* Key ID 0..3 */
const IW_MICFAILURE_GROUP = 0x00000004
const IW_MICFAILURE_PAIRWISE = 0x00000008
const IW_MICFAILURE_STAKEY = 0x00000010
const IW_MICFAILURE_COUNT = 0x00000060 /* 1 or 2 (0 = count not supported)
*/
/* Bit field values for enc_capa in struct iw_range */
const IW_ENC_CAPA_WPA = 0x00000001
const IW_ENC_CAPA_WPA2 = 0x00000002
const IW_ENC_CAPA_CIPHER_TKIP = 0x00000004
const IW_ENC_CAPA_CIPHER_CCMP = 0x00000008
const IW_ENC_CAPA_4WAY_HANDSHAKE = 0x00000010
/* Event capability macros - in (struct iw_range *)->event_capa
* Because we have more than 32 possible events, we use an array of
* 32 bit bitmasks. Note : 32 bits = 0x20 = 2^5. */
func IW_EVENT_CAPA_BASE(cmd uint32) uint32 {
if cmd >= SIOCIWFIRSTPRIV {
return cmd - SIOCIWFIRSTPRIV + 0x60
}
return cmd - SIOCIWFIRST
}
func IW_EVENT_CAPA_INDEX(cmd uint32) uint32 {
return IW_EVENT_CAPA_BASE(cmd) >> 5
}
func IW_EVENT_CAPA_MASK(cmd uint32) uint32 {
return (1 << (IW_EVENT_CAPA_BASE(cmd) & 0x1F))
}
/* Event capability constants - event autogenerated by the kernel
* This list is valid for most 802.11 devices, customise as needed... */
var IW_EVENT_CAPA_K_0 = (IW_EVENT_CAPA_MASK(0x8B04) | IW_EVENT_CAPA_MASK(0x8B06) | IW_EVENT_CAPA_MASK(0x8B1A))
var IW_EVENT_CAPA_K_1 = (IW_EVENT_CAPA_MASK(0x8B2A))
/* "Easy" macro to set events in iw_range (less efficient) */
func IW_EVENT_CAPA_SET(event_capa []uint32, cmd uint32) {
event_capa[IW_EVENT_CAPA_INDEX(cmd)] |= IW_EVENT_CAPA_MASK(cmd)
}
func IW_EVENT_CAPA_SET_KERNEL(event_capa []uint32) {
event_capa[0] |= IW_EVENT_CAPA_K_0
event_capa[1] |= IW_EVENT_CAPA_K_1
}
/****************************** TYPES ******************************/
/* --------------------------- SUBTYPES --------------------------- */
/*
* Generic format for most parameters that fit in an int
*/
type iw_param struct {
value int32 /* The value of the parameter itself */
fixed uint8 /* Hardware should not use auto select */
disabled uint8 /* Disable the feature */
flags uint16 /* Various specifc flags (if any) */
}
/*
* For all data larger than 16 octets, we need to use a
* pointer to memory allocated in user space.
*/
type iw_point struct {
pointer unsafe.Pointer /* Pointer to the data (in user space) */
length uint16 /* number of fields or size in bytes */
flags uint16 /* Optional params */
}
/*
* A frequency
* For numbers lower than 10^9, we encode the number in 'm' and
* set 'e' to 0
* For number greater than 10^9, we divide it by the lowest power
* of 10 to get 'm' lower than 10^9, with 'm'= f / (10^'e')...
* The power of 10 is in 'e', the result of the division is in 'm'.
*/
type iw_freq struct {
m int32 /* Mantissa */
e int16 /* Exponent */
i uint8 /* List index (when in range struct) */
flags uint8 /* Flags (fixed/auto) */
}
/*
* Quality of the link
*/
type iw_quality struct {
qual uint8 /* link quality (%retries, SNR,
%missed beacons or better...) */
level uint8 /* signal level (dBm) */
noise uint8 /* noise level (dBm) */
updated uint8 /* Flags to know if updated */
}
/*
* Packet discarded in the wireless adapter due to
* "wireless" specific problems...
* Note : the list of counter and statistics in net_device_stats
* is already pretty exhaustive, and you should use that first.
* This is only additional stats...
*/
type iw_discarded struct {
nwid uint32 /* Rx : Wrong nwid/essid */
code uint32 /* Rx : Unable to code/decode (WEP) */
fragment uint32 /* Rx : Can't perform MAC reassembly */
retries uint32 /* Tx : Max MAC retries num reached */
misc uint32 /* Others cases */
}
/*
* Packet/Time period missed in the wireless adapter due to
* "wireless" specific problems...
*/
type iw_missed struct {
beacon uint32 /* Missed beacons/superframe */
}
type sockaddr []byte
/*
* Quality range (for spy threshold)
*/
type iw_thrspy struct {
addr sockaddr /* Source address (hw/mac) */
qual iw_quality /* Quality of the link */
low iw_quality /* Low threshold */
high iw_quality /* High threshold */
}
/*
* Optional data for scan request
*
* Note: these optional parameters are controlling parameters for the
* scanning behavior, these do not apply to getting scan results
* (SIOCGIWSCAN). Drivers are expected to keep a local BSS table and
* provide a merged results with all BSSes even if the previous scan
* request limited scanning to a subset, e.g., by specifying an SSID.
* Especially, scan results are required to include an entry for the
* current BSS if the driver is in Managed mode and associated with an AP.
*/
type iw_scan_req struct {
scan_type uint8 /* IW_SCAN_TYPE_{ACTIVE,PASSIVE} */
essid_len uint8
num_channels uint8 /* num entries in channel_list uint8
* 0 = scan all allowed channels */
flags uint8 /* reserved as padding uint8 use zero, this may
* be used in the future for adding flags
* to request different scan behavior */
bssid sockaddr /* ff:ff:ff:ff:ff:ff for broadcast BSSID or
* individual address of a specific BSS */
/*
* Use this ESSID if IW_SCAN_THIS_ESSID flag is used instead of using
* the current ESSID. This allows scan requests for specific ESSID
* without having to change the current ESSID and potentially breaking
* the current association.
*/
essid [IW_ESSID_MAX_SIZE]uint8
/*
* Optional parameters for changing the default scanning behavior.
* These are based on the MLME-SCAN.request from IEEE Std 802.11.
* TU is 1.024 ms. If these are set to 0, driver is expected to use
* reasonable default values. min_channel_time defines the time that
* will be used to wait for the first reply on each channel. If no
* replies are received, next channel will be scanned after this. If
* replies are received, total time waited on the channel is defined by
* max_channel_time.
*/
min_channel_time uint32 /* in TU */
max_channel_time uint32 /* in TU */
channel_list [IW_MAX_FREQUENCIES]iw_freq
}
/* ------------------------- WPA SUPPORT ------------------------- */
/*
* Extended data structure for get/set encoding (this is used with
* SIOCSIWENCODEEXT/SIOCGIWENCODEEXT. struct iw_point and IW_ENCODE_*
* flags are used in the same way as with SIOCSIWENCODE/SIOCGIWENCODE and
* only the data contents changes (key data -> this structure, including
* key data).
*
* If the new key is the first group key, it will be set as the default
* TX key. Otherwise, default TX key index is only changed if
* IW_ENCODE_EXT_SET_TX_KEY flag is set.
*
* Key will be changed with SIOCSIWENCODEEXT in all cases except for
* special "change TX key index" operation which is indicated by setting
* key_len = 0 and ext_flags |= IW_ENCODE_EXT_SET_TX_KEY.
*
* tx_seq/rx_seq are only used when respective
* IW_ENCODE_EXT_{TX,RX}_SEQ_VALID flag is set in ext_flags. Normal
* TKIP/CCMP operation is to set RX seq with SIOCSIWENCODEEXT and start
* TX seq from zero whenever key is changed. SIOCGIWENCODEEXT is normally
* used only by an Authenticator (AP or an IBSS station) to get the
* current TX sequence number. Using TX_SEQ_VALID for SIOCSIWENCODEEXT and
* RX_SEQ_VALID for SIOCGIWENCODEEXT are optional, but can be useful for
* debugging/testing.
*/
type iw_encode_ext struct {
ext_flags uint32 /* IW_ENCODE_EXT_* */
tx_seq [IW_ENCODE_SEQ_MAX_SIZE]uint8 /* LSB first */
rx_seq [IW_ENCODE_SEQ_MAX_SIZE]uint8 /* LSB first */
addr sockaddr /* ff:ff:ff:ff:ff:ff for broadcast/multicast
* (group) keys or unicast address for
* individual keys */
alg uint16 /* IW_ENCODE_ALG_* */
key_len uint16
key []uint8
}
/* SIOCSIWMLME data */
type iw_mlme struct {
cmd uint16 /* IW_MLME_* */
reason_code uint16
addr sockaddr
}
/* SIOCSIWPMKSA data */
const IW_PMKSA_ADD = 1
const IW_PMKSA_REMOVE = 2
const IW_PMKSA_FLUSH = 3
const IW_PMKID_LEN = 16
type iw_pmksa struct {
cmd uint32 /* IW_PMKSA_* */
bssid sockaddr
pmkid [IW_PMKID_LEN]uint8
}
/* IWEVMICHAELMICFAILURE data */
type iw_michaelmicfailure struct {
flags uint32
src_addr sockaddr
tsc [IW_ENCODE_SEQ_MAX_SIZE]uint8 /* LSB first */
}
/* IWEVPMKIDCAND data */
const IW_PMKID_CAND_PREAUTH = 0x00000001 /* RNS pre-authentication enabled */
type iw_pmkid_cand struct {
flags uint32 /* IW_PMKID_CAND_* */
index uint32 /* the smaller the index, the higher the
* priority */
bssid sockaddr
}
/* ------------------------ WIRELESS STATS ------------------------ */
/*
* Wireless statistics (used for /proc/net/wireless)
*/
type iw_statistics struct {
status uint16 /* Status
* - device dependent for now */
qual iw_quality /* Quality of the link
* (instant/mean/max) */
discard iw_quality /* Packet discarded counts */
miss iw_quality /* Packet missed counts */
}
/* ------------------------ IOCTL REQUEST ------------------------ */
/*
* This structure defines the payload of an ioctl, and is used
* below.
*
* Note that this structure should fit on the memory footprint
* of iwreq (which is the same as ifreq), which mean a max size of
* 16 octets = 128 bits. Warning, pointers might be 64 bits wide...
* You should check this when increasing the structures defined
* above in this file...
*
union iwreq_data {
/* Config - generic *
char name[IFNAMSIZ];
/* Name : used to verify the presence of wireless extensions.
* Name of the protocol/provider... *
iw_point essid; /* Extended network name *
iw_param nwid; /* network id (or domain - the cell) *
iw_freq freq; /* frequency or channel :
* 0-1000 = channel
* > 1000 = frequency in Hz *
iw_param sens; /* signal level threshold *
iw_param bitrate; /* default bit rate *
iw_param txpower; /* default transmit power *
iw_param rts; /* RTS threshold threshold *
iw_param frag; /* Fragmentation threshold *
mode uint32 /* Operation mode *
iw_param retry; /* Retry limits & lifetime *
iw_point encoding; /* Encoding stuff : tokens *
iw_param power; /* PM duration/timeout *
iw_quality qual; /* Quality part of statistics *
sockaddr ap_addr; /* Access point address *
sockaddr addr; /* Destination address (hw/mac) *
iw_param param; /* Other small parameters *
iw_point data; /* Other large parameters *
};
/*
* The structure to exchange data for ioctl.
* This structure is the same as 'struct ifreq', but (re)defined for
* convenience...
* Do I need to remind you about structure size (32 octets) ?
*/
type iwreq struct {
//union
//{
// char ifrn_name[IFNAMSIZ]; /* if name, e.g. "eth0" */
// } ifr_ifrn;
/* Data part (defined just above) *
union iwreq_data u;
*/
}
/* -------------------------- IOCTL DATA -------------------------- */
/*
* For those ioctl which want to exchange mode data that what could
* fit in the above structure...
*/
/*
* Range of parameters
*/
type IWRange struct {
/* Informative stuff (to choose between different interface) */
throughput uint32 /* To give an idea... */
/* In theory this value should be the maximum benchmarked
* TCP/IP throughput, because with most of these devices the
* bit rate is meaningless (overhead an co) to estimate how
* fast the connection will go and pick the fastest one.
* I suggest people to play with Netperf or any benchmark...
*/
/* NWID (or domain id) */
min_nwid uint32 /* Minimal NWID we are able to set */
max_nwid uint32 /* Maximal NWID we are able to set */
/* Old Frequency (backward compat - moved lower ) */
old_num_channels uint16
old_num_frequency uint8
/* Scan capabilities */
scan_capa uint8 /* IW_SCAN_CAPA_* bit field */
/* Wireless event capability bitmasks */
event_capa [6]uint32
/* signal level threshold range */
sensitivity int32
/* Quality of link & SNR stuff */
/* Quality range (link, level, noise)
* If the quality is absolute, it will be in the range [0 ; max_qual],
* if the quality is dBm, it will be in the range [max_qual ; 0].
* Don't forget that we use 8 bit arithmetics... */
max_qual iw_quality /* Quality of the link */
/* This should contain the average/typical values of the quality
* indicator. This should be the threshold between a "good" and
* a "bad" link (example : monitor going from green to orange).
* Currently, user space apps like quality monitors don't have any
* way to calibrate the measurement. With this, they can split
* the range between 0 and max_qual in different quality level
* (using a geometric subdivision centered on the average).
* I expect that people doing the user space apps will feedback
* us on which value we need to put in each driver... */
avg_qual iw_quality /* Quality of the link */
/* Rates */
num_bitrates uint8 /* Number of entries in the list */
bitrate [IW_MAX_BITRATES]int32 /* list, in bps */
/* RTS threshold */
min_rts int32 /* Minimal RTS threshold */
max_rts int32 /* Maximal RTS threshold */
/* Frag threshold */
min_frag int32 /* Minimal frag threshold */
max_frag int32 /* Maximal frag threshold */
/* Power Management duration & timeout */
min_pmp int32 /* Minimal PM period */
max_pmp int32 /* Maximal PM period */
min_pmt int32 /* Minimal PM timeout */
max_pmt int32 /* Maximal PM timeout */
pmp_flags uint16 /* How to decode max/min PM period */
pmt_flags uint16 /* How to decode max/min PM timeout */
pm_capa uint16 /* What PM options are supported */
/* Encoder stuff */
encoding_size [IW_MAX_ENCODING_SIZES]uint16 /* Different token sizes */
num_encoding_sizes uint8 /* Number of entry in the list */
max_encoding_tokens uint8 /* Max number of tokens */
/* For drivers that need a "login/passwd" form */
encoding_login_index uint8 /* token index for login token */
/* Transmit power */
txpower_capa uint16 /* What options are supported */
num_txpower uint8 /* Number of entries in the list */
txpower [IW_MAX_TXPOWER]int32 /* list, in bps */
/* Wireless Extension version info */
we_version_compiled uint8 /* Must be WIRELESS_EXT */
we_version_source uint8 /* Last update of source */
/* Retry limits and lifetime */
retry_capa uint16 /* What retry options are supported */
retry_flags uint16 /* How to decode max/min retry limit */
r_time_flags uint16 /* How to decode max/min retry life */
min_retry int32 /* Minimal number of retries */
max_retry int32 /* Maximal number of retries */
min_r_time int32 /* Minimal retry lifetime */
max_r_time int32 /* Maximal retry lifetime */
/* Frequency */
num_channels uint16 /* Number of channels [0; num - 1] */
num_frequency uint8 /* Number of entry in the list */
freq [IW_MAX_FREQUENCIES]iw_freq /* list */
/* Note : this frequency list doesn't need to fit channel numbers,
* because each entry contain its channel index */
enc_capa uint32 /* IW_ENC_CAPA_* bit field */
}
/*
* Private ioctl interface information
*/
const IFNAMSIZ = 16
type iw_priv_args struct {
cmd uint32 /* Number of the ioctl to issue */
set_args uint16 /* Type and number of args */
get_args uint16 /* Type and number of args */
name [IFNAMSIZ]byte /* Name of the extension */
}
/* ----------------------- WIRELESS EVENTS ----------------------- */
/*
* Wireless events are carried through the rtnetlink socket to user
* space. They are encapsulated in the IFLA_WIRELESS field of
* a RTM_NEWLINK message.
*/
/*
* A Wireless Event. Contains basically the same data as the ioctl...
*/
type iw_event struct {
len uint16 /* Real length of this stuff */
cmd uint16 /* Wireless IOCTL */
//union iwreq_data u; /* IOCTL fixed payload */
}
// stupid sizeof tricks for the inevitable binary interface.
/* Size of the Event prefix (including padding and alignement junk) *
const IW_EV_LCP_LEN = (sizeof(struct iw_event) - sizeof(union iwreq_data))
/* Size of the various events *
const IW_EV_CHAR_LEN = (IW_EV_LCP_LEN + IFNAMSIZ)
const IW_EV_UINT_LEN = (IW_EV_LCP_LEN + sizeof(uint32))
const IW_EV_FREQ_LEN = (IW_EV_LCP_LEN + sizeof(struct iw_freq))
const IW_EV_PARAM_LEN = (IW_EV_LCP_LEN + sizeof(struct iw_param))
const IW_EV_ADDR_LEN = (IW_EV_LCP_LEN + sizeof(struct sockaddr))
const IW_EV_QUAL_LEN = (IW_EV_LCP_LEN + sizeof(struct iw_quality))
/* iw_point events are special. First, the payload (extra data) come at
* the end of the event, so they are bigger than IW_EV_POINT_LEN. Second,
* we omit the pointer, so start at an offset. *
const IW_EV_POINT_OFF = (((char *) &(((struct iw_point *) NULL)->length)) - (char *) NULL)
const IW_EV_POINT_LEN = (IW_EV_LCP_LEN + sizeof(struct iw_point) - IW_EV_POINT_OFF)
/* Size of the Event prefix when packed in stream */
const IW_EV_LCP_PK_LEN = (4)
/* Size of the various events when packed in stream *
const IW_EV_CHAR_PK_LEN = (IW_EV_LCP_PK_LEN + IFNAMSIZ)
const IW_EV_UINT_PK_LEN = (IW_EV_LCP_PK_LEN + sizeof(uint32))
const IW_EV_FREQ_PK_LEN = (IW_EV_LCP_PK_LEN + sizeof(struct iw_freq))
const IW_EV_PARAM_PK_LEN = (IW_EV_LCP_PK_LEN + sizeof(struct iw_param))
const IW_EV_ADDR_PK_LEN = (IW_EV_LCP_PK_LEN + sizeof(struct sockaddr))
const IW_EV_QUAL_PK_LEN = (IW_EV_LCP_PK_LEN + sizeof(struct iw_quality))
*/
const IW_EV_POINT_PK_LEN = (IW_EV_LCP_PK_LEN + 4)
|
package models
import (
"database/sql"
"git.hoogi.eu/snafu/go-blog/logger"
"time"
)
// SQLiteTokenDatasource providing an implementation of TokenDatasourceService using MariaDB
type SQLiteTokenDatasource struct {
SQLConn *sql.DB
}
// Create creates a new token
func (rdb *SQLiteTokenDatasource) Create(t *Token) (int, error) {
res, err := rdb.SQLConn.Exec("INSERT INTO token (hash, requested_at, token_type, user_id) VALUES(?, ?, ?, ?)",
t.Hash, time.Now(), t.Type, t.Author.ID)
if err != nil {
return -1, err
}
i, err := res.LastInsertId()
if err != nil {
return -1, err
}
return int(i), nil
}
// Get gets a token based on the hash and the token type
func (rdb *SQLiteTokenDatasource) Get(hash string, tt TokenType) (*Token, error) {
var t Token
var u User
if err := rdb.SQLConn.QueryRow("SELECT t.id, t.hash, t.requested_at, t.token_type, t.user_id FROM token as t WHERE t.hash=? AND t.token_type=? ", hash, tt.String()).
Scan(&t.ID, &t.Hash, &t.RequestedAt, &t.Type, &u.ID); err != nil {
return nil, err
}
t.Author = &u
return &t, nil
}
// ListByUser receives all tokens based on the user id and the token type ordered by requested
func (rdb *SQLiteTokenDatasource) ListByUser(userID int, tt TokenType) ([]Token, error) {
rows, err := rdb.SQLConn.Query("SELECT t.id, t.hash, t.requested_at, t.token_type, t.user_id FROM token as t WHERE t.user_id=? AND t.token_type=? ", userID, tt.String())
if err != nil {
return nil, err
}
defer func() {
if err := rows.Close(); err != nil {
logger.Log.Error(err)
}
}()
tokens := []Token{}
for rows.Next() {
var u User
var t Token
if err = rows.Scan(&t.ID, &t.Hash, &t.RequestedAt, &t.Type, &u.ID); err != nil {
return nil, err
}
t.Author = &u
tokens = append(tokens, t)
}
return tokens, nil
}
// Remove removes a token based on the hash
func (rdb *SQLiteTokenDatasource) Remove(hash string, tt TokenType) error {
if _, err := rdb.SQLConn.Exec("DELETE FROM token WHERE hash=? AND token_type=? ", hash, tt.String()); err != nil {
return err
}
return nil
}
|
package tokenbucket
import (
"errors"
"time"
)
func CreateTokenBucket(
sizeOfBucket int,
numOfTokens int,
tokenFillingInterval time.Duration) chan time.Time {
bucket := make(chan time.Time, sizeOfBucket)
for j := 0; j < sizeOfBucket; j++ {
bucket <- time.Now()
}
go func() {
for t := range time.Tick(tokenFillingInterval) {
for i := 0; i < numOfTokens; i++ {
bucket <- t
}
}
}()
return bucket
}
func GetToken(tokenBucket chan time.Time, timeout time.Duration) (time.Time, error) {
var token time.Time
if timeout != 0 {
select {
case token = <-tokenBucket:
return token, nil
case <-time.After(timeout):
return token, errors.New("Failed to get token for time out")
}
}
token = <-tokenBucket
return token, nil
}
|
package api
import (
"context"
"strings"
"github.com/inconshreveable/log15"
"github.com/opentracing/opentracing-go/log"
"github.com/pkg/errors"
"github.com/sourcegraph/sourcegraph/enterprise/internal/codeintel/stores/lsifstore"
"github.com/sourcegraph/sourcegraph/internal/observation"
)
// Hover returns the hover text and range for the symbol at the given position.
func (api *CodeIntelAPI) Hover(ctx context.Context, file string, line, character, uploadID int) (_ string, _ lsifstore.Range, _ bool, err error) {
ctx, endObservation := api.operations.hover.With(ctx, &err, observation.Args{LogFields: []log.Field{
log.String("file", file),
log.Int("line", line),
log.Int("character", character),
log.Int("uploadID", uploadID),
}})
defer endObservation(1, observation.Args{})
dump, exists, err := api.dbStore.GetDumpByID(ctx, uploadID)
if err != nil {
return "", lsifstore.Range{}, false, errors.Wrap(err, "store.GetDumpByID")
}
if !exists {
return "", lsifstore.Range{}, false, ErrMissingDump
}
pathInBundle := strings.TrimPrefix(file, dump.Root)
text, rn, exists, err := api.lsifStore.Hover(ctx, dump.ID, pathInBundle, line, character)
if err != nil {
if err == lsifstore.ErrNotFound {
log15.Warn("Bundle does not exist")
return "", lsifstore.Range{}, false, nil
}
return "", lsifstore.Range{}, false, errors.Wrap(err, "bundleClient.Hover")
}
if exists {
return text, rn, true, nil
}
definition, exists, err := api.definitionRaw(ctx, dump, pathInBundle, line, character)
if err != nil || !exists {
return "", lsifstore.Range{}, false, errors.Wrap(err, "api.definitionRaw")
}
pathInDefinitionBundle := strings.TrimPrefix(definition.Path, definition.Dump.Root)
text, rn, exists, err = api.lsifStore.Hover(ctx, definition.Dump.ID, pathInDefinitionBundle, definition.Range.Start.Line, definition.Range.Start.Character)
if err != nil {
if err == lsifstore.ErrNotFound {
log15.Warn("Bundle does not exist")
return "", lsifstore.Range{}, false, nil
}
return "", lsifstore.Range{}, false, errors.Wrap(err, "definitionBundleClient.Hover")
}
return text, rn, exists, nil
}
|
package float128ppc
import (
"math/big"
"testing"
)
func TestRoundTrip(t *testing.T) {
golden := []struct {
h, l uint64
}{
{h: 0x0000000000000000, l: 0x0000000000000000}, // "0xM00000000000000000000000000000000"
{h: 0x3DF0000000000000, l: 0x0000000000000000}, // "0xM3DF00000000000000000000000000000"
{h: 0x3FF0000000000000, l: 0x0000000000000000}, // "0xM3FF00000000000000000000000000000"
{h: 0x4000000000000000, l: 0x0000000000000000}, // "0xM40000000000000000000000000000000"
{h: 0x400C000000000030, l: 0x0000000010000000}, // "0xM400C0000000000300000000010000000"
{h: 0x400F000000000000, l: 0xBCB0000000000000}, // "0xM400F000000000000BCB0000000000000"
{h: 0x403B000000000000, l: 0x0000000000000000}, // "0xM403B0000000000000000000000000000"
{h: 0x405EDA5E353F7CEE, l: 0x0000000000000000}, // "0xM405EDA5E353F7CEE0000000000000000"
{h: 0x4093B40000000000, l: 0x0000000000000000}, // "0xM4093B400000000000000000000000000"
{h: 0x41F0000000000000, l: 0x0000000000000000}, // "0xM41F00000000000000000000000000000"
{h: 0x4D436562A0416DE0, l: 0x0000000000000000}, // "0xM4D436562A0416DE00000000000000000"
{h: 0x8000000000000000, l: 0x0000000000000000}, // "0xM80000000000000000000000000000000"
{h: 0x818F2887B9295809, l: 0x800000000032D000}, // "0xM818F2887B9295809800000000032D000"
{h: 0xC00547AE147AE148, l: 0x3CA47AE147AE147A}, // "0xMC00547AE147AE1483CA47AE147AE147A"
}
for _, g := range golden {
f1 := NewFromBits(g.h, g.l)
fbig, nan := f1.Big()
_ = nan
f2, acc := NewFromBig(fbig)
_ = acc
h, l := f2.Bits()
if g.h != h {
t.Errorf("0xM%016X%016X; high mismatch; expected 0x%016X, got 0x%016X", g.h, g.l, g.h, h)
}
if g.l != l {
t.Errorf("0xM%016X%016X; low mismatch; expected 0x%016X, got 0x%016X", g.h, g.l, g.l, l)
}
if acc != big.Exact {
t.Errorf("0xM%016X%016X; round-trip result accuracy inexact; expected %v, got %v", g.h, g.l, big.Exact, acc)
}
}
}
|
package main
import (
"fmt"
"strings"
"github.com/chzyer/readline"
parsec "github.com/prataprc/goparsec"
)
func main() {
fmt.Println("LispG Version 0.0.0.0.1")
fmt.Println("Interactive LispG - Press Ctrl+c to exit")
rl, err := readline.NewEx(&readline.Config{Prompt: "lispg> ", HistoryFile: ".lispg_history", DisableAutoSaveHistory: false})
if err != nil {
panic(err)
}
defer rl.Close()
for {
line, err := rl.Readline()
if err != nil {
panic(err)
}
trimmed := strings.Trim(line, "\r\n ")
if trimmed == "(:exit)" {
break
}
if trimmed == "" {
continue
}
parsed_node := parse_form(trimmed)
result := eval(parsed_node)
fmt.Printf("#=> %s\n", result)
}
}
func eval(parsed_node parsec.Queryable) string {
return parsed_node.GetValue()
}
|
package main
import (
"encoding/json"
"fmt"
"os"
"time"
)
// RepositoryMetadata is metadata for each gist.
type RepositoryMetadata struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
URL string `json:"url"`
GitURL string `json:"git_url"`
Owner string `json:"owner"`
Created int64 `json:"created"`
}
// NewMetadataFromGist converts Gist into metadata.
func NewMetadataFromGist(repositoryName RepositoryName, gist Gist) (*RepositoryMetadata, error) {
createdAt, err := time.Parse("2006-01-02T15:04:05Z", gist.CreatedAt)
if err != nil {
return nil, err
}
return &RepositoryMetadata{
ID: gist.ID,
Name: string(repositoryName),
URL: gist.URL,
GitURL: gist.GitURL,
Owner: gist.Owner.Login,
Created: createdAt.Unix(),
}, nil
}
// AppendTo appends RepositoryMetadata to file. If file is not existing, the file will be created.
func (md *RepositoryMetadata) AppendTo(path string) error {
file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return fmt.Errorf("RepositoryMetadata_AppendTo_OpenFile: %w", err)
}
defer func() { _ = file.Close() }()
bytes, err := json.Marshal(*md)
if err != nil {
return fmt.Errorf("Repositorymetadata_AppendTo_MarshalJson: %w", err)
}
_, err = file.Write(bytes)
if err != nil {
return fmt.Errorf("Repositorymetadata_AppendTo_Write: %w", err)
}
_, err = file.WriteString("\n")
if err != nil {
return fmt.Errorf("Repositorymetadata_AppendTo_WriteNewLine: %w", err)
}
return nil
}
|
package zlog
import (
"go.uber.org/zap"
"testing"
)
func Test_zlog(t *testing.T) {
//logger := ZlogInitSplitFile(&ZlogCfg{
// Level: "DEBUG",
// Compress: false,
// MaxAge: 10,
// MaxSize: 1,
// MaxBackups: 30,
// FileName: "./log/signal.log",
// FlushInterval: 300,
// BuffSize: 1,
// AddCaller: true,
// AddSkip: 1,
//})
//defer logger.Sync()
//for i := 0; i < 1000; i++ {
// logger.Debug("is debug")
//}
//logger.Info("is info")
//logger.Error("is error")
//logger.Panic("is panic")
//fmt.Println(replaceFileName("./log/signnal.log", zapcore.DebugLevel))
//t.Log("1")
//viper.SetDefault("zlog.file_name","./zlog")
//viper.SetConfigName("zlog")
//viper.SetConfigType("yaml")
//viper.AddConfigPath(".")
//err := viper.ReadInConfig()
//if err != nil {
// fmt.Printf("err = %v",err)
//}
//fmt.Println(viper.Get("zlog.level"))
//fmt.Println(viper.Get("zlog.file_name"))
//viper.WatchConfig()
}
func Test_zlog_config(t *testing.T) {
err, zlogConf := InitConfig("./", "zlog", "yaml")
if err != nil {
t.Error(err)
return
}
zlog := ZlogInitSplitFile(zlogConf)
defer zlog.Sync()
zlog.Info("info", zap.String("name", "info..."))
}
func Test_zlog_config2(t *testing.T) {
err, zlogConf := InitConfigByFilePath("./zlog.yaml")
if err != nil {
t.Error(err)
return
}
zlog := ZlogInitSplitFile(zlogConf)
defer zlog.Sync()
zlog.Info("info", zap.String("name", "info..."))
}
|
package delete_container
import (
"net/http"
"sync"
"github.com/cloudfoundry-incubator/executor/registry"
"github.com/cloudfoundry-incubator/garden/warden"
"github.com/cloudfoundry/gosteno"
)
type handler struct {
wardenClient warden.Client
registry registry.Registry
waitGroup *sync.WaitGroup
logger *gosteno.Logger
}
func New(wardenClient warden.Client, registry registry.Registry, waitGroup *sync.WaitGroup, logger *gosteno.Logger) http.Handler {
return &handler{
wardenClient: wardenClient,
registry: registry,
waitGroup: waitGroup,
logger: logger,
}
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.waitGroup.Add(1)
defer h.waitGroup.Done()
guid := r.FormValue(":guid")
container, err := h.registry.FindByGuid(guid)
if err != nil {
handleError(err, w, h.logger)
return
}
//TODO once wardenClient has an ErrNotFound error code, use it
//to determine if we should delete from registry
if container.ContainerHandle != "" {
h.wardenClient.Destroy(container.ContainerHandle)
}
err = h.registry.Delete(guid)
if err != nil {
handleError(err, w, h.logger)
return
}
w.WriteHeader(http.StatusOK)
}
func handleError(err error, w http.ResponseWriter, logger *gosteno.Logger) {
if err == registry.ErrContainerNotFound {
logger.Infod(map[string]interface{}{
"error": err.Error(),
}, "executor.delete-container.not-found")
w.WriteHeader(http.StatusNotFound)
return
}
logger.Errord(map[string]interface{}{
"error": err.Error(),
}, "executor.delete-container.failed")
w.WriteHeader(http.StatusInternalServerError)
}
|
package spider
import (
"spider/entity"
"spider/parser"
)
type MySpider interface {
DocumentParsing(url string, parser parser.Parser) []entity.JobInfo //执行爬虫
}
|
package collector
import (
"context"
"fmt"
"net/http"
"time"
io_prometheus_client "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
)
type NodeStats struct {
CPUUser float64 `json:"user"`
CPUSystem float64 `json:"system"`
CPUIdle float64 `json:"idle"`
CPUIOWait float64 `json:"iowait"`
Froks float64 `json:"forks"`
DiskUsage float64 `json:"disk"`
Load float64 `json:"load"`
MemAvailable float64 `json:"available"`
MemTotal float64 `json:"total"`
NetRev float64 `json:"recived"`
NetTra float64 `json:"transmitted"`
CPUUserDelta float64 `json:"duser"`
CPUSystemDelta float64 `json:"dsystem"`
CPUIdleDelta float64 `json:"didle"`
CPUIOWaitDelta float64 `json:"diowait"`
ForksDelta float64 `json:"dfork"`
MemUsage float64 `json:"mem"`
}
func CreateNodeStats(values map[string]*io_prometheus_client.MetricFamily) NodeStats {
u, s, i, o := CPUStats(values["node_cpu"])
stats := NodeStats{
u,
s,
i,
o,
SumCounters(values["node_forks_total"]),
SumGauge(values["node_disk_io_now"]),
SumGauge(values["node_load1"]),
SumGauge(values["node_memory_MemAvailable"]),
SumGauge(values["node_memory_MemTotal"]),
SumGauge(values["node_network_receive_bytes"]),
SumGauge(values["node_network_transmit_bytes"]),
0, 0, 0, 0, 0, 0,
}
stats.MemUsage = SumGauge(values["node_memory_Active"])/stats.MemTotal
return stats
}
func (m *NodeStats) update(stats NodeStats) {
m.CPUUserDelta = m.CPUUser - stats.CPUUser
m.CPUSystemDelta = m.CPUSystem - stats.CPUSystem
m.CPUIdleDelta = m.CPUIdle - stats.CPUIdle
m.CPUIOWaitDelta = m.CPUIOWait - stats.CPUIOWait
m.ForksDelta = m.Froks - stats.Froks
m.MemUsage = stats.MemAvailable / stats.MemTotal
m.CPUUser = stats.CPUUser
m.CPUSystem = stats.CPUSystem
m.CPUIdle = stats.CPUIdle
m.CPUIOWait = stats.CPUIOWait
m.MemTotal = stats.MemTotal
m.MemAvailable = stats.MemAvailable
m.Froks = stats.Froks
m.DiskUsage = stats.DiskUsage
m.Load = stats.Load
m.NetRev = stats.NetRev
m.NetTra = stats.NetTra
}
func CPUStats(metric *io_prometheus_client.MetricFamily) (float64, float64, float64, float64) {
var user float64 = 0
var system float64 = 0
var idle float64 = 0
var iowait float64 = 0
for _, v := range metric.Metric {
if LabelMatcher(v.Label, "mode", "iowait") {
iowait += *v.Counter.Value
}
if LabelMatcher(v.Label, "mode", "user") {
user += *v.Counter.Value
}
if LabelMatcher(v.Label, "mode", "system") {
system += *v.Counter.Value
}
if LabelMatcher(v.Label, "mode", "idle") {
idle += *v.Counter.Value
}
}
return user, system, idle, iowait
}
func LabelMatcher(labels []*io_prometheus_client.LabelPair, key, val string) bool {
for _, l := range labels {
if l.Name != nil && l.Value != nil && *l.Name == key && *l.Value == val {
return true
}
}
return false
}
func SumCounters(metrics *io_prometheus_client.MetricFamily) float64 {
var sum float64 = 0
if metrics != nil {
for _, v := range metrics.Metric {
sum += *v.Counter.Value
}
}
return sum
}
func SumGauge(metrics *io_prometheus_client.MetricFamily) float64 {
var sum float64 = 0
if metrics != nil {
for _, v := range metrics.Metric {
sum += *v.Gauge.Value
}
return sum / float64(len(metrics.Metric))
}
return 0
}
func prometheusCollector(ctx context.Context, name, url string, stream chan NodeMetrics, errors chan error, filter []string, refreshInterval time.Duration) {
parser := expfmt.TextParser{}
for {
resp, err := http.Get(url)
if err != nil {
errors <- err
} else {
metrics, err := parser.TextToMetricFamilies(resp.Body)
if err != nil {
errors <- err
} else {
data := make(map[string]*io_prometheus_client.MetricFamily)
for _, key := range filter {
if val, ok := metrics[key]; ok {
data[key] = val
}
}
stream <- NodeMetrics{name, data}
resp.Body.Close()
}
}
select {
case _ = <-time.After(refreshInterval):
//nothing
case _ = <-ctx.Done():
fmt.Printf("[%s] cacneld", name)
return
}
}
}
|
package gatekeeper
import (
"fmt"
"log"
)
type Protocol uint
const (
HTTPPublic Protocol = iota + 1
HTTPInternal
HTTPSPublic
HTTPSInternal
)
var formattedProtocols = map[Protocol]string{
HTTPPublic: "http-public",
HTTPInternal: "http-internal",
HTTPSPublic: "https-public",
HTTPSInternal: "https-internal",
}
func (p Protocol) String() string {
str, ok := formattedProtocols[p]
if !ok {
log.Fatal("programming error; unformatted protocol")
}
return str
}
func ParseProtocol(value string) (Protocol, error) {
for protocol, str := range formattedProtocols {
if str == value {
return protocol, nil
}
}
return Protocol(0), fmt.Errorf("unknown protocol")
}
func ParseProtocols(values []string) ([]Protocol, error) {
protocols := make([]Protocol, len(values))
for idx, value := range values {
protocol, err := ParseProtocol(value)
if err != nil {
return []Protocol(nil), err
}
protocols[idx] = protocol
}
return protocols, nil
}
// TODO: remove this method
func NewProtocol(value string) (Protocol, error) {
for protocol, str := range formattedProtocols {
if str == value {
return protocol, nil
}
}
return Protocol(0), fmt.Errorf("unknown protocol")
}
// TODO: remove this method
func NewProtocols(values []string) ([]Protocol, error) {
protocols := make([]Protocol, len(values))
for idx, value := range values {
protocol, err := NewProtocol(value)
if err != nil {
return []Protocol(nil), err
}
protocols[idx] = protocol
}
return protocols, nil
}
|
package main
import (
"fmt"
"github.com/tarantool/go-tarantool"
"log"
"net/http"
"time"
)
func info(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "{\"status\": \"OK\"}")
}
const (
masterUri string = "127.0.0.1:3315"
slaveUri string = "127.0.0.1:3316"
)
var (
node *tarantool.Connection
master *tarantool.Connection
slave *tarantool.Connection
err error
)
func connect(uri string) *tarantool.Connection {
var conn *tarantool.Connection
opts := tarantool.Opts{
Timeout: 1000 * time.Millisecond,
}
maxTry := 10
i := 0
for i < maxTry {
conn, err = tarantool.Connect(uri, opts)
if err != nil {
log.Printf("Node '%s' is unavailable\n", uri)
time.Sleep(1000 * time.Millisecond)
} else {
log.Printf("Connected to %s\n", uri)
break
}
i++
}
return conn
}
func main() {
master = connect(masterUri)
slave = connect(slaveUri)
count := bankInitial()
log.Printf("Load errors: %d\n", count)
node = master
http.HandleFunc("/", handler)
http.HandleFunc("/bank", bankHandler)
http.HandleFunc("/tx", txHandler)
http.HandleFunc("/problem", problemHandler)
http.HandleFunc("/_info", info)
log.Println("Ready 8890")
err = http.ListenAndServe(":8890", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
|
package main
import (
"github.com/gin-gonic/gin"
)
var (
conf *Conf
)
func getServiceOrFail(c *gin.Context, sn string) *Service {
service, ok := conf.Services[sn]
if !ok {
c.JSON(200, gin.H{
"message": "unknown service",
"service": sn,
"error": true,
})
return nil
}
return service
}
func getStatus(sn string, s *Service) (status_code int, json gin.H) {
status, err := s.Status()
if err != nil {
return 500, gin.H{
"message": "error retrieving process status (wrong service configuration?)",
"service": sn,
"error": true,
}
}
return 200, gin.H{
"running": status,
"service": sn,
}
}
func status(c *gin.Context) {
sn := c.Param("name")
service := getServiceOrFail(c, sn)
if service == nil {
return
}
sc, result := getStatus(sn, service)
c.JSON(sc, result)
}
func list(c *gin.Context) {
var out []gin.H
for sn, service := range conf.Services {
_, result := getStatus(sn, service)
out = append(out, result)
}
c.JSON(200, out)
}
func change(c *gin.Context) {
sn := c.Param("name")
service := getServiceOrFail(c, sn)
service.Start()
c.JSON(200, gin.H{
"message": "started",
})
}
func main() {
conf = parseConf("webctrl.yml")
r := gin.Default()
r.GET("/service/", list)
r.GET("/service/:name", status)
r.PUT("/service/:name", change)
r.Run() // listen and serve on 0.0.0.0:8080
}
|
package netutil_test
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/AdguardTeam/golibs/netutil"
)
func ExampleHostPort_MarshalText() {
resp := struct {
Hosts []netutil.HostPort `json:"hosts"`
}{
Hosts: []netutil.HostPort{{
Host: "example.com",
Port: 12345,
}, {
Host: "example.org",
Port: 23456,
}},
}
err := json.NewEncoder(os.Stdout).Encode(resp)
if err != nil {
panic(err)
}
respPtrs := struct {
HostPtrs []*netutil.HostPort `json:"host_ptrs"`
}{
HostPtrs: []*netutil.HostPort{{
Host: "example.com",
Port: 12345,
}, {
Host: "example.org",
Port: 23456,
}},
}
err = json.NewEncoder(os.Stdout).Encode(respPtrs)
if err != nil {
panic(err)
}
// Output:
//
// {"hosts":["example.com:12345","example.org:23456"]}
// {"host_ptrs":["example.com:12345","example.org:23456"]}
}
func ExampleHostPort_String() {
hp := &netutil.HostPort{
Host: "example.com",
Port: 12345,
}
fmt.Println(hp)
hp.Host = "1234::cdef"
fmt.Println(hp)
hp.Port = 0
fmt.Println(hp)
hp.Host = ""
fmt.Println(hp)
// Output:
//
// example.com:12345
// [1234::cdef]:12345
// [1234::cdef]:0
// :0
}
func ExampleHostPort_UnmarshalText() {
resp := &struct {
Hosts []netutil.HostPort `json:"hosts"`
}{}
r := strings.NewReader(`{"hosts":["example.com:12345","example.org:23456"]}`)
err := json.NewDecoder(r).Decode(resp)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", resp.Hosts[0])
fmt.Printf("%#v\n", resp.Hosts[1])
respPtrs := &struct {
HostPtrs []*netutil.HostPort `json:"host_ptrs"`
}{}
r = strings.NewReader(`{"host_ptrs":["example.com:12345","example.org:23456"]}`)
err = json.NewDecoder(r).Decode(respPtrs)
if err != nil {
panic(err)
}
fmt.Printf("%#v\n", respPtrs.HostPtrs[0])
fmt.Printf("%#v\n", respPtrs.HostPtrs[1])
fmt.Println()
r = strings.NewReader(`{"host_ptrs":["example.com:99999","example.org:99999"]}`)
err = json.NewDecoder(r).Decode(respPtrs)
isOutOfRange := err.Error() == `bad hostport address "example.com:99999": `+
`parsing port: strconv.ParseUint: parsing "99999": value out of range`
fmt.Printf("got the expected error: %t", isOutOfRange)
// Output:
//
// netutil.HostPort{Host:"example.com", Port:12345}
// netutil.HostPort{Host:"example.org", Port:23456}
// &netutil.HostPort{Host:"example.com", Port:12345}
// &netutil.HostPort{Host:"example.org", Port:23456}
//
// got the expected error: true
}
|
package queries
import (
"database/sql"
_ "github.com/lib/pq"
"golang.org/x/crypto/blake2b"
"log"
"strings"
)
func getDb() *sql.DB {
connStr := "user=anani dbname=lims port=5050 host=localhost password=mypassword sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
return nil
} else {
return db
}
}
func addSalt(inputString *string) {
*inputString = strings.Join([]string{*inputString, "1234"}, "")
}
func HashPassword(inputPassword *string) {
addSalt(inputPassword)
hashed := blake2b.Sum512([]byte(*inputPassword))
myBytes := make([]byte, len(hashed))
for i := 0; i < len(hashed); i++ {
myBytes[i] = hashed[i]
}
myString := string(myBytes)
*inputPassword = myString
}
|
package main
import "fmt"
//结构体嵌套结构体
//父类
type Person struct {
id int
name string
age int
}
//子类
type Student struct {
Person //匿名字段
score int
}
func main0101() {
//对象创建
//顺序初始化
var s1 Student = Student{Person{101,"小明",18},98}
fmt.Println(s1)
//var p1 Person = Person{102,"小亮",28}
//fmt.Println(p1)
//自动推导类型
s2 := Student{Person{102,"小亮",28},87}
fmt.Println(s2)
//指定初始化成员 没有初始化的部分 使用默认值
s3 := Student{score:97}
fmt.Println(s3)
s4 := Student{Person{name:"小红"},100}
fmt.Println(s4)
}
func main() {
var s1 Student = Student{Person{101,"小明",18},98}
s1.score = 89
s1.Person.age = 20
s1.age = 30
s1.Person = Person{110,"小兰",20}
fmt.Println(s1)
} |
package enter
import (
"encoding/json"
"github.com/ttooch/payment/helper"
)
type QueryEnter struct {
*QueryConf
BaseCharge
}
type QueryConf struct {
AccountNo string `json:"accountNo"` //商户登陆账号
}
type QueryReturn struct {
AccountNo string `json:"accountNo"`
Status string `json:"status"`
AccountType string `json:"accountType"`
MerchantName string `json:"merchantName"`
MerchantMail string `json:"merchantMail"`
PhoneNo string `json:"phoneNo"`
SettleInfo string `json:"settleInfo"`
FeeInfo string `json:"feeInfo"`
FeeStartTime string `json:"feeStartTime"`
FeeEndTime string `json:"feeEndTime"`
}
func (en *QueryEnter) Handle(conf *QueryConf) (interface{}, error) {
err := en.BuildData(conf)
if err != nil {
return nil, err
}
en.SetSign()
ret, err := en.SendReq(EnterUrl, en)
if err != nil {
return nil, err
}
return en.RetData(ret)
}
func (en *QueryEnter) RetData(ret []byte) (*QueryReturn, error) {
ret, err := en.BaseCharge.RetData(ret)
if err != nil {
return nil, err
}
modifyReturn := new(QueryReturn)
err = json.Unmarshal(ret, &modifyReturn)
if err != nil {
return nil, err
}
return modifyReturn, nil
}
func (en *QueryEnter) BuildData(conf *QueryConf) error {
b, err := json.Marshal(conf)
if err != nil {
return err
}
en.QueryConf = conf
en.ServiceName = "merchant.enter.query"
encryptData, err := helper.Rsa1Encrypt(en.PfxData, b, en.CertPassWord)
if err != nil {
return err
}
en.EncryptData = encryptData
return nil
}
|
package leetcode
/*
* LeetCode T509. 斐波那契数
* https://leetcode-cn.com/problems/fibonacci-number/
* 面试题10- I. 斐波那契数列
* https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/
* 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。
* 该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。
* 给定 N,计算 F(N)。
*/
// 方法 1:递归法(暴力解)
// 时间复杂度 O(N^2)
// 由于存在大量重复计算,会报错“超出时间限制”
func Fib(n int) int {
if n == 0 {
return 0
}
if n == 1 || n == 2 {
return 1
}
return (Fib(n-1) + Fib(n-2)) % 1000000007
}
// 方法 2:备忘录递归(自顶向下)
// 上面方法中存在的重复计算问题,可以使用使用一个数组存放已经计算过的值,
// 当数组中有的话,直接从数组中取到,否则进行递归运算
// 时间复杂度和空间复杂度为 O(N)
func Fib2(n int) int {
memo := make([]int, n+1)
var _helper func(int) int
_helper = func(n int) int {
if n == 0 {
return 0
}
if n == 1 || n == 2 {
return 1
}
if memo[n] != 0 {
return memo[n]
}
memo[n] = (_helper(n-1) + _helper(n-2)) % 1000000007
return memo[n]
}
return _helper(n)
}
// 方法 3:动态规划(自底向上)
// 状态定义: 设 dp 为一维数组,其中 dp[i] 的值代表斐波那契数列第 i 个数字
// 转移方程: dp[i] = dp[i-1] + dp[i-2] ,即对应数列定义 f(n) = f(n-1) + f(n-2)
// 初始状态: dp[0] = 0 dp[1] = 1 ,即初始化前两个数字
// 返回值: dp[n] ,即斐波那契数列的第 n 个数字
// 时间复杂度 O(N),空间复杂度为 O(1)
func Fib3(n int) int {
if n == 0 {
return 0
}
dp := make([]int, n+1)
// 初始状态
dp[0], dp[1] = 0, 1
for i := 2; i <= n; i++ {
// 转移方程
dp[i] = (dp[i-1] + dp[i-2]) % 1000000007
}
// 返回值
return dp[n]
}
// 方法 4
// 进一步优化
// f(n) 只跟 f(n-1) 和 f(n-2) 有关,所以只需要保留前两个值,以及和值,不断进行迭代
// 设正整数 x, y, p,求余符号为 ⊙,那么(x + y) ⊙ p = (x ⊙ p + y ⊙ p) ⊙ p
// 时间复杂度 O(N),空间复杂度为 O(1)
func Fib4(n int) int {
if n == 0 {
return 0
}
if n == 1 || n == 2 {
return 1
}
sum := 0
prev, curr := 1, 1
for i := 3; i <= n; i++ {
sum = (prev + curr) % 1000000007
prev = curr
curr = sum
}
return curr
}
/*
* LeetCode T322. 零钱兑换
* https://leetcode-cn.com/problems/coin-change/
*
* 给定不同面额的硬币 coins 和一个总金额 amount。
* 编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1
* 示例 1:
* 输入: coins = [1, 2, 5], amount = 11
* 输出: 3
* 解释: 11 = 5 + 5 + 1
*
* 示例 2:
* 输入: coins = [2], amount = 3
* 输出: -1
*
* 说明:你可以认为每种硬币的数量是无限的。
*/
// 方法 1:备忘录递归(自顶向下)
// count 数组保存已经计算过的 amount
// 假设 N 为金额,M 为面额数
// 时间复杂度 = 子问题数目 * 每个子问题的时间,所以为 O(MN)
// 因为有一个备忘录数组,所以空间复杂度为 O(N)
func CoinChange(coins []int, amount int) int {
// 状态定义
count := make([]int, amount+1)
var _dp func(int) int
_dp = func(n int) int {
if n == 0 { // amount 为 0,需要 0 个硬币
return 0
}
// 查看备忘录,避免重复计算
if count[n] != 0 {
return count[n]
}
// 凑成 amount 金额的硬币数最多只可能等于 amount(全部用 1 元面值的硬币)
// 初始化为 amount+1就相当于初始化为正无穷,便于后续取最小值
count[n] = amount + 1
for _, coin := range coins {
if n-coin < 0 { // 子问题无解跳过
continue
}
// 记入备忘录,转移方程
count[n] = min(count[n], _dp(n-coin)+1)
}
return count[n]
}
res := _dp(amount)
if res == amount+1 {
return -1
}
return res
}
// 方法 2:动态规划(自下而上)
// 时间复杂度 O(MN),空间复杂度为 O(N)
// 将方法 1 中的递归转换成迭代
func CoinChange2(coins []int, amount int) int {
dpLen := amount + 1
dp := make([]int, dpLen)
for n := 1; n < dpLen; n++ {
dp[n] = amount + 1
for _, coin := range coins {
if n-coin < 0 {
continue
}
dp[n] = min(dp[n], dp[n-coin]+1)
}
}
if dp[amount] == amount+1 {
return -1
}
// 省去了 amount = 0 的检查,初始值 dp[0] = 0
return dp[amount]
}
/*
* LeetCode T53. 最大子序和
* https://leetcode-cn.com/problems/maximum-subarray/
*
* 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
* 示例 1:
* 输入: [-2,1,-3,4,-1,2,1,-5,4],
* 输出: 6
* 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
*/
// 方法 1:动态规划
func MaxSubArray(nums []int) int {
numsLen := len(nums)
// 1.定义状态:dp[i] 表示以 i 结尾子串的最大值
dp := make([]int, numsLen)
// 3.初始化:找到初始条件
dp[0] = nums[0]
for i := 1; i < numsLen; i++ {
// 第 i 个子组合的最大值可以通过第 i-1 个子组合的最大值和第 i 个数字获得
// 2.状态转移方程,如果 dp[i-1] 不能带来正增益的话,那么丢弃以前的最大值
if dp[i-1] > 0 {
dp[i] = dp[i-1] + nums[i]
} else {
// 抛弃前面的结果
dp[i] = nums[i]
}
}
max := nums[0]
// 4.选出结果
for _, sum := range dp {
if sum > max {
max = sum
}
}
return max
}
// 动态规划的优化
func MaxSubArray2(nums []int) int {
// 状态压缩:每次状态的更新只依赖于前一个状态,就是说 dp[i] 的更新只取决于 dp[i-1] ,
// 我们只用一个存储空间保存上一次的状态即可。
// var start, end, subStart, subEnd int // 可以获得最大和子序列的边界位置
sum := nums[0]
maxSum := nums[0]
numsLen := len(nums)
for i := 1; i < numsLen; i++ {
if sum > 0 {
sum += nums[i]
// subEnd++
} else {
sum = nums[i]
// subStart = i
// subEnd = i
}
if maxSum < sum {
maxSum = sum
// start = subStart
// end = subEnd
}
}
return maxSum
}
// 方法 2:Kadane算法
func MaxSubArray3(nums []int) int {
sum := nums[0]
maxSum := nums[0]
for _, num := range nums {
sum = maxInt(num, sum+num) // sum 能否提供正增益,与 dp 解法其实是一致的
if maxSum < sum {
maxSum = sum
}
}
return maxSum
}
// 方法 3:分治法
// 时间复杂度 O(nlogn)
func min(x, y int) int {
if x < y {
return x
}
return y
}
/*
* LeetCode T70. 爬楼梯
* https://leetcode-cn.com/problems/climbing-stairs/
*
* 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
* 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
* 注意:给定 n 是一个正整数。
*/
// 状态 n,n 阶台阶共有 f(n) 种不同的方法
// dp 状态转移方程,f(n) = f(n-1) + f(n-2),一次只能走 1 或 2 个台阶,所以 f(n) 可以从 f(n-1) 到达,也可以从 f(n-2)到达
// 边界值 f(0) = 1, f(1) = 1
// 这个问题转换完跟斐波拉契数列是一样的,其他解法可以参考
func climbStairs(n int) int {
if n == 0 || n == 1 {
return 1
}
first, second := 1, 1
res := 0
for i := 2; i <= n; i++ {
res = first + second
first = second
second = res
}
return res
}
// 方法 1:dp table,自底而上
// 状态:i,f(i) = max(f(i-1), nums[i]+f(i-2))
// 选择: 第 i 间房屋,偷还是不偷
// 偷窃第 i 间房屋,那么就不能偷窃第 i−1 间房屋,偷窃总金额为前 i−2 间房屋的最高总金额与第 i 间房屋的金额之和。
// 不偷窃第 i 间房屋,偷窃总金额为前 i−1 间房屋的最高总金额
// 边界条件:只有1间房屋,则偷窃该房屋; 只有两间房屋,选择其中金额较高的房屋进行偷窃
// 状态 -> 选择 -> 状态转移方程 -> 边界条件
func rob(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
if n == 1 {
return nums[0]
}
dp := make([]int, n)
// 边界条件
dp[0] = nums[0]
dp[1] = maxInt(nums[0], nums[1])
for i := 2; i < n; i++ {
dp[i] = maxInt(dp[i-1], nums[i]+dp[i-2])
}
return dp[n-1]
}
// 因为 dp[i] 只与dp[i-1] 和 dp[i-2] 有关,所以可以使用滚动数组存储前两次的结果,
// 使空间复杂度从 O(n) 降为 O(1)
func rob2(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
if n == 1 {
return nums[0]
}
first := nums[0]
second := maxInt(nums[0], nums[1])
for i := 2; i < n; i++ {
temp := maxInt(second, nums[i]+first)
first = second
second = temp
}
return second
}
// 方法 3:memo 备忘录,自顶而下
func rob3(nums []int) int {
n := len(nums)
memo := make([]int, n)
for i := range memo {
memo[i] = -1
}
var _dp func(int) int
_dp = func(i int) int {
if i >= n || i < 0 {
return 0
}
if i == 0 {
return nums[0]
}
if memo[i] != -1 {
return memo[i]
}
res := maxInt(_dp(i-1), nums[i]+_dp(i-2))
memo[i] = res
return res
}
return _dp(n - 1)
}
|
//-----------------------------------------------Paquetes E Imports-----------------------------------------------------
package Metodos
import (
"../Variables"
"fmt"
)
//---------------------------------------------------Variables----------------------------------------------------------
var miDisco int
var discoBinario []bool
var EspaciosDisponibles [200]Espacio
//--------------------------------------------------Estructura----------------------------------------------------------
type Espacio struct {
P1 int
Tamano int
Disponible bool
}
//----------------------------------------------------Métodos-----------------------------------------------------------
func GeneraEspacios() {
elemento := 0
limpiaVacios()
for i:=0; i<= miDisco -1 ; i++ {
if i <= 0 && !discoBinario[i] {
EspaciosDisponibles[elemento].P1 = 0
EspaciosDisponibles[elemento].Disponible = true
}
if i > 0 && i <= miDisco - 1 && discoBinario[i -1] && !discoBinario[i] {
elemento++
EspaciosDisponibles[elemento].P1 = i
EspaciosDisponibles[elemento].Disponible = true
}
sumaVacios(i, elemento)
}
}
func sumaVacios(inicio int, elemento int) {
if !discoBinario[inicio] {
EspaciosDisponibles[elemento].Tamano++
}
}
func limpiaVacios(){
for i:= 0; i<= 200 - 1; i++{
EspaciosDisponibles[i].Tamano = 0
EspaciosDisponibles[i].P1 = 0
EspaciosDisponibles[i].Disponible = false
}
}
func LimpiaDisco(){
discoBinario = make([]bool,0)
}
func LlenaDisco(inicio int, tamano int){
for i:= inicio; i<=inicio + tamano - 1; i++ {
discoBinario[i] = true
}
}
func CreaDisco( Disco int){
miDisco = Disco
for i :=0; i<= miDisco - 1; i++ {
discoBinario = append(discoBinario, false)
}
}
func TamanoLibreTotal() int {
var total int
for i := 0; i<= 200 - 1 ;i++ {
if EspaciosDisponibles[i].Disponible {
total = total + EspaciosDisponibles[i].Tamano
}
}
return total
}
func TamanoOcupadoTotal() int {
var total int
total = 0
for i := 0; i<= miDisco - 1 ;i++ {
if discoBinario[i] {
total++
}
}
return total
}
func MostrarEspacios() {
siExiste := true
for i := 0; i<= 200 - 1; i++ {
if EspaciosDisponibles[i].Disponible {
fmt.Println("espacios vacios: inicio ", EspaciosDisponibles[i].P1," tamaño ", EspaciosDisponibles[i].Tamano)
siExiste = false
}
}
if siExiste {
fmt.Println("espacios vacios no hay disponibilidad")
}
}
func LLenarParticiones(MBRAuxiliar Variables.MBREstructura) {
//Verificar Particiones
if MBRAuxiliar.Particion1MBR.SizePart != 0 {
LlenaDisco(int(MBRAuxiliar.Particion1MBR.InicioPart), int(MBRAuxiliar.Particion1MBR.SizePart))
}
if MBRAuxiliar.Particion2MBR.SizePart != 0 {
LlenaDisco(int(MBRAuxiliar.Particion2MBR.InicioPart), int(MBRAuxiliar.Particion2MBR.SizePart))
}
if MBRAuxiliar.Particion3MBR.SizePart != 0 {
LlenaDisco(int(MBRAuxiliar.Particion3MBR.InicioPart), int(MBRAuxiliar.Particion3MBR.SizePart))
}
if MBRAuxiliar.Particion4MBR.SizePart != 0 {
LlenaDisco(int(MBRAuxiliar.Particion4MBR.InicioPart), int(MBRAuxiliar.Particion4MBR.SizePart))
}
}
func LLenarParticionesAdd(MBRAuxiliar Variables.MBREstructura, NumeroParticion int) {
//Verificar Particiones
if MBRAuxiliar.Particion1MBR.SizePart != 0 && NumeroParticion != 1 {
LlenaDisco(int(MBRAuxiliar.Particion1MBR.InicioPart), int(MBRAuxiliar.Particion1MBR.SizePart))
}
if MBRAuxiliar.Particion2MBR.SizePart != 0 && NumeroParticion != 2 {
LlenaDisco(int(MBRAuxiliar.Particion2MBR.InicioPart), int(MBRAuxiliar.Particion2MBR.SizePart))
}
if MBRAuxiliar.Particion3MBR.SizePart != 0 && NumeroParticion != 3 {
LlenaDisco(int(MBRAuxiliar.Particion3MBR.InicioPart), int(MBRAuxiliar.Particion3MBR.SizePart))
}
if MBRAuxiliar.Particion4MBR.SizePart != 0 && NumeroParticion != 4 {
LlenaDisco(int(MBRAuxiliar.Particion4MBR.InicioPart), int(MBRAuxiliar.Particion4MBR.SizePart))
}
}
|
package localcache
import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/assert"
"github.com/JokeTrue/otus-golang/hw12_13_14_15_calendar/pkg/models"
"github.com/google/uuid"
)
func createEvent(t *testing.T) *models.Event {
ev, err := models.NewEvent(
uuid.New(),
1,
"Встреча #1",
"Встреча на метро Аэропорт",
"2020-06-05T10:05:00",
"2020-06-05T14:05:00",
time.Duration(3600),
)
assert.NoError(t, err)
return ev
}
func TestDeleteEvent(t *testing.T) {
ev1 := createEvent(t)
s := NewEventLocalStorage()
_, err := s.CreateEvent(ev1)
assert.NoError(t, err)
err = s.DeleteEvent(1, ev1.ID)
assert.NoError(t, err)
err = s.DeleteEvent(1, ev1.ID)
assert.Equal(t, err, ErrEventNotFound)
}
func TestCreateEvent(t *testing.T) {
ev1 := createEvent(t)
s := NewEventLocalStorage()
id, err := s.CreateEvent(ev1)
assert.NoError(t, err)
assert.Equal(t, ev1.ID, id)
}
func TestRetrieveEvent(t *testing.T) {
ev1 := createEvent(t)
s := NewEventLocalStorage()
retrieved, err := s.RetrieveEvent(1, uuid.New())
assert.Equal(t, ErrEventNotFound, err)
id, err := s.CreateEvent(ev1)
assert.NoError(t, err)
retrieved, err = s.RetrieveEvent(1, id)
assert.Equal(t, ev1, retrieved)
}
func TestGetEvents(t *testing.T) {
s := NewEventLocalStorage()
cases := []struct {
name string
interval models.Interval
startDate, endDate string
}{
{name: "day interval", interval: models.DayInterval, startDate: "2020-06-01", endDate: "2020-06-02"},
{name: "week interval", interval: models.WeekInterval, startDate: "2020-06-05", endDate: "2020-06-06"},
{name: "month interval", interval: models.MonthInterval, startDate: "2020-06-25", endDate: "2020-06-28"},
}
// Create Events
createdEvents := make([]*models.Event, 0)
for _, c := range cases {
ev := createEvent(t)
parsedDT, err := time.Parse("2006-01-02", c.startDate)
assert.NoError(t, err)
ev.StartDate = parsedDT
_, err = s.CreateEvent(ev)
assert.NoError(t, err)
createdEvents = append(createdEvents, ev)
}
for i, c := range cases {
startDate, err := time.Parse("2006-01-02", "2020-06-01")
assert.NoError(t, err)
endDate, err := time.Parse("2006-01-02", c.endDate)
assert.NoError(t, err)
list, err := s.GetUserEvents(1, startDate, endDate)
assert.NoError(t, err)
require.Len(t, list, i+1)
}
}
|
package bbox
import (
"fmt"
"time"
"github.com/siggy/bbox/beatboxer/wavs"
)
const (
DEFAULT_BPM = 120
MIN_BPM = 30
MAX_BPM = 480
SOUNDS = 4
BEATS = 16
DEFAULT_TICKS_PER_BEAT = 10
DEFAULT_TICKS = BEATS * DEFAULT_TICKS_PER_BEAT
TEMPO_DECAY = 3 * time.Minute
)
type Interval struct {
TicksPerBeat int
Ticks int
}
type Beats [SOUNDS][BEATS]bool
type Loop struct {
beats Beats
closing chan struct{}
msgs <-chan Beats
bpmCh chan int
bpm int
tempo <-chan int
tempoDecay *time.Timer
ticks []chan<- int
wavs *wavs.Wavs
iv Interval
intervalCh []chan<- Interval
}
var sounds = []string{
"hihat-808.wav",
"kick-classic.wav",
"perc-808.wav",
"tom-808.wav",
}
func InitLoop(
msgs <-chan Beats,
tempo <-chan int,
ticks []chan<- int,
intervalCh []chan<- Interval,
) *Loop {
return &Loop{
beats: Beats{},
bpmCh: make(chan int),
bpm: DEFAULT_BPM,
closing: make(chan struct{}),
msgs: msgs,
tempo: tempo,
ticks: ticks,
wavs: wavs.InitWavs(),
intervalCh: intervalCh,
iv: Interval{
TicksPerBeat: DEFAULT_TICKS_PER_BEAT,
Ticks: DEFAULT_TICKS,
},
}
}
func (l *Loop) Run() {
ticker := time.NewTicker(l.bpmToInterval(l.bpm))
defer ticker.Stop()
tick := 0
tickTime := time.Now()
for {
select {
case _, more := <-l.closing:
if !more {
fmt.Printf("Loop trying to close\n")
// return
}
case beats, more := <-l.msgs:
if more {
// incoming beat update from keyboard
l.beats = beats
} else {
// closing
l.wavs.Close()
fmt.Printf("Loop closing\n")
return
}
case bpm, more := <-l.bpmCh:
if more {
// incoming bpm update
l.bpm = bpm
// BPM: 30 -> 60 -> 120 -> 240 -> 480.0
// TPB: 40 -> 20 -> 10 -> 5 -> 2.5
l.iv.TicksPerBeat = 1200 / l.bpm
l.iv.Ticks = BEATS * l.iv.TicksPerBeat
for _, ch := range l.intervalCh {
ch <- l.iv
}
ticker.Stop()
ticker = time.NewTicker(l.bpmToInterval(l.bpm))
defer ticker.Stop()
} else {
// we should never get here
fmt.Printf("closed on bpm, invalid state")
panic(1)
}
case tempo, more := <-l.tempo:
if more {
// incoming tempo update from keyboard
if (l.bpm > MIN_BPM || tempo > 0) &&
(l.bpm < MAX_BPM || tempo < 0) {
go l.setBpm(l.bpm + tempo)
// set a decay timer
if l.tempoDecay != nil {
l.tempoDecay.Stop()
}
l.tempoDecay = time.AfterFunc(TEMPO_DECAY, func() {
l.setBpm(DEFAULT_BPM)
})
}
} else {
// we should never get here
fmt.Printf("unexpected: tempo return no more\n")
return
}
case <-ticker.C: // for every time interval
// next interval
tick = (tick + 1) % l.iv.Ticks
tmp := tick
for _, ch := range l.ticks {
ch <- tmp
}
// for each beat type
if tick%l.iv.TicksPerBeat == 0 {
for i, beat := range l.beats {
if beat[tick/l.iv.TicksPerBeat] {
// initiate playback
l.wavs.Play(sounds[i])
}
}
}
t := time.Now()
tbprint(0, 5, fmt.Sprintf("______BPM:__%+v______", l.bpm))
tbprint(0, 6, fmt.Sprintf("______int:__%+v______", l.bpmToInterval(l.bpm)))
tbprint(0, 7, fmt.Sprintf("______time:_%+v______", t.Sub(tickTime)))
tbprint(0, 8, fmt.Sprintf("______tick:_%+v______", tick))
tickTime = t
}
}
}
func (l *Loop) Close() {
// TODO: this doesn't block?
close(l.closing)
}
func (l *Loop) bpmToInterval(bpm int) time.Duration {
return 60 * time.Second / time.Duration(bpm) / (BEATS / 4) / time.Duration(l.iv.TicksPerBeat) // 4 beats per interval
}
func (l *Loop) setBpm(bpm int) {
l.bpmCh <- bpm
}
|
package odor
import (
"syscall"
"github.com/chifflier/nfqueue-go/nfqueue"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
)
var netFilterStatic *NetFilter
// PacketHandler interface that implements the callback to handle a packet.
type PacketHandler interface {
HandlePacket(context *Context) FilterAction
}
// NetFilter provides some operations over a NetFilter queue.
type NetFilter struct {
queue *nfqueue.Queue
handler PacketHandler
}
// NewNetFilter creates a NetFilter object.
func NewNetFilter(handler PacketHandler) *NetFilter {
queue := new(nfqueue.Queue)
netFilter := &NetFilter{
queue: queue,
handler: handler,
}
netFilterStatic = netFilter
queue.SetCallback(staticCallback)
return netFilter
}
func staticCallback(payload *nfqueue.Payload) int {
return netFilterStatic.Callback(payload)
}
// Start the NetFilter queue.
func (n *NetFilter) Start(queueNum int) {
n.queue.Init()
n.queue.Unbind(syscall.SOCK_PACKET)
n.queue.Bind(syscall.SOCK_PACKET)
n.queue.CreateQueue(queueNum)
n.queue.Loop()
}
// Stop the NetFilter queue.
func (n *NetFilter) Stop() {
n.queue.DestroyQueue()
n.queue.Close()
}
// Callback to handle a packet from NetFilter queue.
func (n NetFilter) Callback(payload *nfqueue.Payload) int {
// Decode a packet
packet := gopacket.NewPacket(payload.Data, layers.LayerTypeIPv4, gopacket.Default)
context := &Context{
PacketInitial: packet,
Packet: packet,
}
action := n.handler.HandlePacket(context)
switch action {
case Accept:
payload.SetVerdict(nfqueue.NF_ACCEPT)
case Drop:
payload.SetVerdict(nfqueue.NF_DROP)
}
return 0
}
// GetIPv4Layer returns the IPv4 layer of the packet.
func GetIPv4Layer(packet gopacket.Packet) *layers.IPv4 {
if ipv4Layer := packet.Layer(layers.LayerTypeIPv4); ipv4Layer != nil {
return ipv4Layer.(*layers.IPv4)
}
return nil
}
|
package logger
import (
"fmt"
"io"
)
type Logger struct {
Stdout io.Writer
Stderr io.Writer
Verbose bool
}
func (l *Logger) Outf(s string, args ...interface{}) {
if len(args) == 0 {
s, args = "%s", []interface{}{s}
}
fmt.Fprintf(l.Stdout, s+"\n", args...)
}
func (l *Logger) VerboseOutf(s string, args ...interface{}) {
if l.Verbose {
l.Outf(s, args...)
}
}
func (l *Logger) Errf(s string, args ...interface{}) {
if len(args) == 0 {
s, args = "%s", []interface{}{s}
}
fmt.Fprintf(l.Stderr, s+"\n", args...)
}
func (l *Logger) VerboseErrf(s string, args ...interface{}) {
if l.Verbose {
l.Errf(s, args...)
}
}
|
/**********************************************************************************
*
* Given two binary strings, return their sum (also a binary string).
*
* For example,
* a = "11"
* b = "1"
* Return "100".
*
*
**********************************************************************************/
package main
import (
"fmt"
"strconv"
)
func addBinary(a, b string) {
var alen, blen int = len(a), len(b)
var plus bool
var add string
var result string
for alen > 0 || blen > 0 {
var ha int = threeCul(a, alen)
var hb int = threeCul(b, blen)
var hc int
if plus {
hc = 1
} else {
hc = 0
}
if ha+hb+hc == 3 {
plus = true
add = "1"
} else if ha+hb+hc == 2 {
add = "0"
plus = true
} else {
add = strconv.Itoa(ha + hb + hc)
plus = false
}
result += add
alen--
blen--
}
if plus {
result += "1"
}
printReslut(result)
}
func threeCul(val string, index int) int {
if index <= 0 {
return 0
}
retInt, _ := strconv.Atoi(val[index-1 : index])
return retInt
}
func printReslut(s string) {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
fmt.Println(string(runes))
}
func main() {
a := "11"
b := "1"
addBinary(a, b)
}
|
package utils
import (
"crypto/rand"
"encoding/base64"
)
func GenerateToken(len int) (string, error) {
t := make([]byte, len)
if _, err := rand.Read(t); err != nil {
return "", err
}
t64 := base64.RawURLEncoding.EncodeToString(t)
return t64, nil
}
|
package client
import (
"sync"
)
var registeredChannels map[interface{}]chan int64 = make(map[interface{}]chan int64)
var rcLock sync.Mutex
const BUF = 2
// called by the reciever of a value across a channel to find out what event sent the value
// the argument 'channel' should be any channel the goroutine is waiting to recieve a value
// from. returns a chan int64 which will emit every eventid that has registered as sending
// along the channel
func RegisterChannelReciever(channel interface{}) (ch chan int64) {
rcLock.Lock()
defer rcLock.Unlock()
ch, ok := registeredChannels[channel]
if !ok {
ch = make(chan int64, BUF)
registeredChannels[channel] = ch
}
return
}
// Convenience method. Get the event id of the last sender in the channel, and
// add it to the local store of redundant edges
func ReadChannelEvent(channel interface{}) {
redund := GetChannelSender(channel)
AddRedundancies(redund...)
}
// Get the last EventID that sent a value along the provided channel.
// Returns a singleton slice containing the most recent EventID of the sender,
// so long as the sender called called SendChannelEvent before sending
// the value. Returns an empty slice if no sender is known.
func GetChannelSender(channel interface{}) []int64 {
ch := RegisterChannelReciever(channel)
select {
// if the recv blocks, there must have been no call to SendChannelEvent on the
// channel as the function argument
case sender := <-ch:
return []int64{sender}
default:
return []int64{}
}
}
// called by the sender of a value over a channel BEFORE sending the value.
// Informs the future recipient of the value which event ID it originated from.
func SendChannelEvent(channel interface{}) {
rcLock.Lock()
defer rcLock.Unlock()
ch, ok := registeredChannels[channel]
if !ok {
ch = make(chan int64, BUF)
registeredChannels[channel] = ch
}
eventID := GetEventID()
// do this in a separate goroutine because chan sends can block unless there is a reciever ready
go func() {
ch <- eventID
}()
}
|
package client
import (
"context"
"testing"
"time"
"github.com/drand/drand/chain"
"github.com/drand/drand/test"
)
func TestClientConstraints(t *testing.T) {
if _, e := New(); e == nil {
t.Fatal("client can't be created without root of trust")
}
if _, e := New(WithChainHash([]byte{0})); e == nil {
t.Fatal("Client needs URLs if only a chain hash is specified")
}
if _, e := New(WithHTTPEndpoints([]string{"http://test.com"})); e == nil {
t.Fatal("Client needs root of trust unless insecure specified explicitly")
}
addr, _, cancel := withServer(t)
defer cancel()
if _, e := New(WithInsecureHTTPEndpoints([]string{"http://" + addr})); e != nil {
t.Fatal(e)
}
}
func TestClientMultiple(t *testing.T) {
addr1, hash, cancel := withServer(t)
defer cancel()
addr2, _, cancel2 := withServer(t)
defer cancel2()
c, e := New(WithHTTPEndpoints([]string{"http://" + addr1, "http://" + addr2}), WithChainHash(hash))
if e != nil {
t.Fatal(e)
}
r, e := c.Get(context.Background(), 0)
if e != nil {
t.Fatal(e)
}
if r.Round() <= 0 {
t.Fatal("expected valid client")
}
}
func TestClientWithChainInfo(t *testing.T) {
id := test.GenerateIDs(1)[0]
chainInfo := &chain.Info{
PublicKey: id.Public.Key,
GenesisTime: 100,
Period: time.Second,
}
c, err := New(WithChainInfo(chainInfo), WithHTTPEndpoints([]string{"http://nxdomain.local/"}))
if err != nil {
t.Fatal("existing group creation shouldn't do additional validaiton.")
}
_, err = c.Get(context.Background(), 0)
if err == nil {
t.Fatal("bad urls should clearly not provide randomness.")
}
}
func TestClientCache(t *testing.T) {
addr1, hash, cancel := withServer(t)
defer cancel()
c, e := New(WithHTTPEndpoints([]string{"http://" + addr1}), WithChainHash(hash), WithCacheSize(1))
if e != nil {
t.Fatal(e)
}
_, e = c.Get(context.Background(), 0)
if e != nil {
t.Fatal(e)
}
cancel()
_, e = c.Get(context.Background(), 0)
if e != nil {
t.Fatal(e)
}
_, e = c.Get(context.Background(), 4)
if e == nil {
t.Fatal("non-cached results should fail.")
}
}
func TestClientWithoutCache(t *testing.T) {
addr1, hash, cancel := withServer(t)
defer cancel()
c, e := New(WithHTTPEndpoints([]string{"http://" + addr1}), WithChainHash(hash), WithCacheSize(0))
if e != nil {
t.Fatal(e)
}
_, e = c.Get(context.Background(), 0)
if e != nil {
t.Fatal(e)
}
cancel()
_, e = c.Get(context.Background(), 0)
if e == nil {
t.Fatal("cache should be disabled.")
}
}
func TestClientWithFailover(t *testing.T) {
addr1, hash, cancel := withServer(t)
defer cancel()
// ensure a client with failover can be created successfully without error
_, err := New(
WithHTTPEndpoints([]string{"http://" + addr1}),
WithChainHash(hash),
WithFailoverGracePeriod(time.Second*5),
)
if err != nil {
t.Fatal(err)
}
}
|
package linkedlists
//import "fmt"
func sumForward(l1, l2 *ListNode, carry int) *ListNode {
if l1 == nil && l2 == nil {
if carry == 0 {
return nil
}
return &ListNode{carry, nil}
}
var v1, v2 int
var l1next, l2next *ListNode
if l1 == nil {
v2 = l2.value
l2next = l2.next
} else if l2 == nil {
v1 = l1.value
l1next = l1.next
} else {
v1 = l1.value
v2 = l2.value
l1next = l1.next
l2next = l2.next
}
temp := v1 + v2 + carry
if temp > 10 {
temp -= 10
carry = 1
} else {
carry = 0
}
head := &ListNode{temp, sumForward(l1next, l2next, carry)}
return head
}
/*
func sumForward(l1, l2 *ListNode) *ListNode {
var sum *ListNode
var cur *ListNode
carry := 0
for l1 != nil && l2 != nil {
temp := l1.value + l2.value + carry
if temp >= 10 {
temp -= 10
} else {
carry = 0
}
// Now insert into sum list checking if cur is nil
n := &ListNode{temp, nil}
if cur == nil {
cur = n
sum = n
} else {
cur.next = n
}
l1 = l1.next
l2 = l2.next
}
if l1 != nil {
cur.next, carry = carryOver(l1, carry)
cur = cur.next
} else if l2 != nil {
cur.next, carry = carryOver(l2, carry)
cur = cur.next
}
// Last step is to check the final carry
if carry > 0 {
cur.next = &ListNode{1, nil}
}
return sum
}
func carryOver(l *ListNode, carry int) (*ListNode, int) {
head := l
for l != nil {
temp := l.value + carry
if temp > 10 {
temp -= 10
l.value = temp
} else {
carry = 0
}
l = l.next
}
return head, carry
} */
|
//TODO
package logger
import(
"fmt"
)
func InitLogger(){
}
|
package main
import (
"context"
"encoding/json"
"testing"
"github.com/aws/aws-lambda-go/events"
)
const req1 string = `
{
"requestContext": {
"elb": {
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a"
}
},
"httpMethod": "GET",
"path": "/lambda",
"queryStringParameters": {
"query": "1234ABCD"
},
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"accept-encoding": "gzip",
"accept-language": "en-US,en;q=0.9",
"connection": "keep-alive",
"host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476",
"x-forwarded-for": "1.2.3.4, 72.12.164.125",
"x-forwarded-port": "80",
"x-forwarded-proto": "http",
"x-imforwards": "20"
},
"body": "",
"isBase64Encoded": false
}
`
const req2 string = `
{
"requestContext": {
"elb": {
"targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a"
}
},
"httpMethod": "GET",
"path": "/lambda",
"queryStringParameters": {
"query": "1234ABCD"
},
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"accept-encoding": "gzip",
"accept-language": "en-US,en;q=0.9",
"connection": "keep-alive",
"host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476",
"x-forwarded-for": "72.12.164.125",
"x-forwarded-port": "80",
"x-forwarded-proto": "http",
"x-imforwards": "20"
},
"body": "",
"isBase64Encoded": false
}
`
func TestGetClientIP(t *testing.T) {
var request events.ALBTargetGroupRequest
json.Unmarshal([]byte(req1), &request)
clientip := getClientIP(request)
if clientip != "1.2.3.4" {
t.Errorf("getClientIP returned %s", clientip)
}
}
func TestHandleRequest(t *testing.T) {
var request events.ALBTargetGroupRequest
json.Unmarshal([]byte(req1), &request)
response, err := HandleRequest(context.Background(), request)
if err != nil {
t.Errorf(" returned error: %s", err)
}
if response.Body != "1.2.3.4" {
t.Errorf(" returned body: %s", response.Body)
}
json.Unmarshal([]byte(req2), &request)
response, err = HandleRequest(context.Background(), request)
if err != nil {
t.Errorf(" returned error: %s", err)
}
if response.Body != "72.12.164.125" {
t.Errorf(" returned body: %s", response.Body)
}
}
|
package env
import (
"errors"
"github.com/andybar2/team/store"
"github.com/spf13/cobra"
)
var deleteParams struct {
Stage string
Name string
}
var deleteCmd = &cobra.Command{
Use: "delete",
Short: "Delete an environment variable",
RunE: runDeleteCmd,
}
func init() {
deleteCmd.Flags().StringVarP(&deleteParams.Stage, "stage", "s", "", "Stage name")
deleteCmd.Flags().StringVarP(&deleteParams.Name, "name", "n", "", "Variable name")
EnvCmd.AddCommand(deleteCmd)
}
func runDeleteCmd(cmd *cobra.Command, args []string) error {
if deleteParams.Stage == "" {
return errors.New("invalid stage name")
}
if deleteParams.Name == "" {
return errors.New("invalid variable name")
}
s, err := store.New()
if err != nil {
return err
}
return s.EnvDelete(deleteParams.Stage, deleteParams.Name)
}
|
package services
import (
"github.com/danielhood/quest.server.api/entities"
"github.com/danielhood/quest.server.api/repositories"
)
// DeviceService provides a CRUD interface for Devices
type DeviceService interface {
ReadAll() ([]entities.Device, error)
Read(string, string) (*entities.Device, error)
Update(*entities.Device) error
Delete(*entities.Device) error
}
// NewDeviceService creates a new DeviceService
func NewDeviceService(dr repositories.DeviceRepo) DeviceService {
return &deviceService{
deviceRepo: dr,
}
}
type deviceService struct {
deviceRepo repositories.DeviceRepo
}
func (s *deviceService) ReadAll() ([]entities.Device, error) {
return s.deviceRepo.GetAll()
}
func (s *deviceService) Read(hostname string, deviceKey string) (*entities.Device, error) {
return s.deviceRepo.GetByHostnameAndKey(hostname, deviceKey)
}
func (s *deviceService) Update(u *entities.Device) error {
return s.deviceRepo.Add(u)
}
func (s *deviceService) Delete(u *entities.Device) error {
return s.deviceRepo.Delete(u)
}
|
package solutions
import (
"fmt"
"testing"
)
func TestMerge(t *testing.T) {
t.Run("Test [[1,3],[2,6],[8,10],[15,18]]", func(t *testing.T) {
input := [][]int{{1, 3}, {2, 6}, {8, 10}, {15, 18}}
want := [][]int{{1, 6}, {8, 10}, {15, 18}}
r := merge(input)
if fmt.Sprint(input) != fmt.Sprint(want) {
t.Errorf("got %v, want %v", r, want)
}
})
}
|
package module
import (
"accountBook/models/beans"
"accountBook/models/beans/customer"
"accountBook/models/beans/dbBeans"
"accountBook/models/endpoints"
"accountBook/models/endpoints/web"
"accountBook/models/service"
"strings"
"github.com/kinwyb/go/db"
"github.com/kinwyb/go/err1"
)
func init() {
endpoints.RegisterLogContentParseFun("Receipt", logContentParse)
}
func logContentParse(db *customer.LogAddReq) {
switch db.CallFunc {
case "Receipt.Add":
if len(db.Args) > 0 {
arg := db.Args[0].(*dbBeans.ReceiptDB)
if arg.Money > 0 {
db.Content = strings.Split(db.Content, "【")[0] + "【收入单据】"
} else {
db.Content = strings.Split(db.Content, "【")[0] + "【支出单据】"
}
}
}
}
var Receipt web.IReceiptEndpoint = &receiptEp{}
type receiptEp struct{}
func (receiptEp) List(req *customer.ReceiptListReq, pg *db.PageObj, ctx *beans.Context) (*customer.ReceiptListResp, err1.Error) {
defer ctx.Start("ep.ReceiptList").Finish()
if err := endpoints.CheckPower("ReceiptList", ctx.Child()); err != nil {
return nil, err
}
return service.ReceiptList(req, pg, ctx.Child()), nil
}
func (receiptEp) NextNo(ctx *beans.Context) string {
defer ctx.Start("ep.ReceiptNextNo").Finish()
if err := endpoints.CheckPower("ReceiptNextNo", ctx.Child()); err != nil {
return ""
}
return service.ReceiptNextNo(ctx.Child())
}
func (receiptEp) Add(req *dbBeans.ReceiptDB, ctx *beans.Context) err1.Error {
defer ctx.Start("ep.ReceiptAdd").Finish()
ctx.RequestArgs = []interface{}{req} //请求参数
if err := endpoints.CheckPower("Receipt.Add", ctx.Child()); err != nil {
return err
}
return service.ReceiptAdd(req, ctx.Child())
}
|
// Mandelbrot creates PNG of Mandelbrot N**4-1
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"math/cmplx"
"os"
"runtime"
"sync"
)
type job struct {
xstart, xend, ystart, yend int
}
const (
xmin, ymin, xmax, ymax = -2, -2, 2, 2
width, height = 1920, 1080
chunks = 16
)
func main() {
img := image.NewRGBA(image.Rect(0, 0, width, height))
jobs := make(chan job, 256)
var wg sync.WaitGroup
numWorkers := runtime.NumCPU()
for i := 0; i < numWorkers; i++ {
go worker(&wg, jobs, img)
wg.Add(1)
}
increment := height / chunks
for py := 0; py < height; py += increment {
jobs <- job{
xstart: 0,
xend: width,
ystart: py,
yend: py + increment,
}
}
// last chunk if needed
if height%chunks != 0 {
jobs <- job{
xstart: 0,
xend: width,
ystart: height - height%chunks,
yend: height,
}
}
close(jobs)
wg.Wait()
if err := png.Encode(os.Stdout, img); err != nil {
fmt.Fprintf(os.Stderr, "Error while encoding image: %v\n", err)
}
}
func worker(wg *sync.WaitGroup, jobs chan job, img *image.RGBA) {
defer wg.Done()
for j := range jobs {
for py := j.ystart; py < j.yend; py++ {
y := float64(py)/height*(ymax-ymin) + ymin
for px := j.xstart; px < j.xend; px++ {
x := float64(px)/width*(xmax-xmin) + xmin
z, n, ok := neuton(complex(x, y))
if !ok {
img.Set(px, py, color.Black)
continue
}
c, ok := colors(z)
if !ok {
img.Set(px, py, color.White)
continue
}
img.Set(px, py, reduceColor(c, n))
}
}
}
}
func reduceColor(c color.RGBA, n uint8) color.RGBA {
return color.RGBA{
R: c.R / n * 2,
G: c.G / n * 2,
B: c.B / n * 2,
A: 255,
}
}
func neuton(z complex128) (complex128, uint8, bool) {
const iterations = 255
for n := uint8(1); n < iterations; n++ {
d := delta(z)
if d == 0 {
return 0, 0, false
}
z -= f(z) / d
if cmplx.Abs(f(z)) < 0.0001 {
return z, n, true
}
}
return 0, 0, false
}
// function specifics
func f(z complex128) complex128 {
return cmplx.Pow(z, 4) - 1
}
func delta(z complex128) complex128 {
return 4 * cmplx.Pow(z, 3)
}
var colormap = map[complex128]color.RGBA{
1: {R: 255, G: 0, B: 0, A: 255},
-1: {R: 0, G: 255, B: 0, A: 255},
-1i: {R: 0, G: 0, B: 255, A: 255},
1i: {R: 255, G: 255, B: 0, A: 255},
}
func colors(z complex128) (c color.RGBA, ok bool) {
c, ok = colormap[complex(math.RoundToEven(real(z)), math.RoundToEven(imag(z)))]
return
}
|
// Copyright 2014 The Sporting Exchange Limited. All rights reserved.
// Use of this source code is governed by a free license that can be
// found in the LICENSE file.
package collect
import (
"os"
"syscall"
)
// BUG(masiulaniecj): On Windows, plugin rescheduling on exit code 13 is not supported.
func reschedule(_ error) bool { return false }
func sysProcAttr() *syscall.SysProcAttr {
return nil
}
// BUG(masiulaniecj): On Windows, plugins must run in single process, i.e. must not
// have child processes themselves.
func kill(process *os.Process) error {
return process.Kill()
}
|
package test
import (
"testing"
// "os"
// "path/filepath"
"portal/service"
// "portal/database"
)
func TestCreateApp(t *testing.T) {
// database.OpenDB("root:scut2018@tcp(192.168.80.243:3306)/portal2?parseTime=true")
var name string = "测试_A"
code, err := service.CreateApp(name)
if err != nil {
t.Error(err)
} else {
t.Log("success code: ", code)
}
// exepath, err := os.Executable()
// if err != nil {
// t.Error(err)
// }
// file := filepath.Dir(exepath)
// t.Log("myfile ", file)
} |
package full
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/actors/builtin/miner"
"github.com/filecoin-project/lotus/chain/stmgr"
"github.com/filecoin-project/lotus/chain/types"
das "github.com/filecoin-project/specs-actors/v5/actors/builtin/miner"
miner5 "github.com/filecoin-project/specs-actors/v5/actors/builtin/miner"
"github.com/ipfs/go-cid"
"github.com/shopspring/decimal"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"os/exec"
"reflect"
"strconv"
"strings"
)
func (a *StateAPI) StateMinerDeadlinesByMiner(ctx context.Context, m address.Address, tsk types.TipSetKey) ([]*api.StateMinerDeadlinesByMinerInfo, error) {
deadlines, err := a.StateMinerDeadlines(ctx, m, tsk)
r := make([]*api.StateMinerDeadlinesByMinerInfo, 0, len(deadlines))
if err != nil {
return []*api.StateMinerDeadlinesByMinerInfo{}, xerrors.Errorf("loading deadlines %s: %w", tsk, err)
}
provingDeadline, err := a.StateMinerProvingDeadline(ctx, m, tsk)
if err != nil {
return []*api.StateMinerDeadlinesByMinerInfo{}, xerrors.Errorf("loading provingDeadline %s: %w", tsk, err)
}
for i, deadline := range deadlines {
var ll = uint64(i)
minerDeadlinesInfo := new(api.StateMinerDeadlinesByMinerInfo)
partitions, err := a.StateMinerPartitionsNew(ctx, m, ll, tsk)
if err != nil {
return []*api.StateMinerDeadlinesByMinerInfo{}, xerrors.Errorf("partitions tipset %s: %w", tsk, err)
}
if ll== provingDeadline.Index{
minerDeadlinesInfo.Index = 1
}else {
minerDeadlinesInfo.Index = 0
}
var Faults uint64 = 0
var Recoveries uint64 = 0
var Sectors uint64 =0
var Terminated uint64 =0
var FaultyPower uint64 =0
var LivePower uint64 =0
var RecoveringPower uint64 =0
for _, partition := range partitions {
RecoveriesCount, _ := partition.Recoveries.Count()
Recoveries = Recoveries + RecoveriesCount
FaultsCount, _ := partition.Faults.Count()
Faults = Faults + FaultsCount
SectorsCount, _ := partition.Sectors.Count()
Sectors = Sectors + SectorsCount
TerminatedCount, _ := partition.Terminated.Count()
Terminated = Terminated + TerminatedCount
FaultyPower = FaultyPower + partition.FaultyPower.QA.Uint64()
LivePower = LivePower + partition.LivePower.QA.Uint64()
RecoveringPower = RecoveringPower + partition.RecoveringPower.QA.Uint64()
}
minerDeadlinesInfo.FaultyPower = FaultyPower
minerDeadlinesInfo.LivePower = LivePower
minerDeadlinesInfo.RecoveringPower = RecoveringPower
minerDeadlinesInfo.Recoveries = Recoveries
minerDeadlinesInfo.Faults = Faults
minerDeadlinesInfo.Sectors = Sectors
minerDeadlinesInfo.Terminated = Terminated
minerDeadlinesInfo.PostSubmissions = deadline.PostSubmissions
minerDeadlinesInfo.Wpost = len(partitions)
r = append(r, minerDeadlinesInfo)
}
return r, nil
}
//func (a *StateAPI ) StateBlockMessages(ctx context.Context,msg cid.Cid) (*api.NBlockMessages, error) {
// b, err := a.Chain.GetBlock(msg)
// if err != nil {
// return nil, err
// }
//
//
// bmsgs, smsgs, err := a.NMessagesForBlock(ctx,b)
// if err != nil {
// return nil, err
// }
//
//
//
// return &api.NBlockMessages{
// BlsMessages: bmsgs,
// SecpkMessages: smsgs,
// }, nil
//}
func (a *StateAPI) StateMinerPartitionsNew(ctx context.Context, m address.Address, dlIdx uint64, tsk types.TipSetKey) ( []*das.Partition, error) {
var out []*das.Partition
return out, a.StateManager.WithParentStateTsk(tsk,
a.StateManager.WithActor(m,
a.StateManager.WithActorState(ctx,
a.StateManager.WithDeadlines(
a.StateManager.WithDeadline(dlIdx,
a.StateManager.WithEachPartition(func(store adt.Store, partIdx uint64, partition *das.Partition) error {
out = append(out, partition)
return nil
}))))))
}
func (cs *StateAPI) NMessagesForBlock(ctx context.Context,b *types.BlockHeader) ([]*api.NMessage, []*api.NMessage, error) {
blscids, secpkcids, err := cs.Chain.ReadMsgMetaCids(b.Messages)
if err != nil {
return nil, nil, xerrors.Errorf("loading bls messages for block: %w", err)
}
blsmsgs, err := cs.NLoadMessagesFromCids(ctx,blscids,b)
if err != nil {
return nil, nil, xerrors.Errorf("loading bls messages for block: %w", err)
}
secpkmsgs, err := cs.NLoadSignedMessagesFromCids(ctx,secpkcids,b)
if err != nil {
return nil, nil, xerrors.Errorf("loading secpk messages for block: %w", err)
}
return blsmsgs, secpkmsgs, nil
}
func (cs *StateAPI) NLoadSignedMessagesFromCids(ctx context.Context,cids []cid.Cid,b *types.BlockHeader) ([]*api.NMessage, error) {
msgs := make([]*api.NMessage, 0, len(cids))
//nodeAPI, closer, err := GetFullNodeAPI(cs.ctxx)
//if err != nil {
// return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", err)
//}
//defer closer()
//t := types.NewTipSetKey(b.Cid())
//fmt.Print("MessagesFromCidsByTipSetKey:",t.String())
for i, c := range cids {
//var flag = false
m, err := cs.Chain.GetSignedMessage(c)
//fmt.Print("m.To:",m.Message.To)
//fmt.Print("m.Cid():",m.Cid())
if err != nil {
return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
nMessage := new(api.NMessage)
//actor, err := cs.StateGetActor(ctx, m.Message.To, t)
//
//if err != nil {
// flag = true
//}
//receipt, err := cs.StateGetReceipt(ctx, c, t)
//
//if err != nil {
// return nil, xerrors.Errorf("failed to get receipt: (%s):%d: %w", c, i, err)
//}
//
//
//
//if receipt != nil {
// ret, err := jsonReturn(actor.Code, m.Message.Method, receipt.Return)
// if err != nil {
// return nil, xerrors.Errorf("failed to get jsonReturn: (%s):%d: %w", c, i, err)
// }
// nMessage.Return = ret
// nMessage.ExitCode = receipt.ExitCode
// nMessage.GasUsed = receipt.GasUsed
//}
//if m.Message.Params != nil {
// if !flag {
// par, err := jsonParams(actor.Code, m.Message.Method, m.Message.Params)
//
// if err != nil {
// return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
// }
// nMessage.Params = par
// }
//}
nMessage.Version = m.Message.Version
//nMessage.MessageId = c.String()
nMessage.To = m.Message.To
nMessage.From = m.Message.From
nMessage.Nonce = m.Message.Nonce
nMessage.Value = m.Message.Value
nMessage.GasLimit = m.Message.GasLimit
nMessage.GasFeeCap = m.Message.GasFeeCap
nMessage.GasPremium = m.Message.GasPremium
nMessage.Method = m.Message.Method
//if !flag {
// nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
//
//}
msgs = append(msgs, nMessage)
//msgs = append(msgs, m)
}
return msgs, nil
}
func (a *StateAPI) StateGetParentReceipts(ctx context.Context, bcid cid.Cid) ([]*types.MessageReceipt, error) {
b, err := a.Chain.GetBlock(bcid)
if err != nil {
return nil, err
}
if b.Height == 0 {
return nil, nil
}
// TODO: need to get the number of messages better than this
pts, err := a.Chain.LoadTipSet(types.NewTipSetKey(b.Parents...))
if err != nil {
return nil, err
}
cm,sm, err := a.Chain.MessagesForTipsetEx(pts)
if err != nil {
return nil, err
}
t := types.NewTipSetKey(bcid)
var out []*types.MessageReceipt
for i, msg := range cm {
r, err := a.Chain.GetParentReceipt(b, i)
if err != nil {
return nil, err
}
actor, err := a.StateManager.LoadActorTsk(ctx, msg.VMMessage().To, t)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", msg.VMMessage().To, i, err)
}
jsonReturn, err := jsonReturn(actor.Code, msg.VMMessage().Method, r.Return)
r.Returns = jsonReturn
//r.BlockCID = msg.VMMessage().BlockCid.String()
//
out = append(out, r)
}
for i, msg := range sm {
r, err := a.Chain.GetParentReceipt(b, i)
if err != nil {
return nil, err
}
actor, err := a.StateManager.LoadActorTsk(ctx, msg.VMMessage().To, t)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", msg.VMMessage().To, i, err)
}
jsonReturn, err := jsonReturn(actor.Code, msg.VMMessage().Method, r.Return)
r.Returns = jsonReturn
//r.BlockCID = msg.VMMessage().BlockCid.String()
//
out = append(out, r)
}
return out, nil
}
func (a *StateAPI) StateReplayList(ctx context.Context, tsp *types.TipSet) ([]*api.InvocResult, error) {
t, err := stmgr.ComputeStateList(ctx, a.StateManager, tsp)
if err != nil {
return nil, err
}
return t, nil
}
func (a *StateAPI) StateReplayLists(ctx context.Context, height int64) ([]*api.InvocResult, error) {
byHeight, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(height), nil, true)
t, err := stmgr.ComputeStateList(ctx, a.StateManager, byHeight)
if err != nil {
return nil, err
}
return t, nil
}
func (a *StateAPI) StateGetMessageByHeightIntervalEx(ctx context.Context, params api.StateGetMessageByHeightIntervalParams) ([]*api.SMessage, error) {
marshal, _ := json.Marshal(params)
log.Info("params ",string(marshal))
log.Info("params.FromAddress ",params.FromAddress)
log.Info("params.Method ",params.Method)
log.Info("params.CodeMethod ",params.CodeMethod)
log.Info("params.ToAddress ",params.ToAddress)
blockStart, _ := a.Chain.GetBlock(params.BlockIdStart)
//blockEnd, _ := a.Chain.GetBlock(params.BlockIdEnd)
var msgs []*api.SMessage
//var whereMsgs []*api.SMessage
for {
parents := blockStart.Parents
//if blockStart.Height < blockEnd.Height {
// log.Error("stop for")
// break
//}
flag := false
for _, parent := range parents {
if parent.String() == params.BlockIdEnd.String(){
flag = true
}
}
if flag{
log.Error("stop for")
break
}
pts, err := a.Chain.LoadTipSet(types.NewTipSetKey(parents...))
if err != nil {
log.Error("loading LoadTipSet %s: %w", pts, err)
continue
}
parentBlockHeader, _ := a.Chain.GetBlock(parents[0])
cm, err := a.Chain.MessagesForTipset(pts)
if err != nil {
log.Error("loading MessagesForTipset %s: %w", pts, err)
continue
}
//t := types.NewTipSetKey(parents[0])
t := types.EmptyTSK
for i, msg := range cm {
r, err := a.Chain.GetParentReceipt(blockStart, i)
if err != nil {
log.Error("a.Chain.GetParentReceipt %s: %w", err)
continue
}
var actor *types.Actor
actor, err = a.StateManager.LoadActorTsk(ctx, msg.VMMessage().To, t)
if err != nil {
actor, err = a.StateGetActor(ctx, msg.VMMessage().To, t)
}
a2 := new(api.SMessage)
a2.Tipset = parents
a2.Version = msg.VMMessage().Version
a2.To = msg.VMMessage().To
a2.From = msg.VMMessage().From
a2 .Nonce = msg.VMMessage().Nonce
a2.Value = msg.VMMessage().Value
a2.GasLimit = msg.VMMessage().GasLimit
a2.GasFeeCap = msg.VMMessage().GasFeeCap
a2.GasPremium = msg.VMMessage().GasPremium
a2.Method = msg.VMMessage().Method
a2.CID = msg.Cid()
a2.ExitCode = r.ExitCode
if actor!=nil {
a2.CodeMethod = builtin.ActorNameByCode(actor.Code)
if a2.CodeMethod == "<undefined>" || a2.CodeMethod == "<unknown>"{
a2.CodeMethod = BuiltinName4(actor.Code)
}
if a2.CodeMethod == "<undefined>" || a2.CodeMethod == "<unknown>"{
a2.CodeMethod = BuiltinName3(actor.Code)
}
if a2.CodeMethod == "<undefined>" || a2.CodeMethod == "<unknown>"{
a2.CodeMethod = BuiltinName2(actor.Code)
}
if a2.CodeMethod == "<undefined>" || a2.CodeMethod == "<unknown>"{
a2.CodeMethod = BuiltinName1(actor.Code)
}
if a2.CodeMethod !=""{
split := strings.Split( a2.CodeMethod, "/")
bame := split[len(split)-1]
a2.CodeMethod = bame
}
}
if msg.VMMessage().Params != nil {
if !flag {
par, err := jsonParams(actor.Code, msg.VMMessage().Method, msg.VMMessage().Params)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", i, err)
}
a2.Params = par
}
}
a2.Height = parentBlockHeader.Height
msgs = append(msgs, a2)
}
blockStart = parentBlockHeader
}
var whereMsgs []*api.SMessage
//筛选
if params.CodeMethod !=""&&len(params.Method) >=1 {
for _, msg := range msgs {
if params.CodeMethod == msg.CodeMethod{
for _, method := range params.Method {
if method == msg.Method.String(){
whereMsgs = append(whereMsgs,msg )
}
}
}
}
}
if params.CodeMethod !=""&&len(params.Method) >=1&&len(params.ToAddress) >=1{
for _, msg := range msgs {
if params.CodeMethod == msg.CodeMethod{
for _, toAddress := range params.ToAddress {
for _, method := range params.Method {
if toAddress == msg.To.String() && method == msg.Method.String(){
whereMsgs = append(whereMsgs,msg )
}
}
}
}
}
}
if params.CodeMethod !=""&&len(params.Method) >=1 &&len(params.FromAddress) >=1{
for _, msg := range msgs {
if params.CodeMethod == msg.CodeMethod{
for _, FromAddress := range params.FromAddress {
for _, method := range params.Method {
if FromAddress == msg.From.String() && method == msg.Method.String(){
whereMsgs = append(whereMsgs,msg )
}
}
}
}
}
}
if params.CodeMethod !="" ||len(params.Method) >=1 ||len(params.ToAddress) >=1 || len(params.FromAddress) >=1{
return whereMsgs,nil
}
return msgs,nil
}
func (a *StateAPI) StateGetParentDeals(ctx context.Context, bcid cid.Cid) ([]*api.StateGetParentDealsResp, error) {
b, err := a.Chain.GetBlock(bcid)
if err != nil {
return nil, err
}
if b.Height == 0 {
return nil, nil
}
// TODO: need to get the number of messages better than this
pts, err := a.Chain.LoadTipSet(types.NewTipSetKey(b.Parents...))
if err != nil {
return nil, err
}
cm, err := a.Chain.MessagesForTipset(pts)
if err != nil {
return nil, err
}
t := types.NewTipSetKey(bcid)
var out []*api.StateGetParentDealsResp
for i, msg := range cm {
r, err := a.Chain.GetParentReceipt(b, i)
if err != nil {
return nil, err
}
var actor *types.Actor
actor, err = a.StateManager.LoadActorTsk(ctx, msg.VMMessage().To, t)
if err != nil {
actor, err = a.StateGetActor(ctx, msg.VMMessage().To, t)
}
if r.Return != nil {
jsonReturn, err := jsonReturn(actor.Code, msg.VMMessage().Method, r.Return)
if err != nil {
return nil, err
}
r.Returns = jsonReturn
code := builtin.ActorNameByCode(actor.Code)
if code == "<undefined>" || code == "<unknown>"{
code = BuiltinName4(actor.Code)
}
if code == "<undefined>" || code == "<unknown>"{
code = BuiltinName3(actor.Code)
}
if code == "<undefined>" || code == "<unknown>"{
code = BuiltinName2(actor.Code)
}
if code == "<undefined>" || code == "<unknown>"{
code = BuiltinName1(actor.Code)
}
if code !=""{
split := strings.Split( code, "/")
bame := split[len(split)-1]
code = bame
}
if code == "storagemarket" && msg.VMMessage().Method == 4 {
resps := Deals{}
err := json.Unmarshal([]byte(jsonReturn), &resps)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", actor.Code, i, err)
}
for _, d := range resps.IDs {
deal, err := a.StateMarketStorageDeal(ctx, d, t)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", d, i, err)
}
key, err := a.StateAccountKey(ctx, deal.Proposal.Client, t)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", d, i, err)
}
a2 := new(api.StateGetParentDealsResp)
a2.Height = b.Height
a2.GasUsed = r.GasUsed
a2.ExitCode = r.ExitCode
a2.State = deal.State
a2.Proposal = deal.Proposal
a2.DealID = d
a2.CID = msg.VMMessage().Cid()
a2.ClientWallet = key.String()
out = append(out, a2)
}
}
}
}
return out, nil
}
type Deals struct {
IDs []abi.DealID
}
func (cs *StateAPI) NLoadMessagesFromCids(ctx context.Context,cids []cid.Cid,b *types.BlockHeader) ([]*api.NMessage, error) {
msgs := make([]*api.NMessage, 0, len(cids))
//nodeAPI, closer, err := GetFullNodeAPI(cs.ctxx)
//if err != nil {
// return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", err)
//}
//defer closer()
t := types.NewTipSetKey(b.Cid())
//fmt.Print("MessagesFromCidsByTipSetKey:",t.String())
for i, c := range cids {
var flag = false
m, err := cs.Chain.GetMessage(c)
//fmt.Print("m.To:",m.To)
//fmt.Print("m.Cid():",m.Cid())
if err != nil {
return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
actor, err := cs.StateManager.LoadActorTsk(ctx, m.To, t)
//fmt.Print("actorss:",actor)
//fmt.Print("actorss:",actor.Code.String())
if err != nil {
flag = true
}
//receipt, err := cs.StateGetReceipt(ctx, c, t)
//
//if err != nil {
// return nil, xerrors.Errorf("failed to get receipt: (%s):%d: %w", c, i, err)
//}
//fmt.Print("actor.Code:",actor.Code)
//fmt.Print("m.Method:",m.Method)
nMessage := new(api.NMessage)
//if receipt != nil {
// //fmt.Print("receipt.Return:",receipt)
// ret, err := jsonReturn(actor.Code, m.Method, receipt.Return)
// if err != nil {
// return nil, xerrors.Errorf("failed to get jsonReturn: (%s):%d: %w", c, i, err)
// }
// nMessage.Return = ret
// nMessage.ExitCode = receipt.ExitCode
// nMessage.GasUsed = receipt.GasUsed
//}
if m.Params != nil {
if !flag {
par, err := jsonParams(actor.Code, m.Method, m.Params)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
}
nMessage.Params = par
}
}
nMessage.Version = m.Version
//nMessage.MessageId = c.String()
nMessage.To = m.To
nMessage.From = m.From
nMessage.Nonce = m.Nonce
nMessage.Value = m.Value
nMessage.GasLimit = m.GasLimit
nMessage.GasFeeCap = m.GasFeeCap
nMessage.GasPremium = m.GasPremium
nMessage.Method = m.Method
if !flag {
//if actor.Code.String() == "bafkqaetgnfwc6mjpon2g64tbm5sw22lomvza"{
// nMessage.CodeMethod = "fil/2/storageminer"
// //fmt.Print("CodeMethods:",nMessage.CodeMethod)
//}else {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
//fmt.Print("CodeMethods:",nMessage.CodeMethod)
//}
}
msgs = append(msgs, nMessage)
}
return msgs, nil
}
func jsonParams(code cid.Cid, method abi.MethodNum, params []byte) (string, error) {
p, err := stmgr.GetParamType(code, method)
if err != nil {
return "", err
}
if err := p.UnmarshalCBOR(bytes.NewReader(params)); err != nil {
return "", err
}
if method == miner.Methods.ProveCommitAggregate {
var retval miner5.ProveCommitAggregateParams
if err := retval.UnmarshalCBOR(bytes.NewReader(params)); err != nil {
return "", err
}
sids,err:=retval.SectorNumbers.All(abi.MaxSectorNumber)
if err != nil {
return "", err
}
var m =map[string]interface{}{}
m["SectorNumbers"]=sids
m["AggregateProof"]=retval.AggregateProof
indent, err := json.MarshalIndent(m, "", " ")
return string(indent), err
}
if method == miner.Methods.ExtendSectorExpiration {
var expirationExtensionEx []ExpirationExtensionEx
var retval miner5.ExtendSectorExpirationParams
if err := retval.UnmarshalCBOR(bytes.NewReader(params)); err != nil {
return "", err
}
for _, extension := range retval.Extensions {
all, err := extension.Sectors.All(abi.MaxSectorNumber)
if err != nil {
return "", err
}
exp := ExpirationExtensionEx{
Deadline: extension.Deadline,
Partition: extension.Partition,
Sectors: all,
NewExpiration: extension.NewExpiration,
}
expirationExtensionEx = append(expirationExtensionEx,exp )
}
indent, err := json.MarshalIndent(expirationExtensionEx, "", " ")
return string(indent), err
}
b, err := json.MarshalIndent(p, "", " ")
return string(b), err
}
type ExpirationExtensionEx struct {
Deadline uint64
Partition uint64
Sectors [] uint64
NewExpiration abi.ChainEpoch
}
func jsonReturn(code cid.Cid, method abi.MethodNum, ret []byte) (string, error) {
methodMeta, found := stmgr.MethodsMap[code][method]
if !found {
return "", fmt.Errorf("method %d not found on actor %s", method, code)
}
re := reflect.New(methodMeta.Ret.Elem())
p := re.Interface().(cbg.CBORUnmarshaler)
if err := p.UnmarshalCBOR(bytes.NewReader(ret)); err != nil {
return "", err
}
b, err := json.MarshalIndent(p, "", " ")
return string(b), err
}
//func (a *StateAPI) StateWithdrawal(ctx context.Context, params *api.StateWithDrawalReq) (string, error) {
// fmt.Print("StateWithdrawal:",params)
// //str := params.Root+" "+params.Miner+" "+params.EpochPrice+" "+params.MinBlocksDuration
// //fmt.Print("ClientStartDealGoReq:"+str)
// cmd := exec.Command("./lotus", "send", params.From ,params.Amount)
// output,err := cmd.Output()
// if err != nil {
// return "", xerrors.Errorf("failed lotus send: %w", err)
// }
// s := string(output)
//
// return s,nil
//
//
//}
func (a *StateAPI) StateBlockMessages(ctx context.Context, msg cid.Cid) (*api.StateBlockMessagesRes, error) {
b, err := a.Chain.GetBlock(msg)
if err != nil {
return nil, err
}
bmsgs, smsgs, err := a.MessagesForBlock(b,ctx)
if err != nil {
return nil, err
}
//cids := make([]cid.Cid, len(bmsgs)+len(smsgs))
//
//for i, m := range bmsgs {
//
// cids[i] = m.Cid()
//}
//
//for i, m := range smsgs {
// cids[i+len(bmsgs)] = m.Cid()
//}
return &api.StateBlockMessagesRes{
BlsMessages: bmsgs,
SecpkMessages: smsgs,
}, nil
}
func (cs *StateAPI) MessagesForBlock(b *types.BlockHeader,ctx context.Context) ([]*api.NMessage, []*api.NMessage, error) {
blscids, secpkcids, err := cs.Chain.ReadMsgMetaCids(b.Messages)
if err != nil {
return nil, nil, err
}
blsmsgs, err := cs.LoadMessagesFromCids(blscids,b,ctx)
if err != nil {
return nil, nil, xerrors.Errorf("loading bls messages for block: %w", err)
}
secpkmsgs, err := cs.LoadSignedMessagesFromCids(secpkcids,b,ctx)
if err != nil {
return nil, nil, xerrors.Errorf("loading secpk messages for block: %w", err)
}
return blsmsgs, secpkmsgs, nil
}
func (cs *StateAPI) LoadMessagesFromCids(cids []cid.Cid,b *types.BlockHeader,ctx context.Context) ([]*api.NMessage, error) {
msgs := make([]*api.NMessage, 0, len(cids))
t := types.NewTipSetKey(b.Cid())
for i, c := range cids {
var flag = false
m, err := cs.Chain.GetMessage(c)
if err != nil {
return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
var actor *types.Actor
actor, err = cs.StateManager.LoadActorTsk(ctx, m.To, t)
if err != nil {
actor, err = cs.StateGetActor(ctx, m.To, t)
if(err != nil){
flag = true
}
}
call, err := cs.StateCall(ctx, m,t)
if err != nil {
xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
nMessage := new(api.NMessage)
if m.Params != nil {
if !flag {
par, err := jsonParams(actor.Code, m.Method, m.Params)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
}
nMessage.Params = par
}
}
if call != nil {
if call.MsgRct.Return !=nil {
if !flag {
returns, err := jsonReturn(actor.Code, m.Method, call.MsgRct.Return)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
}
call.MsgRct.Returns = returns
}
}
nMessage.MsgRct = call.MsgRct
}
nMessage.Version = m.Version
nMessage.To = m.To
nMessage.From = m.From
nMessage.Nonce = m.Nonce
nMessage.Value = m.Value
nMessage.GasLimit = m.GasLimit
nMessage.GasFeeCap = m.GasFeeCap
nMessage.GasPremium = m.GasPremium
nMessage.Method = m.Method
nMessage.CID = c
nMessage.GasCost = call.GasCost
nMessage.ExecutionTrace = call.ExecutionTrace
nMessage.Duration = call.Duration
nMessage.Error = call.Error
if !flag {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
}
msgs = append(msgs, nMessage)
}
return msgs, nil
}
func (cs *StateAPI) LoadSignedMessagesFromCids(cids []cid.Cid,b *types.BlockHeader,ctx context.Context) ([]*api.NMessage, error) {
msgs := make([]*api.NMessage, 0, len(cids))
t := types.NewTipSetKey(b.Cid())
for i, c := range cids {
var flag = false
m, err := cs.Chain.GetSignedMessage(c)
if err != nil {
return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
var actor *types.Actor
actor, err = cs.StateManager.LoadActorTsk(ctx, m.VMMessage().To, t)
if err != nil {
actor, err = cs.StateGetActor(ctx, m.VMMessage().To, t)
if(err != nil){
flag = true
}
}
call, err := cs.StateCall(ctx, &m.Message,t)
if err != nil {
xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
nMessage := new(api.NMessage)
if m.VMMessage().Params != nil {
if !flag {
par, err := jsonParams(actor.Code, m.VMMessage().Method, m.VMMessage().Params)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
}
nMessage.Params = par
}
}
if call != nil {
if call.MsgRct.Return !=nil {
if !flag {
returns, err := jsonReturn(actor.Code, m.VMMessage().Method, call.MsgRct.Return)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
}
call.MsgRct.Returns = returns
}
}
nMessage.MsgRct = call.MsgRct
}
nMessage.Version = m.VMMessage().Version
nMessage.To = m.VMMessage().To
nMessage.From = m.VMMessage().From
nMessage.Nonce = m.VMMessage().Nonce
nMessage.Value = m.VMMessage().Value
nMessage.GasLimit = m.VMMessage().GasLimit
nMessage.GasFeeCap = m.VMMessage().GasFeeCap
nMessage.GasPremium = m.VMMessage().GasPremium
nMessage.Method = m.VMMessage().Method
nMessage.CID = c
nMessage.GasCost = call.GasCost
nMessage.ExecutionTrace = call.ExecutionTrace
nMessage.Duration = call.Duration
nMessage.Error = call.Error
if !flag {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
}
msgs = append(msgs, nMessage)
}
return msgs, nil
}
func (a *StateAPI) StateCallExt(ctx context.Context, msg *types.Message,priorMsgs types.ChainMsg, tsk types.TipSetKey) (res *api.InvocResult, err error) {
ts, err := a.Chain.GetTipSetFromKey(tsk)
if err != nil {
return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err)
}
for {
res, err = a.StateManager.CallExt(ctx, msg,ts)
if err != stmgr.ErrExpensiveFork {
break
}
ts, err = a.Chain.GetTipSetFromKey(ts.Parents())
if err != nil {
return nil, xerrors.Errorf("getting parent tipset: %w", err)
}
}
return res, err
}
func (a *StateAPI) StateReplayTest(ctx context.Context, tsk types.TipSetKey, mc []cid.Cid) ([]*api.InvocResult, error) {
var rets []*api.InvocResult
return rets,nil
}
func (a *StateAPI) StateReplayEx(ctx context.Context, tsk types.TipSetKey) ([]*api.InvocResults, error) {
//var ts *types.TipSet
//var err error
//
//ts, err = a.Chain.LoadTipSet(tsk)
//if err != nil {
// return nil, xerrors.Errorf("loading specified tipset %s: %w", tsk, err)
//}
//_, r, err := a.StateManager.ReplayEx(ctx, ts)
return nil,nil
}
func (a *StateAPI) StateComputeBaseFee(ctx context.Context, bcid cid.Cid) (abi.TokenAmount, error) {
b, err := a.Chain.GetBlock(bcid)
if err != nil {
return abi.TokenAmount{}, xerrors.Errorf("loading tipset %s: %w", b, err)
}
tsk := types.NewTipSetKey(b.Parents...)
ts, err := a.Chain.LoadTipSet(tsk)
if err != nil {
return abi.TokenAmount{}, xerrors.Errorf("loading tipset %s: %w", tsk, err)
}
fee, err := a.StateManager.ChainStore().ComputeBaseFee(ctx, ts)
if err != nil {
return abi.TokenAmount{}, xerrors.Errorf("loading StateComputeBaseFee %s: %w", tsk, err)
}
return fee,nil
}
func (a *StateAPI) StateComputeBaseFeeTest(ctx context.Context) (abi.TokenAmount, error) {
return abi.NewTokenAmount(100),nil
}
func (a *StateAPI) StateGetMessageByHeightInterval(ctx context.Context, height int64) ([]*api.NMessage, error) {
var out []*api.NMessage
byHeight, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(height), nil, true)
if byHeight == nil {
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
log.Info("byHeight",byHeight.Height(),abi.ChainEpoch(height))
if byHeight.Height().String()!=abi.ChainEpoch(height).String(){
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
set := a.Chain.GetHeaviestTipSet()
cids := set.Cids()
c := cids[0]
headers, err := a.Chain.GetBlock(c)
if err != nil {
return nil, err
}
if err != nil {
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
list, err := a.StateReplayList(ctx,byHeight)
for _, header := range byHeight.Blocks() {
b, err := a.Chain.GetBlock(header.Cid())
if err != nil {
return nil, err
}
blscids, secpkcids, err := a.Chain.ReadMsgMetaCids(b.Messages)
if err != nil {
return nil, err
}
out, err = a.LoadMessagesFromCidsByHeight(blscids, headers, ctx, out, list,header)
if err != nil {
return nil, xerrors.Errorf("loading LoadMessagesFromCidsByHeight %s: %w", byHeight, err)
}
out, err = a.LoadSignedMessagesFromCidsByHeight(secpkcids, headers, ctx, out, list,header)
if err != nil {
return nil, xerrors.Errorf("loading fromCidsByHeight %s: %w", byHeight, err)
}
}
return out,nil
}
func (a *StateAPI) StateGetBlockByHeightInterval(ctx context.Context, height int64) ([]*types.BlockHeaders, error) {
var out []*types.BlockHeaders
byHeight, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(height), nil, true)
if byHeight == nil {
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
log.Info("byHeight",byHeight.Height(),abi.ChainEpoch(height))
if byHeight.Height().String()!=abi.ChainEpoch(height).String(){
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
if err != nil {
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
for _, header := range byHeight.Blocks() {
reward, err := a.StateGetRewardLastPerEpochReward(ctx, types.NewTipSetKey(header.Cid()))
if err != nil {
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
t := new(types.BlockHeaders)
t.BlockId = header.Cid()
t.Miner = header.Miner
t.Ticket = header.Ticket
t.ElectionProof = header.ElectionProof
t.BeaconEntries = header.BeaconEntries
t.WinPoStProof = header.WinPoStProof
t.Parents = header.Parents
t.ParentWeight = header.ParentWeight
t.Height = header.Height
t.ParentStateRoot = header.ParentStateRoot
t.ParentMessageReceipts = header.ParentMessageReceipts
t.Messages = header.Messages
t.BLSAggregate = header.BLSAggregate
t.Timestamp = header.Timestamp
t.BlockSig = header.BlockSig
t.ForkSignaling = header.ForkSignaling
t.ParentBaseFee = header.ParentBaseFee
t.Reward = reward
out = append(out, t);
}
return out,nil
}
func (a *StateAPI) StateGetBlockByHeightWhere(ctx context.Context, params api.StateGetBlockByHeightIntervalParams) ([]*types.BlockHeaders, error) {
startHeight := params.StartHeight
endHeight := params.EndHeight
heightfix := endHeight-startHeight
height := startHeight-1
var out []*types.BlockHeaders
for i := 0; i <= heightfix; i++ {
if height >endHeight{
break
}
height = height+1
byHeight, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(height), nil, true)
if byHeight == nil {
continue;
}
log.Info("byHeight",byHeight.Height(),abi.ChainEpoch(height))
if byHeight.Height().String()!=abi.ChainEpoch(height).String(){
continue;
//return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
if err != nil {
continue;
}
for _, header := range byHeight.Blocks() {
reward, err := a.StateGetRewardLastPerEpochReward(ctx, types.NewTipSetKey(header.Cid()))
if err != nil {
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
t := new(types.BlockHeaders)
t.BlockId = header.Cid()
t.Miner = header.Miner
t.Ticket = header.Ticket
t.ElectionProof = header.ElectionProof
t.BeaconEntries = header.BeaconEntries
t.WinPoStProof = header.WinPoStProof
t.Parents = header.Parents
t.ParentWeight = header.ParentWeight
t.Height = header.Height
t.ParentStateRoot = header.ParentStateRoot
t.ParentMessageReceipts = header.ParentMessageReceipts
t.Messages = header.Messages
t.BLSAggregate = header.BLSAggregate
t.Timestamp = header.Timestamp
t.BlockSig = header.BlockSig
t.ForkSignaling = header.ForkSignaling
t.ParentBaseFee = header.ParentBaseFee
t.Reward = reward
out = append(out, t);
}
}
var sout []*types.BlockHeaders
if len(params.MinerAddress) >0 {
for _, headers := range out {
for _, minerAddress := range params.MinerAddress {
if minerAddress == headers.Miner.String() {
sout = append(sout, headers)
}
}
}
return sout,nil
}
return out,nil
}
func (a *StateAPI) StateGetMessageDealsByHeightInterval(ctx context.Context, height int64) ([]*api.StateGetParentDealsResp, error) {
log.Info("comming StateGetMessageDealsByHeightInterval")
height = height +1
byHeight, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(height), nil, true)
if byHeight == nil {
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
log.Info("byHeight",byHeight.Height(),abi.ChainEpoch(height))
if byHeight.Height().String()!=abi.ChainEpoch(height).String(){
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
header := byHeight.Blocks()[0]
deals, err := a.StateGetParentDeals(ctx, header.Cid())
if err != nil {
return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
}
return deals,nil
}
//func (a *StateAPI) StateGetMessageDealsByHeightInterval(ctx context.Context, height int64) ([]*api.StateGetMessageDealsByHeightIntervalResp, error) {
//
// var resp []*api.StateGetMessageDealsByHeightIntervalResp
//
//
// var out []*api.NMessage
//
//
// byHeight, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(height), nil, true)
//
// if byHeight == nil {
// return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
//
// }
//
//
//
// if err != nil {
// return nil, xerrors.Errorf("loading GetTipsetByHeight %s: %w", byHeight, err)
// }
//
// //list, err := a.StateReplayList(ctx,byHeight)
// for _, header := range byHeight.Blocks() {
//
// b, err := a.Chain.GetBlock(header.Cid())
// if err != nil {
// return nil, err
// }
//
// blscids, secpkcids, err := a.Chain.ReadMsgMetaCids(b.Messages)
// if err != nil {
// return nil, err
// }
//
// resp, err = a.LoadMessagesFromCidsByHeightDeal(blscids, header, ctx, out,resp)
//
// if err != nil {
// return nil, xerrors.Errorf("loading LoadMessagesFromCidsByHeight %s: %w", byHeight, err)
// }
//
// resp, err = a.LoadSignedMessagesFromCidsByHeightDeal(secpkcids, header, ctx, out,resp)
//
// if err != nil {
// return nil, xerrors.Errorf("loading fromCidsByHeight %s: %w", byHeight, err)
// }
//
// }
// return resp,nil
//
//
//}
func (cs *StateAPI) LoadMessagesFromCidsByHeight(cids []cid.Cid,b *types.BlockHeader,ctx context.Context,msgs []*api.NMessage,list []*api.InvocResult,block *types.BlockHeader) ([]*api.NMessage, error) {
//t := types.NewTipSetKey(b.Cid())
t := types.EmptyTSK
for i, c := range cids {
var flag = false
m, err := cs.Chain.GetMessage(c)
if err != nil {
return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
var invocResult *api.InvocResult
for _, results := range list {
if results.MsgCid.String() == m.Cid().String(){
invocResult = results
continue
}
}
var actor *types.Actor
actor, err = cs.StateManager.LoadActorTsk(ctx, m.To, t)
if err != nil {
actor, err = cs.StateGetActor(ctx, m.To, t)
if(err != nil){
flag = true
}else {
log.Debugf("hhactorCode is null",c,t)
}
}
nMessage := new(api.NMessage)
if m.Params != nil {
if !flag {
par, err := jsonParams(actor.Code, m.Method, m.Params)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
}
nMessage.Params = par
}
}
if invocResult != nil {
if invocResult.MsgRct.Return !=nil {
if !flag {
returns, err := jsonReturn(actor.Code, m.VMMessage().Method, invocResult.MsgRct.Return)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", err)
}
invocResult.MsgRct.Returns = returns
}
}
nMessage.GasCost = invocResult.GasCost
nMessage.ExecutionTrace = invocResult.ExecutionTrace
nMessage.Duration = invocResult.Duration
nMessage.Error = invocResult.Error
nMessage.MsgRct = invocResult.MsgRct
nMessage.Timestamp = invocResult.Timestamp
}else {
mcp := new(types.MessageReceipt)
mcp.ExitCode = -1
nMessage.MsgRct = mcp
}
nMessage.Paramss = m.Params
nMessage.Version = m.Version
nMessage.To = m.To
nMessage.From = m.From
nMessage.Nonce = m.Nonce
nMessage.Value = m.Value
nMessage.GasLimit = m.GasLimit
nMessage.GasFeeCap = m.GasFeeCap
nMessage.GasPremium = m.GasPremium
nMessage.Method = m.Method
nMessage.CID = c
nMessage.BlockCid = block.Cid()
if !flag {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
if nMessage.CodeMethod == "<undefined>" || nMessage.CodeMethod == "<unknown>"{
nMessage.CodeMethod = BuiltinName4(actor.Code)
}
if nMessage.CodeMethod == "<undefined>" || nMessage.CodeMethod == "<unknown>"{
nMessage.CodeMethod = BuiltinName3(actor.Code)
}
if nMessage.CodeMethod == "<undefined>" || nMessage.CodeMethod == "<unknown>"{
nMessage.CodeMethod = BuiltinName2(actor.Code)
}
if nMessage.CodeMethod == "<undefined>" || nMessage.CodeMethod == "<unknown>"{
nMessage.CodeMethod = BuiltinName1(actor.Code)
}
if nMessage.CodeMethod !=""{
split := strings.Split( nMessage.CodeMethod, "/")
bame := split[len(split)-1]
nMessage.CodeMethod = bame
}else {
log.Debugf("codeMethod is null",nMessage.CID,actor.Code)
}
}
msgs = append(msgs, nMessage)
}
return msgs, nil
}
func (cs *StateAPI) LoadMessagesFromCidsByHeightDeal(cids []cid.Cid,b *types.BlockHeader,ctx context.Context,msgs []*api.NMessage,deal []*api.StateGetMessageDealsByHeightIntervalResp) ([]*api.StateGetMessageDealsByHeightIntervalResp, error) {
t := types.NewTipSetKey(b.Cid())
for i, c := range cids {
var flag = false
m, err := cs.Chain.GetMessage(c)
if err != nil {
return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
//var invocResult *api.InvocResults
//for _, results := range list {
// if results.MsgCid.String() == m.Cid().String(){
// invocResult = results
// continue
// }
//
//
//}
var actor *types.Actor
actor, err = cs.StateManager.LoadActorTsk(ctx, m.To, t)
if err != nil {
actor, err = cs.StateGetActor(ctx, m.To, t)
if(err != nil){
flag = true
}
}
nMessage := new(api.NMessage)
if m.Params != nil {
if !flag {
par, err := jsonParams(actor.Code, m.Method, m.Params)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
}
nMessage.Params = par
}
}
//if invocResult != nil {
// if invocResult.MsgRct.Return !=nil {
// if !flag {
// returns, err := jsonReturn(actor.Code, m.VMMessage().Method, invocResult.MsgRct.Return)
// if err != nil {
// return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", err)
// }
// invocResult.MsgRct.Returns = returns
//
// }
//
// }
//
// nMessage.GasCost = invocResult.GasCost
// nMessage.ExecutionTrace = invocResult.ExecutionTrace
// nMessage.Duration = invocResult.Duration
// nMessage.Error = invocResult.Error
// nMessage.MsgRct = invocResult.MsgRct
//
//}else {
// mcp := new(types.MessageReceipt)
// mcp.ExitCode = -1
// nMessage.MsgRct = mcp
//}
nMessage.Version = m.Version
nMessage.To = m.To
nMessage.From = m.From
nMessage.Nonce = m.Nonce
nMessage.Value = m.Value
nMessage.GasLimit = m.GasLimit
nMessage.GasFeeCap = m.GasFeeCap
nMessage.GasPremium = m.GasPremium
nMessage.Method = m.Method
nMessage.CID = c
nMessage.BlockCid = b.Cid()
if !flag {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
if nMessage.CodeMethod == "fil/4/storagemarket" && nMessage.Method == 4{
tsk := types.EmptyTSK
a := new(api.StateGetMessageDealsByHeightIntervalResp)
var marketDeal []*api.MarketDeal
resps := Deals{}
err := json.Unmarshal([]byte(nMessage.MsgRct.Returns), &resps)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", nMessage.MsgRct.Returns, nMessage.CID.String(), err)
}
for _, d := range resps.IDs {
deal, err := cs.StateMarketStorageDeal(ctx, d, tsk)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", d, i, err)
}
key, err := cs.StateAccountKey(ctx, deal.Proposal.Client, tsk)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", d, i, err)
}
deal.Proposal.Client = key
marketDeal = append(marketDeal,deal )
}
a.Msg = nMessage
a.Deal = marketDeal
deal = append(deal, a)
}
}
//msgs = append(msgs, nMessage)
}
return deal, nil
}
func (cs *StateAPI) LoadSignedMessagesFromCidsByHeightDeal(cids []cid.Cid,b *types.BlockHeader,ctx context.Context,msgs []*api.NMessage,deal []*api.StateGetMessageDealsByHeightIntervalResp) ([]*api.StateGetMessageDealsByHeightIntervalResp, error) {
t := types.NewTipSetKey(b.Cid())
for i, c := range cids {
var flag = false
m, err := cs.Chain.GetSignedMessage(c)
if err != nil {
return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
var actor *types.Actor
actor, err = cs.StateManager.LoadActorTsk(ctx, m.VMMessage().To, t)
if err != nil {
actor, err = cs.StateGetActor(ctx, m.VMMessage().To, t)
if(err != nil){
flag = true
}
}
nMessage := new(api.NMessage)
if m.VMMessage().Params != nil {
if !flag {
par, err := jsonParams(actor.Code, m.VMMessage().Method, m.VMMessage().Params)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
}
nMessage.Params = par
}
}
nMessage.Version = m.VMMessage().Version
nMessage.To = m.VMMessage().To
nMessage.From = m.VMMessage().From
nMessage.Nonce = m.VMMessage().Nonce
nMessage.Value = m.VMMessage().Value
nMessage.GasLimit = m.VMMessage().GasLimit
nMessage.GasFeeCap = m.VMMessage().GasFeeCap
nMessage.GasPremium = m.VMMessage().GasPremium
nMessage.Method = m.VMMessage().Method
nMessage.CID = c
nMessage.BlockCid = b.Cid()
if !flag {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
if nMessage.CodeMethod == "fil/4/storagemarket" && nMessage.Method == 4{
tsk := types.EmptyTSK
a := new(api.StateGetMessageDealsByHeightIntervalResp)
var marketDeal []*api.MarketDeal
resps := Deals{}
err := json.Unmarshal([]byte(nMessage.MsgRct.Returns), &resps)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", nMessage.MsgRct.Returns, nMessage.CID, err)
}
for _, d := range resps.IDs {
deal, err := cs.StateMarketStorageDeal(ctx, d, tsk)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", d, i, err)
}
key, err := cs.StateAccountKey(ctx, deal.Proposal.Client, tsk)
if err != nil {
return nil, xerrors.Errorf("failed to get Actor: (%s):%d: %w", d, i, err)
}
deal.Proposal.Client = key
marketDeal = append(marketDeal,deal )
}
a.Msg = nMessage
a.Deal = marketDeal
deal = append(deal, a)
}
}
}
return deal, nil
}
func (cs *StateAPI) LoadSignedMessagesFromCidsByHeight(cids []cid.Cid,b *types.BlockHeader,ctx context.Context,msgs []*api.NMessage,list []*api.InvocResult,block *types.BlockHeader) ([]*api.NMessage, error) {
//t := types.NewTipSetKey(b.Cid())
t := types.EmptyTSK
for i, c := range cids {
var flag = false
m, err := cs.Chain.GetSignedMessage(c)
if err != nil {
return nil, xerrors.Errorf("failed to get message: (%s):%d: %w", c, i, err)
}
var invocResult *api.InvocResult
for _, results := range list {
if results.MsgCid.String() == m.Cid().String(){
invocResult = results
continue
}
}
var actor *types.Actor
actor, err = cs.StateManager.LoadActorTsk(ctx, m.VMMessage().To, t)
if err != nil {
actor, err = cs.StateGetActor(ctx, m.VMMessage().To, t)
if(err != nil){
flag = true
}else {
log.Debugf("hhactorCode is null",c,t)
}
}
nMessage := new(api.NMessage)
if m.VMMessage().Params != nil {
if !flag {
par, err := jsonParams(actor.Code, m.VMMessage().Method, m.VMMessage().Params)
if err != nil {
//if err != nil {
// return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", err)
//}
//log.Errorf("failed to get jsonParams: (%s):%d: %w", c, i, err)
nMessage.Params = par
}
}
}
if invocResult != nil {
if invocResult.MsgRct.Return !=nil {
if !flag {
returns, err := jsonReturn(actor.Code, m.VMMessage().Method, invocResult.MsgRct.Return)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", err)
}
invocResult.MsgRct.Returns = returns
}
}
nMessage.GasCost = invocResult.GasCost
nMessage.ExecutionTrace = invocResult.ExecutionTrace
nMessage.Duration = invocResult.Duration
nMessage.Error = invocResult.Error
nMessage.MsgRct = invocResult.MsgRct
nMessage.Timestamp = invocResult.Timestamp
}else {
mcp := new(types.MessageReceipt)
mcp.ExitCode = -1
nMessage.MsgRct = mcp
}
nMessage.Paramss = m.VMMessage().Params
nMessage.Version = m.VMMessage().Version
nMessage.To = m.VMMessage().To
nMessage.From = m.VMMessage().From
nMessage.Nonce = m.VMMessage().Nonce
nMessage.Value = m.VMMessage().Value
nMessage.GasLimit = m.VMMessage().GasLimit
nMessage.GasFeeCap = m.VMMessage().GasFeeCap
nMessage.GasPremium = m.VMMessage().GasPremium
nMessage.Method = m.VMMessage().Method
nMessage.CID = c
nMessage.BlockCid = block.Cid()
if !flag {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
if nMessage.CodeMethod == "<undefined>" || nMessage.CodeMethod == "<unknown>"{
nMessage.CodeMethod = BuiltinName4(actor.Code)
}
if nMessage.CodeMethod == "<undefined>" || nMessage.CodeMethod == "<unknown>"{
nMessage.CodeMethod = BuiltinName3(actor.Code)
}
if nMessage.CodeMethod == "<undefined>" || nMessage.CodeMethod == "<unknown>"{
nMessage.CodeMethod = BuiltinName2(actor.Code)
}
if nMessage.CodeMethod == "<undefined>" || nMessage.CodeMethod == "<unknown>"{
nMessage.CodeMethod = BuiltinName1(actor.Code)
}
if nMessage.CodeMethod !=""{
split := strings.Split( nMessage.CodeMethod, "/")
bame := split[len(split)-1]
nMessage.CodeMethod = bame
}else {
log.Debugf("codeMethod is null",nMessage.CID)
}
}
msgs = append(msgs, nMessage)
}
return msgs, nil
}
func (a *StateAPI) StateGetBlockByHeight(ctx context.Context, start int64, end int64) ([]*api.Blocks, error) {
ts, err := a.Chain.GetTipSetFromKey(types.EmptyTSK)
if err != nil {
return nil, xerrors.Errorf("loading tipset %s: %w", err)
}
startTs, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(start), ts, true)
if err != nil {
return nil, xerrors.Errorf("loading tipset %s: %w", err)
}
var resp []*api.Blocks
if(end==2){
for _, header := range startTs.Blocks() {
a2 := new(api.Blocks)
reward, err := a.StateGetRewardLastPerEpochReward(ctx, types.NewTipSetKey(header.Cid()))
if err != nil {
return nil, xerrors.Errorf("loading reward %s: %w",reward, err)
}
a2.Cid = header.Cid().String()
a2.Miner = header.Miner
a2.Reward = reward
a2.Height = header.Height
a2.Timestamp = header.Timestamp
resp = append(resp, a2)
}
return resp,nil
}
set := a.Chain.GetHeaviestTipSet()
i1, err := strconv.ParseInt(set.Height().String(), 10, 64)
if err != nil {
return nil, xerrors.Errorf("loading reward %s: %w", err)
}
num := i1 - start
strInt64 := strconv.FormatInt(num, 10)
id16 ,_ := strconv.Atoi(strInt64)
startHeight := start-1
for i := 0; i <= id16; i++ {
startHeight = startHeight+1
log.Info("startHeight",startHeight)
tss, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(startHeight), ts, true)
if err != nil {
return nil, xerrors.Errorf("loading reward %s: %w", err)
}
for _, header := range tss.Blocks() {
a2 := new(api.Blocks)
reward, err := a.StateGetRewardLastPerEpochReward(ctx, types.NewTipSetKey(header.Cid()))
if err != nil {
return nil, xerrors.Errorf("loading reward %s: %w",reward, err)
}
a2.Cid = header.Cid().String()
a2.Miner = header.Miner
a2.Reward = reward
a2.Height = header.Height
a2.Timestamp = header.Timestamp
resp = append(resp, a2)
}
}
return resp,nil
}
func (a *StateAPI) StateMinerVestingFundsByHeight(ctx context.Context, maddr address.Address, start abi.ChainEpoch,end abi.ChainEpoch,tsk types.TipSetKey) ([]map[string]interface{}, error) {
ts, err := a.Chain.GetTipSetFromKey(tsk)
if err != nil {
return nil, xerrors.Errorf("loading tipset %s: %w", err)
}
act, err := a.StateManager.LoadActor(ctx, maddr, ts)
if err != nil {
return nil, xerrors.Errorf("failed to load miner actor: %w", err)
}
mas, err := miner.Load(a.StateManager.ChainStore().ActorStore(ctx), act)
if err != nil {
return nil, xerrors.Errorf("failed to load miner actor state: %w", err)
}
vested, err := mas.LoadVestingFundList()
if err != nil {
return nil, err
}
//var res []map[string]interface{}
//
//for _, m := range vested {
// //if Epoch>=start && Epoch<=end{
// m2 := make(map[string]interface{})
// m2["Epoch"] = m["Epoch"].(abi.ChainEpoch)
// m2["Amount"] = m["Amount"]
// res = append(res, m2)
// //}
//}
//abal, err := mas.AvailableBalance(act.Balance)
//if err != nil {
// return types.EmptyInt, err
//}
return vested, nil
}
func (a *StateAPI) StateMessageByHeight(ctx context.Context, epoch abi.ChainEpoch) ([]*api.InvocResultExt, error) {
var exts []*api.InvocResultExt
tsk := types.EmptyTSK
ts, err := a.Chain.GetTipSetFromKey(tsk)
if err != nil {
return nil, xerrors.Errorf("loading tipset %s: %w", err)
}
startTs, err := a.Chain.GetTipsetByHeight(ctx, abi.ChainEpoch(epoch), ts, true)
if err != nil {
return nil, xerrors.Errorf("loading tipset %s: %w", err)
}
_, t, err := stmgr.ComputeState(ctx, a.StateManager, startTs.Height(), nil, startTs)
if err != nil {
return nil, err
}
for _, result := range t {
m := result.Msg
invocResultExt := new(api.InvocResultExt)
nMessage := new(api.NMessage)
var flag = false
var actor *types.Actor
actor, err = a.StateManager.LoadActorTsk(ctx, m.To, tsk)
if err != nil {
actor, err = a.StateGetActor(ctx, m.To, tsk)
if(err != nil){
flag = true
}
}
if m.Params != nil {
if !flag {
par, err := jsonParams(actor.Code, m.Method, m.Params)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", err)
}
nMessage.Params = par
}
}
if result != nil {
if result.MsgRct.Return !=nil {
if !flag {
returns, err := jsonReturn(actor.Code, m.Method, result.MsgRct.Return)
if err != nil {
return nil, xerrors.Errorf("failed to get jsonParams: (%s):%d: %w", err)
}
result.MsgRct.Returns = returns
}
}
nMessage.MsgRct = result.MsgRct
}
nMessage.Version = m.Version
nMessage.To = m.To
nMessage.From = m.From
nMessage.Nonce = m.Nonce
nMessage.Value = m.Value
nMessage.GasLimit = m.GasLimit
nMessage.GasFeeCap = m.GasFeeCap
nMessage.GasPremium = m.GasPremium
nMessage.Method = m.Method
nMessage.CID = result.MsgCid
//nMessage.BlockId = result.BlockId
//nMessage.Height = result.Height
//nMessage.GasCost = result.GasCost
//nMessage.ExecutionTrace = result.ExecutionTrace
//nMessage.Duration = result.Duration
//nMessage.Error = result.Error
if !flag {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
}
invocResultExt.Timestamp = result.Timestamp
invocResultExt.Msg = nMessage
invocResultExt.MsgRct = result.MsgRct
invocResultExt.Error = result.Error
invocResultExt.Duration = result.Duration
invocResultExt.GasCost = result.GasCost
invocResultExt.MsgCid = result.MsgCid
invocResultExt.ExecutionTrace = result.ExecutionTrace
invocResultExt.BlockId = result.BlockId
invocResultExt.Height = result.Height
exts = append(exts, invocResultExt)
}
return exts,nil
}
func (a *StateAPI) StateGetMessageTest(ctx context.Context,height int) (int, error) {
return height, nil
}
func (a *StateAPI) StateReplayNoTs(ctx context.Context, mc cid.Cid) (*api.InvocResult, error) {
replay, err2 := a.StateReplay(ctx, types.EmptyTSK, mc)
if err2 != nil {
return nil, xerrors.Errorf("loading StateReplayNoTs %s: %w", err2)
}
return replay,nil
}
func (a *StateAPI) StateMarketStorageDealNoTs(ctx context.Context, dealId abi.DealID) (*api.MarketDeal, error) {
onChain, err := a.StateMarketStorageDeal(ctx, dealId, types.EmptyTSK)
if err != nil {
return nil, xerrors.Errorf("loading StateMarketStorageDealNoTs %s: %w", err)
}
return onChain,nil
}
func (a *StateAPI) StateTest(ctx context.Context,parame api.StateTestParams) (abi.SectorQuality, error) {
size := abi.SectorSize(parame.Size)
duration := abi.ChainEpoch(parame.Duration)
dealWeight := big.NewInt(parame.DealWeight)
verifiedWeight := big.NewInt(parame.VerifiedWeight)
log.Infof("size %d",size)
log.Infof("duration %d",duration)
log.Infof("dealWeight %v",dealWeight)
log.Infof("verifiedWeight %v",verifiedWeight)
sectorWeight := builtin.QAPowerForWeight(size, duration, dealWeight, verifiedWeight)
return sectorWeight,nil
}
func (m *StateAPI) StateSectorGetInfoQa(ctx context.Context, maddr address.Address, n abi.SectorNumber, tsk types.TipSetKey) (*api.StateSectorGetInfoQaResp, error) {
ts, err := m.Chain.GetTipSetFromKey(tsk)
if err != nil {
return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err)
}
info, err := stmgr.MinerSectorInfo(ctx, m.StateManager, maddr, n, ts)
if err != nil {
return nil, xerrors.Errorf("loading MinerSectorInfo %s: %w", tsk, err)
}
minerInfo, err := m.StateMinerInfo(ctx, maddr, tsk)
if err != nil {
return nil, xerrors.Errorf("loading minerInfo %s: %w", tsk, err)
}
duration := info.Expiration-info.Activation
sectorWeight := builtin.QAPowerForWeight(minerInfo.SectorSize, duration, info.DealWeight, info.VerifiedDealWeight)
a := new(api.StateSectorGetInfoQaResp)
a.SectorOnChainInfo = info
a.SectorQuality = sectorWeight
return a,nil
}
func (a *StateAPI) StateMinerSectorsQa(ctx context.Context, addr address.Address, sectorNos *bitfield.BitField, tsk types.TipSetKey) ([]*api.SectorOnChainInfoQa, error) {
act, err := a.StateManager.LoadActorTsk(ctx, addr, tsk)
if err != nil {
return nil, xerrors.Errorf("failed to load miner actor: %w", err)
}
mas, err := miner.Load(a.StateManager.ChainStore().ActorStore(ctx), act)
if err != nil {
return nil, xerrors.Errorf("failed to load miner actor state: %w", err)
}
sectors, err := mas.LoadSectors(sectorNos)
if err != nil {
return nil, xerrors.Errorf("failed to LoadSectors : %w", err)
}
minerInfo, err := a.StateMinerInfo(ctx, addr, tsk)
if err != nil {
return nil, xerrors.Errorf("loading minerInfo %s: %w", tsk, err)
}
var res []*api.SectorOnChainInfoQa
for _, sector := range sectors {
a2 := new(api.SectorOnChainInfoQa)
duration := sector.Expiration-sector.Activation
sectorWeight := builtin.QAPowerForWeight(minerInfo.SectorSize, duration, sector.DealWeight, sector.VerifiedDealWeight)
a2.SectorNumber = sector.SectorNumber
a2.SealProof = sector.SealProof
a2.SealedCID = sector.SealedCID
a2.DealIDs = sector.DealIDs
a2.Activation = sector.Activation
a2.Expiration = sector.Expiration
a2.DealWeight = sector.DealWeight
a2.VerifiedDealWeight = sector.VerifiedDealWeight
a2.InitialPledge = sector.InitialPledge
a2.ExpectedDayReward = sector.ExpectedDayReward
a2.ExpectedStoragePledge = sector.ExpectedStoragePledge
a2.SectorQuality = sectorWeight
res = append(res,a2 )
}
return res,nil
}
func (a *StateAPI) StateWithdrawal(ctx context.Context, params *api.StateWithDrawalReq) (string, error) {
fmt.Print("StateWithdrawal:",params)
//str := params.Root+" "+params.Miner+" "+params.EpochPrice+" "+params.MinBlocksDuration
//fmt.Print("ClientStartDealGoReq:"+str)
cmd := exec.Command("./lotus", "send", "--from",params.From, params.To ,params.Amount)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return "", xerrors.Errorf("failed lotus send: %w", err.Error(), stderr.String())
} else {
log.Info(out.String())
}
return out.String(),nil
}
func (a *StateAPI) StateGetMessage(ctx context.Context, params cid.Cid) (*api.NMessage, error) {
cm, err := a.Chain.GetCMessage(params)
if err != nil {
return nil, err
}
sm := cm.VMMessage()
nMessage := new(api.NMessage)
nMessage.Version = sm.Version
nMessage.To = sm.To
nMessage.From = sm.From
nMessage.Nonce = sm .Nonce
nMessage.Value = sm.Value
nMessage.GasLimit = sm.GasLimit
nMessage.GasFeeCap = sm.GasFeeCap
nMessage.GasPremium = sm.GasPremium
nMessage.Method = sm.Method
nMessage.CID = sm.Cid()
var flag = false
var actor *types.Actor
tsk := types.EmptyTSK
actor, err = a.StateManager.LoadActorTsk(ctx, nMessage.To, tsk)
if err != nil {
actor, err = a.StateGetActor(ctx, nMessage.To, tsk)
if(err != nil){
flag = true
}
}
if !flag {
nMessage.CodeMethod = builtin.ActorNameByCode(actor.Code)
}
//ts, err := a.Chain.GetTipSetFromKey(tsk)
//if err != nil {
// return nil, xerrors.Errorf("loading tipset %s: %w", tsk, err)
//}
//receipt, err := a.StateManager.GetReceipt(ctx, params, ts)
//
//if err != nil {
// return nil, xerrors.Errorf("loading receipt %s: %w", tsk, err)
//}
//nMessage.GasUsed = receipt.GasUsed
//nMessage.ExitCode = receipt.ExitCode
return nMessage ,err
}
func (a *StateAPI) StateMpoolReplace(ctx context.Context, params cid.Cid) (string, error) {
set := a.Chain.GetHeaviestTipSet()
cids := set.Cids()
block, err := a.Chain.GetBlock(cids[0])
if err != nil {
return "", xerrors.Errorf("failed lotus send: %w", err.Error(), err)
}
var num1 float64 = 1.2
var num2 float64 = 1.5
fee := block.ParentBaseFee
endGasFeeCap := decimal.NewFromFloat(num1).Mul(decimal.NewFromFloat(float64(fee.Int64())))
endGasFeeStr := strings.Split(endGasFeeCap.String(), ".")
endGasFee := endGasFeeStr[0]
message, err := a.Chain.GetCMessage(params)
if err != nil {
return "", xerrors.Errorf("failed lotus send: %w", err.Error(), err)
}
newInt := big.NewInt(message.VMMessage().GasPremium.Int64())
mul := decimal.NewFromFloat(num2).Mul(decimal.NewFromFloat(float64(newInt.Int64())))
gaspremiumStr := strings.Split(mul.String(), ".")
gaspremium := gaspremiumStr[0]
fmt.Print("gas-premiumss:",gaspremium)
fmt.Print("gas-feecapss:",endGasFee)
fmt.Print("StateMpoolReplace:",params)
//str := params.Root+" "+params.Miner+" "+params.EpochPrice+" "+params.MinBlocksDuration
//fmt.Print("ClientStartDealGoReq:"+str)
cmd := exec.Command("./lotus", "mpool", "replace","--auto=false","--gas-premium",gaspremium,"--gas-feecap",endGasFee,params.String())
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
return "", xerrors.Errorf("failed lotus send: %w", err.Error(), stderr.String())
} else {
log.Info(out.String())
}
return out.String(),nil
}
func (a *StateAPI) StateDecodeReturn(ctx context.Context, toAddr address.Address, method abi.MethodNum, params []byte) (string, error) {
tsk := types.EmptyTSK
var act *types.Actor
var err error
act, err = a.StateManager.LoadActorTsk(ctx, toAddr, tsk)
if err != nil {
act, err = a.StateGetActor(ctx, toAddr, tsk)
if err != nil {
return "", err
}
}
//if builtin.IsStorageMarketMinerActor(act.Code) {
// if method == market.Methods.PublishStorageDeals {
// var ret market.PublishStorageDealsReturn
// err := ret.UnmarshalCBOR(bytes.NewReader(params))
// if err != nil {
// return "", err
// }
// b, err := json.MarshalIndent(&ret, "", " ")
// result:=string(b)
// return result, err
// }
//}
jsonReturn, err := jsonReturn(act.Code, method, params)
if err != nil {
return "", err
}
return jsonReturn,nil
}
|
package loadtest
import (
"time"
)
// An Endpoint represents a URL and a weight indicating the "importance" of the URL.
type Endpoint struct {
// The URL on which the request will be performed.
URL string
// The "importance" of the URL. The higher the number,
// the more often a request on the endpoint will be made.
Weight uint
}
// EndpointResult contains all necessary information of a runners response results.
type EndpointResult struct {
// URL is the ressource requested by the runner.
URL string
// HTTPStatusCode is the http status code of the runners response.
HTTPStatusCode int
// HTTPStatusMessage is the http status message of the runners response.
HTTPStatusMessage string
// TTFB is the time-to-first-byte of the runners response.
TTFB time.Duration
// Cached indicates if the browser cache was used instead of performing a real request.
Cached bool
}
// BrowserType represents a type of browser.
type BrowserType int
const (
// BrowserTypeFake represents a fake browser type.
BrowserTypeFake BrowserType = 0
// BrowserTypeChrome represents a chrome browser type.
BrowserTypeChrome BrowserType = 1
)
|
package databases
import (
"WhereIsMyDriver/adapters"
"WhereIsMyDriver/helper"
"log"
)
//MigrateDB ...
func MigrateDB(v interface{}) {
db, err := adapters.ConnectDB()
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(v)
if err != nil {
log.Println("error when migrate", err)
}
errorCloseDB := db.Close()
helper.CheckError("Error when close db ", errorCloseDB)
}
|
package gacha_odds
import (
"Golang-API-Game/pkg/repository"
"database/sql"
"log"
)
// gacha_oddsテーブルデータ
type GachaOdds struct {
CharacterID string
Odds int
}
type Total struct {
sum int
}
//gacha_OddsTableのOddsを合計したrowデータをとる
func OddsSum() (int, error) { //selectにするとoddsのsumを取ってくるという意味になってしまう
row := repository.DB.QueryRow("SELECT SUM(odds) FROM gacha_odds") //*だと全カラム,?は引数を受け取るときに必要
return convertToInt(row)
}
// convertToInt rowデータを整数値に変換する
func convertToInt(row *sql.Row) (int, error) { //row型からint型へ変換する必要がある。
total := Total{} //varのように構造体の宣言方法(ゼロ値)
err := row.Scan(&total.sum)
if err != nil {
if err == sql.ErrNoRows {
return 0, nil //int型だからゼロ値
}
log.Println(err)
return 0, err
}
return total.sum, nil //int型だから,intのポイント型を返す場合
}
// convertToGachaOdds rowデータをGachaOddsデータへ変換する
func convertToGachaOdds(row *sql.Row) (*GachaOdds, error) {
gacha_odds := GachaOdds{}
err := row.Scan(&gacha_odds.CharacterID, &gacha_odds.Odds)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
log.Println(err)
return nil, err
}
return &gacha_odds, nil //*GachaOdds,ポイント型で返す必要があるから
}
func SelectByRandomNumber(random int) (*GachaOdds, error) {
rows, err := repository.DB.Query("SELECT * FROM gacha_odds") //ROWをつけると単一の行のみになってしまう
if err != nil {
log.Println("failed to gacha", err)
}
gacha_odds := GachaOdds{} //メモリ消費を抑える
for rows.Next() {
err = rows.Scan(&gacha_odds.CharacterID, &gacha_odds.Odds) //scanによってgacha_oddsに格納しているからエラーを返すだけでいい
if err != nil {
log.Println(gacha_odds)
}
random -= gacha_odds.Odds
if random <= 0 {
break //
}
}
return &gacha_odds, nil
}
|
package api
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/golang/protobuf/proto"
"github.com/hashicorp/raft"
"github.com/robustirc/robustirc/internal/config"
"github.com/robustirc/robustirc/internal/ircserver"
"github.com/robustirc/robustirc/internal/privacy"
"github.com/robustirc/robustirc/internal/raftlog"
"github.com/robustirc/robustirc/internal/robust"
pb "github.com/robustirc/robustirc/internal/proto"
)
//go:generate go run gentmpl.go -package=api templates/header templates/footer templates/status templates/getmessage templates/sessions templates/state templates/statusirclog templates/irclog
func (api *HTTP) handleStatusGetMessage(w http.ResponseWriter, req *http.Request) {
if err := templates.ExecuteTemplate(w, "templates/getmessage", struct {
Addr string
GetMessageRequests map[string]GetMessagesStats
CurrentLink string
Sessions map[robust.Id]ircserver.Session
}{
Addr: api.peerAddr,
GetMessageRequests: api.copyGetMessagesRequests(),
CurrentLink: "/status/getmessage",
Sessions: api.ircServer().GetSessions(),
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (api *HTTP) handleStatusSessions(w http.ResponseWriter, req *http.Request) {
if err := templates.ExecuteTemplate(w, "templates/sessions", struct {
Addr string
Sessions map[robust.Id]ircserver.Session
CurrentLink string
GetMessageRequests map[string]GetMessagesStats
}{
Addr: api.peerAddr,
Sessions: api.ircServer().GetSessions(),
CurrentLink: "/status/sessions",
GetMessageRequests: api.copyGetMessagesRequests(),
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (api *HTTP) handleStatusState(w http.ResponseWriter, req *http.Request) {
textState := "state serialization failed"
state, err := api.ircServer().Marshal(0)
if err != nil {
textState = fmt.Sprintf("state serialization failed: %v", err)
} else {
var snapshot pb.Snapshot
if err := proto.Unmarshal(state, &snapshot); err != nil {
textState = fmt.Sprintf("unmarshaling state failed: %v", err)
} else {
snapshot = privacy.FilterSnapshot(snapshot)
var marshaler proto.TextMarshaler
textState = marshaler.Text(&snapshot)
}
}
if err := templates.ExecuteTemplate(w, "templates/state", struct {
Addr string
ServerState string
CurrentLink string
Sessions map[robust.Id]ircserver.Session
GetMessageRequests map[string]GetMessagesStats
}{
Addr: api.peerAddr,
ServerState: textState,
CurrentLink: "/status/state",
Sessions: api.ircServer().GetSessions(),
GetMessageRequests: api.copyGetMessagesRequests(),
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (api *HTTP) handleStatusIrclog(w http.ResponseWriter, req *http.Request) {
lo, err := api.ircStore().FirstIndex()
if err != nil {
log.Printf("Could not get first index: %v", err)
http.Error(w, "internal error", 500)
return
}
hi, err := api.ircStore().LastIndex()
if err != nil {
log.Printf("Could not get last index: %v", err)
http.Error(w, "internal error", 500)
return
}
// Show the last 50 messages by default.
if hi > 50 && hi-50 > lo {
lo = hi - 50
}
if offsetStr := req.FormValue("offset"); offsetStr != "" {
offset, err := strconv.ParseInt(offsetStr, 0, 64)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
lo = uint64(offset)
}
if hi > lo+50 {
hi = lo + 50
}
var entries []*raft.Log
if lo != 0 && hi != 0 {
for i := lo; i <= hi; i++ {
l := new(raft.Log)
if err := api.ircStore().GetLog(i, l); err != nil {
// Not every message goes into the ircStore (e.g. raft peer change
// messages do not).
continue
}
if l.Type == raft.LogCommand {
msg := robust.NewMessageFromBytes(l.Data, robust.IdFromRaftIndex(l.Index))
msg.Data = msg.PrivacyFilter()
l.Data, _ = json.Marshal(&msg)
}
entries = append(entries, l)
}
}
prevOffset := int64(lo) - 50
if prevOffset < 0 {
prevOffset = 1
}
if err := templates.ExecuteTemplate(w, "templates/statusirclog", struct {
Addr string
First uint64
Last uint64
Entries []*raft.Log
PrevOffset int64
NextOffset uint64
CurrentLink string
Sessions map[robust.Id]ircserver.Session
GetMessageRequests map[string]GetMessagesStats
}{
Addr: api.peerAddr,
First: lo,
Last: hi,
Entries: entries,
PrevOffset: prevOffset,
NextOffset: lo + 50,
CurrentLink: "/status/irclog",
Sessions: api.ircServer().GetSessions(),
GetMessageRequests: api.copyGetMessagesRequests(),
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (api *HTTP) handleStatus(res http.ResponseWriter, req *http.Request) {
cfgf := api.raftNode.GetConfiguration()
if err := cfgf.Error(); err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
servers := cfgf.Configuration().Servers
p := make([]string, len(servers))
for idx, server := range servers {
p[idx] = string(server.Address)
}
// robustirc-rollingrestart wants a machine-readable version of the status.
if req.Header.Get("Accept") == "application/json" {
type jsonStatus struct {
State string
Leader string
Peers []string
AppliedIndex uint64
CommitIndex uint64
LastContact time.Time
ExecutableHash string
CurrentTime time.Time
}
res.Header().Set("Content-Type", "application/json")
leaderStr := string(api.raftNode.Leader())
stats := api.raftNode.Stats()
appliedIndex, err := strconv.ParseUint(stats["applied_index"], 0, 64)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
commitIndex, err := strconv.ParseUint(stats["commit_index"], 0, 64)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(res).Encode(jsonStatus{
State: api.raftNode.State().String(),
Leader: leaderStr,
AppliedIndex: appliedIndex,
CommitIndex: commitIndex,
Peers: p,
LastContact: api.raftNode.LastContact(),
ExecutableHash: executablehash,
CurrentTime: time.Now(),
}); err != nil {
log.Printf("%v\n", err)
http.Error(res, err.Error(), http.StatusInternalServerError)
}
return
}
api.ircServer().ConfigMu.RLock()
defer api.ircServer().ConfigMu.RUnlock()
args := struct {
Addr string
State raft.RaftState
Leader string
Peers []string
Stats map[string]string
Sessions map[robust.Id]ircserver.Session
GetMessageRequests map[string]GetMessagesStats
NetConfig config.Network
CurrentLink string
}{
Addr: api.peerAddr,
State: api.raftNode.State(),
Leader: string(api.raftNode.Leader()),
Peers: p,
Stats: api.raftNode.Stats(),
Sessions: api.ircServer().GetSessions(),
GetMessageRequests: api.copyGetMessagesRequests(),
NetConfig: api.ircServer().Config,
CurrentLink: "/status",
}
if err := templates.ExecuteTemplate(res, "templates/status", args); err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
}
func (api *HTTP) handleIrclog(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseUint(r.FormValue("sessionid"), 0, 64)
if err != nil || id == 0 {
http.Error(w, "Invalid session", http.StatusBadRequest)
return
}
session := robust.Id{Id: id}
// TODO(secure): pagination
var messages []*robust.Message
first, _ := api.ircStore().FirstIndex()
last, _ := api.ircStore().LastIndex()
iterator := api.ircStore().GetBulkIterator(first, last+1)
defer iterator.Release()
for iterator.Next() {
elog, err := raftlog.FromBytes(iterator.Value())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if elog.Type != raft.LogCommand {
continue
}
msg := robust.NewMessageFromBytes(elog.Data, robust.IdFromRaftIndex(elog.Index))
if msg.Session.Id == session.Id {
messages = append(messages, &msg)
}
output, ok := api.output().Get(msg.Id)
if ok {
for _, msg := range outputToRobustMessages(output) {
if !msg.InterestingFor[session.Id] {
continue
}
messages = append(messages, msg)
}
}
}
if err := iterator.Error(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
args := struct {
Session robust.Id
Messages []*robust.Message
}{
session,
messages,
}
if err := templates.ExecuteTemplate(w, "templates/irclog", args); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
|
package datastruct
import (
"container/list"
"fmt"
)
func ExampleDeque() {
// list.New()は双方向の連結リストを生成する→dequeとして利用できる
deque := list.New()
// 先頭に要素を追加する
deque.PushFront(-5) // [-5]
deque.PushFront(10) // [10, -5]
// 先頭の要素を取得する
// Valueはinterface型なので,型を意識した操作 (構造体の属性へのアクセス等) を
// したい場合にはキャストする必要がある
fmt.Println(deque.Front().Value) // 10
// 先頭の要素を削除する
// Goの実装ではPopFrontは存在しないため,
// 先頭要素へのポインタをRemoveの引数として与える必要がある
deque.Remove(deque.Front()) // [-5]
// 末尾に要素を追加する
deque.PushBack(3) // [-5, 3]
deque.PushBack(-1) // [-5, 3, -1]
// 末尾の要素を取得する
fmt.Println(deque.Back().Value) // -1
// 末尾の要素を削除する
// Goの実装ではPopBackは存在しないため,
// 末尾要素へのポインタをRemoveの引数として与える必要がある
deque.Remove(deque.Back()) // [-5, -3]
// Removeは削除する要素の値を返却するので,要素の取得と削除を一括で行うこともできる
fmt.Println(deque.Remove(deque.Back())) // -3 ; [-5]
// 特定要素の前後に要素を追加することもできる
// 末尾の要素の1つ手前に新しい要素2を追加する
e1 := deque.InsertBefore(2, deque.Back()) // 2 ; [2, -5]
// 新しく追加した要素の後ろに-2を追加する
deque.InsertAfter(-2, e1) // [2, -2, -5]
// 先頭から順に走査したい場合にはNextを利用する
for e := deque.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value) // [2, -2, -5]
}
// 末尾から順に走査したい場合にはPrevを利用する
for e := deque.Back(); e != nil; e = e.Prev() {
fmt.Println(e.Value) // [-5, -2, 2]
}
// dequeの要素が無くなるまで処理をしたいときはLenで判定できる
for deque.Len() > 0 {
fmt.Println(deque.Remove(deque.Front())) // [2, -2, -5]
}
// Output:
// 10
// -1
// 3
// 2
// -2
// -5
// -5
// -2
// 2
// 2
// -2
// -5
}
|
package main
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
// Book Struct (Model)
type Book struct {
ID string `json:"id"`
Isbn string `json:"isbn"`
Title string `json:"title"`
Author *Author `json:"author"`
}
// Author Struct (Model)
type Author struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
var books []Book
func getBooks(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Content-Type", "application/json")
json.NewEncoder(resp).Encode(books)
}
func getBook(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Content-Type", "application/json")
params := mux.Vars(req)
for _, item := range books {
if item.ID == params["id"] {
json.NewEncoder(resp).Encode(item)
return
}
}
json.NewEncoder(resp).Encode(&Book{})
}
func createBook(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Content-Type", "application/json")
var book Book
_ = json.NewDecoder(req.Body).Decode(&book)
book.ID = strconv.Itoa(rand.Intn(10000000))
books = append(books, book)
json.NewEncoder(resp).Encode(books)
}
func updateBook(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Content-Type", "application/json")
params := mux.Vars(req)
for _, item := range books {
if item.ID == params["id"] {
json.NewEncoder(resp).Encode(item)
return
}
}
json.NewEncoder(resp).Encode(&Book{})
}
func deleteBook(resp http.ResponseWriter, req *http.Request) {
resp.Header().Set("Content-Type", "application/json")
params := mux.Vars(req)
for _, item := range books {
if item.ID == params["id"] {
json.NewEncoder(resp).Encode(item)
return
}
}
json.NewEncoder(resp).Encode(&Book{})
}
func main() {
//Init Router
router := mux.NewRouter()
books = append(books, Book{ID: "1", Isbn: "12345", Title: "Risalah Cinta",
Author: &Author{FirstName: "Riyansyah", LastName: "Iqbal"}})
books = append(books, Book{ID: "2", Isbn: "12346", Title: "Risalah Hati",
Author: &Author{FirstName: "Riyansyah", LastName: "Iqbal"}})
books = append(books, Book{ID: "3", Isbn: "12347", Title: "Risalah Jiwa",
Author: &Author{FirstName: "Riyansyah", LastName: "Iqbal"}})
router.HandleFunc("/api/books", getBooks).Methods(http.MethodGet)
router.HandleFunc("/api/books/{id}", getBook).Methods(http.MethodGet)
router.HandleFunc("/api/books", createBook).Methods(http.MethodPost)
router.HandleFunc("/api/books/{id}", deleteBook).Methods(http.MethodDelete)
log.Fatal(http.ListenAndServe(":8000", router))
}
|
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package api
// Batch is the interface that wraps the basic Batch method.
//
// GetSourceOffset returns the initial offset of the current batch.
// This return value should be treated as an opaque value as it is source dependent.
//
// GetRecords returns an iterator with all the records in the batch for the current stage.
// Every time this method is called it returns a new iterator with all records in the batch.
type Batch interface {
GetSourceOffset() string
GetRecords() []Record
}
|
package rest
type webHandler struct {
res *Resource
}
func newWebHandler(configFile string) *webHandler {
res, _ := LoadResourceFile(configFile)
return &webHandler{
res: res,
}
}
|
package metrics
import (
"os/exec"
)
const REBOOT_CMD = "/system/bin/reboot"
func (tcp *TcpStats) performReboot() {
cmd := exec.Command(REBOOT_CMD)
cmd.Start()
}
|
// test is an example package containing the most basic
// tests possible.
package presentation
import (
"testing"
)
// Double doubles the provided value
func Double(n int) int {
return n * 2
}
// Fibonacci will what you'd think
func Fibonacci(n int) int {
if n < 2 {
return n
}
return Fibonacci(n-1) + Fibonacci(n-2)
}
// TestDouble verifies that Double returns 2 * n
func TestDouble(t *testing.T) {
if Double(2) != 4 {
t.Error("Double is not doubling...")
}
if Double(3) == 5 {
t.Error("ERROR: 3 doubled doens't equal 5")
}
}
// BenchmarkFibonacci will provide benchmark statistics for
// the Fibonacci function
func BenchmarkFibonacci(b *testing.B) {
for n := 0; n < b.N; n++ {
Fibonacci(10)
}
}
|
package msg
import (
"server/msg/protocolfile"
"github.com/name5566/leaf/network"
"github.com/name5566/leaf/network/json"
)
var Processorbak network.Processor
// 使用默认的 JSON 消息处理器(默认还提供了 protobuf 消息处理器)
var Processor = json.NewProcessor()
func init() {
Processor.Register(&Protocol.UserLogin{})
}
// 一个结构体定义了一个 JSON 消息的格式
// 消息名为 Test
type Test struct {
Name string
}
// 用户登陆的协议
type UserLogin struct {
LoginName string
LoginPW string
}
|
package main
import (
"bytes"
"fmt"
)
func main(){
var slice1 [4]int
slice1 = [...]int{1,2,3,0} // `...` -> denote as: origin of any value
var slice2 [4]int
fmt.Printf("%p\n",&slice1)
fmt.Printf("%p\n",&slice1)
alamat := &slice1
var thisCompareByValue bool = (slice1 == slice2)
var thisCompareByRefrence bool = (&slice1 == &slice2)
fmt.Println(thisCompareByValue)
fmt.Println(thisCompareByRefrence)
fmt.Printf("%T\n",alamat)
// array diatas terlihat kurang fleksibel; dan golang jarang menggunakannya
// sebagai gantinya golang menyediakan slices
// pendeklarasian mirip array, hanya saja tanpa length `[length]` eksplisit
letters := []string{"a", "b", "c", "d"}
fmt.Println(letters)
// dengan fungsi make() juga dapat digunakan untuk membuat slice
// func make([]T, len, cap) []T {}
//var s []byte
//s = make([]byte, 5, 10)
// s == []byte{0, 0, 0, 0, 0}
//s[0] = 100
s := make([]int, 1, 13)
fmt.Printf("%v\n",cap(s))
for i := 0; i < 10; i++ {
s = append(s, i)
fmt.Printf("cap %v, len %v, %v\n", cap(s), len(s), s)
}
b := []byte{'g', 'o', 'l', 'a', 'n', 'g'}
is_same := bytes.Compare([]byte{'g','o'}, b[0:1])
fmt.Println(is_same)
cek_byte0 := &[]byte{'g'}
cek_byte1 := &[]byte{'g'}
fmt.Printf("%v -> %p\n\n",string(b),&b)
fmt.Printf("compare ptr origin:\n byte0= %p byte1= %p\n\n",cek_byte0, cek_byte1)
fmt.Printf("compare ptr var :\n %p <--> %p\n\n",cek_byte1, &cek_byte1)
// FUN FACT!!!! :V
// Slicing does not copy the slice's data.
// It creates a new slice value that points to the original array.
// This makes slice operations as efficient as manipulating array indices.
// Therefore, modifying the elements (not the slice itself)
// of a re-slice modifies the elements of the original slice:
d := []byte{'r', 'o', 'a', 'd'}
e := d[2:] // e == []byte{'a', 'd'}
e[1] = 'm' // e == []byte{'a', 'm'}
// d == []byte{'r', 'o', 'a', 'm'}
}
|
package irc
import "awesome-dragon.science/go/goGoGameBot/pkg/event"
func (i *IRC) handleNickInUse(e event.Event) {
rawEvent := event2RawEvent(e)
if rawEvent == nil {
i.log.Warn("Got an invalid 433 event")
return
}
newNick := rawEvent.Line.Params[1] + "_"
if _, err := i.writeLine("NICK", newNick); err != nil {
i.log.Warnf("Error while updating nick")
}
// TODO: add a goroutine here that tries to regain our original nick if its in use
i.runtimeNick = newNick
}
func (i *IRC) onNick(source, newNick string) {
oldNick := i.HumanReadableSource(source)
if oldNick != i.runtimeNick {
return
}
i.runtimeNick = newNick
}
|
package common
import (
"net/url"
)
// Client ecapsulates client details
type Client interface {
// URL returns a URL; unless there was a problem parsing it, in which case
// it returns an error
URL() (*url.URL, error)
// APIKey returns the API Key you are using, or an error if it is missing
APIKey() (string, error)
// Valid ensures URL() and APIKey return no errors
Valid() bool
// Request takes a method, an endpoint, and a map of additional options in
// order to use the API
Request(string, string, map[string]interface{}) ([]byte, error)
}
|
addressSvc := svc.AddressSvc{store.AddressStore{cruder, lister}}
brandSvc := svc.BrandSvc{store.BrandStore{cruder, lister, beginer}}
categorySvc := svc.CategorySvc{store.CategoryStore{cruder, lister, beginer}}
companySvc := svc.CompanySvc{store.CompanyStore{cruder, lister, beginer}}
feedbackSvc := svc.FeedbackSvc{store.FeedbackStore{cruder, lister}}
imageSvc := svc.ImageSvc{store.ImageStore{conf, queryer}}
invoiceSvc := svc.InvoiceSvc{store.InvoiceStore{cruder, queryer, beginer, lister}}
contentSvc := svc.ContentSvc{store.ContentStore{cruder, lister, beginer}}
|
package chapter10
import (
"fmt"
"testing"
)
func TestMergeSortedArrays(t *testing.T) {
arrs := [][]int{
{24, 45, 49},
{12, 59, 87},
{44, 99},
}
result := MergeSortedArrays(arrs)
fmt.Println(result)
fmt.Println()
}
|
package httpd
import (
. "gopkg.in/check.v1"
"testing"
)
// test framework tie-in /////////////////////
func Test(t *testing.T) { TestingT(t) }
type XLSuite struct{}
var _ = Suite(&XLSuite{})
// end test framework setup //////////////////
|
// This file was generated for SObject FeedTrackedChange, API Version v43.0 at 2018-07-30 03:47:33.895560215 -0400 EDT m=+20.238926072
package sobjects
import (
"fmt"
"strings"
)
type FeedTrackedChange struct {
BaseSObject
FeedItemId string `force:",omitempty"`
FieldName string `force:",omitempty"`
Id string `force:",omitempty"`
NewValue string `force:",omitempty"`
OldValue string `force:",omitempty"`
}
func (t *FeedTrackedChange) ApiName() string {
return "FeedTrackedChange"
}
func (t *FeedTrackedChange) String() string {
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("FeedTrackedChange #%s - %s\n", t.Id, t.Name))
builder.WriteString(fmt.Sprintf("\tFeedItemId: %v\n", t.FeedItemId))
builder.WriteString(fmt.Sprintf("\tFieldName: %v\n", t.FieldName))
builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id))
builder.WriteString(fmt.Sprintf("\tNewValue: %v\n", t.NewValue))
builder.WriteString(fmt.Sprintf("\tOldValue: %v\n", t.OldValue))
return builder.String()
}
type FeedTrackedChangeQueryResponse struct {
BaseQuery
Records []FeedTrackedChange `json:"Records" force:"records"`
}
|
package lineartable
import (
"bytes"
"fmt"
)
// SortedArrayInterface 有序数组 接口
type SortedArrayInterface interface {
Add(int64)
Remove(int64)
Find(int64) int
}
// NewSortedArray 创建新的有序数组
func NewSortedArray(cap int) *SortedArray {
return &SortedArray{
data: make([]int64, cap, cap),
cap: cap,
len: 0,
}
}
// SortedArray 有序数组
type SortedArray struct {
data []int64
cap int
len int
}
// Add 增加元素
func (a *SortedArray) Add(v int64) {
if a.len == a.cap {
panic("array is full!")
}
insertI := a.len
for i := a.len; i > 0; i-- {
if a.data[i-1] <= v {
break
}
a.data[i] = a.data[i-1]
insertI = i - 1
}
a.data[insertI] = v
a.len++
}
// Find 查找元素
func (a *SortedArray) Find(v int64) int {
for i := 0; i < a.len; i++ {
if v == a.data[i] {
return i
}
}
return -1
}
// Remove 删除元素
func (a *SortedArray) Remove(v int64) {
removeI := a.Find(v)
if removeI != -1 {
for i := removeI; i < a.len-1; i++ {
a.data[i] = a.data[i+1]
}
a.len--
}
}
func (a *SortedArray) String() string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("SortedArray: length = %d, capacity = %d, ", a.len, a.cap))
buffer.WriteString("data = [")
for i := 0; i < a.len; i++ {
buffer.WriteString(fmt.Sprint(a.data[i]))
if i < a.len-1 {
buffer.WriteString(",")
}
}
buffer.WriteString("]")
return buffer.String()
}
|
package concat
import (
"fmt"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/grafana/loki/pkg/promtail/api"
"github.com/prometheus/common/model"
"regexp"
"sync"
"time"
)
type Config struct {
// Empty string results in disabling
MultilineStartRegexpString string `yaml:"multiline_start_regexp`
// 0 for wait forever, else duration in seconds
Timeout time.Duration `yaml:"flush_timeout"`
}
type logEntry struct {
labels model.LabelSet
time time.Time
line string
mutex sync.Mutex
}
type Concat struct {
next api.EntryHandler
logger log.Logger
multilineStartRegexp *regexp.Regexp
cfg Config
bufferMutex sync.Mutex
// Map of filename to log entry
buffer map[string]*logEntry
quit chan struct{}
wg sync.WaitGroup
}
func New(logger log.Logger, next api.EntryHandler, cfg Config) (*Concat, error) {
multilineStartRegexp, err := regexp.Compile(cfg.MultilineStartRegexpString)
if err != nil {
return nil, err
}
c := &Concat {
next: next,
logger: logger,
multilineStartRegexp: multilineStartRegexp,
cfg: cfg,
bufferMutex: sync.Mutex{},
buffer: map[string]*logEntry{},
quit: make(chan struct{}),
}
c.wg.Add(1)
return c, nil
}
// Handle implement EntryHandler
func (c *Concat) Handle(labels model.LabelSet, t time.Time, line string) error {
// Disabled concat if regex is empty
if c.cfg.MultilineStartRegexpString == "" {
return c.next.Handle(labels, t, line)
}
filenameLabel, ok := labels[api.FilenameLabel]
if !ok {
return fmt.Errorf("unable to find %s label in message", api.FilenameLabel)
}
filename := string(filenameLabel)
c.bufferMutex.Lock()
existingMessage, messageExists := c.buffer[filename]
shouldFlush := c.multilineStartRegexp.MatchString(line)
if !shouldFlush && !messageExists {
level.Warn(c.logger).Log("msg", "encountered non-multiline-starting line in empty buffer, indicates tailer started in middle of multiline entry", "file", filename)
}
// If the buffer exists and we shouldn't flush, we should append to the existing buffer
if messageExists && !shouldFlush {
c.buffer[filename].line += "\n" + line
} else {
c.buffer[filename] = &logEntry {
labels: labels,
time: t,
line: line,
}
}
// At this point, we're okay to unlock the mutex.
c.bufferMutex.Unlock()
// Flush the old entry if necessary
if shouldFlush && messageExists {
return c.next.Handle(existingMessage.labels, existingMessage.time, existingMessage.line)
}
return nil
}
func (c *Concat) flushLoop(forceFlush bool) {
c.bufferMutex.Lock()
for filename, logEntry := range c.buffer {
// Check whether the log entry should be force-flushed
if forceFlush || time.Now().Sub(logEntry.time) > c.cfg.Timeout {
c.next.Handle(logEntry.labels, logEntry.time, logEntry.line)
}
delete(c.buffer, filename)
}
c.bufferMutex.Unlock()
}
func (c *Concat) Run() {
defer func() {
c.flushLoop(true)
c.wg.Done()
}()
// Set up timer loop to poll buffer every second
timer := time.NewTicker(1*time.Second)
for {
select {
case <-timer.C:
c.flushLoop(false)
case <-c.quit:
return
}
}
}
func (c *Concat) Stop() {
close(c.quit)
c.wg.Wait()
}
|
package keeper
import (
"testing"
"github.com/irisnet/irishub/app/v1/auth"
"github.com/irisnet/irishub/app/v2/htlc/internal/types"
sdk "github.com/irisnet/irishub/types"
"github.com/stretchr/testify/require"
)
func TestKeeper_CreateHTLC(t *testing.T) {
ctx, keeper, ak, accs := createTestInput(t, sdk.NewInt(5000000000), 2)
senderAddr := accs[0].GetAddress().Bytes()
receiverAddr := accs[1].GetAddress().Bytes()
receiverOnOtherChain := "receiverOnOtherChain"
amount := sdk.NewCoins(sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(10)))
secret := []byte("___abcdefghijklmnopqrstuvwxyz___")
timestamp := uint64(1580000000)
hashLock := sdk.SHA256(append(secret, sdk.Uint64ToBigEndian(timestamp)...))
timeLock := uint64(50)
expireHeight := timeLock + uint64(ctx.BlockHeight())
state := types.OPEN
initSecret := make([]byte, 0)
_, err := keeper.GetHTLC(ctx, hashLock)
require.NotNil(t, err)
htlc := types.NewHTLC(
senderAddr,
receiverAddr,
receiverOnOtherChain,
amount,
initSecret,
timestamp,
expireHeight,
state,
)
originSenderAccAmt := ak.GetAccount(ctx, senderAddr).GetCoins()
htlcAddr := auth.HTLCLockedCoinsAccAddr
require.Nil(t, ak.GetAccount(ctx, htlcAddr))
_, err = keeper.CreateHTLC(ctx, htlc, hashLock)
require.Nil(t, err)
htlcAcc := ak.GetAccount(ctx, htlcAddr)
require.NotNil(t, htlcAcc)
amountCreatedHTLC := ak.GetAccount(ctx, htlcAddr).GetCoins()
require.True(t, amount.IsEqual(amountCreatedHTLC))
finalSenderAccAmt := ak.GetAccount(ctx, senderAddr).GetCoins()
require.True(t, originSenderAccAmt.Sub(amount).IsEqual(finalSenderAccAmt))
htlc, err = keeper.GetHTLC(ctx, hashLock)
require.Nil(t, err)
require.Equal(t, accs[0].GetAddress(), htlc.Sender)
require.Equal(t, accs[1].GetAddress(), htlc.To)
require.Equal(t, receiverOnOtherChain, htlc.ReceiverOnOtherChain)
require.Equal(t, amount, htlc.Amount)
require.Equal(t, []byte(nil), htlc.Secret)
require.Equal(t, timestamp, htlc.Timestamp)
require.Equal(t, expireHeight, htlc.ExpireHeight)
require.Equal(t, state, htlc.State)
store := ctx.KVStore(keeper.storeKey)
require.True(t, store.Has(KeyHTLCExpireQueue(htlc.ExpireHeight, hashLock)))
}
func newHashLock(secret []byte, timestamp uint64) []byte {
if timestamp > 0 {
return sdk.SHA256(append(secret, sdk.Uint64ToBigEndian(timestamp)...))
}
return sdk.SHA256(secret)
}
func TestKeeper_ClaimHTLC(t *testing.T) {
ctx, keeper, ak, accs := createTestInput(t, sdk.NewInt(5000000000), 2)
senderAddr := accs[0].GetAddress().Bytes()
receiverAddr := accs[1].GetAddress().Bytes()
receiverOnOtherChain := "receiverOnOtherChain"
amount := sdk.NewCoins(sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(10)))
secret1 := []byte("___abcdefghijklmnopqrstuvwxyz___")
secret2 := []byte("___00000000000000000000000000___")
timestamp := uint64(1580000000)
timestampNil := uint64(0)
timeLock := uint64(50)
expireHeight := timeLock + uint64(ctx.BlockHeight())
state := types.OPEN
initSecret := make([]byte, 0)
testData := []struct {
expectPass bool
senderAddr []byte
toAddr []byte
receiverOnOtherChain string
amount sdk.Coins
secret []byte
timestamp uint64
hashLock []byte
timeLock uint64
expireHeight uint64
state types.HTLCState
initSecret []byte
}{
// timestamp > 0
{true, senderAddr, receiverAddr, receiverOnOtherChain, amount, secret1, timestamp, newHashLock(secret1, timestamp), timeLock, expireHeight, state, initSecret},
// timestamp = 0
{true, senderAddr, receiverAddr, receiverOnOtherChain, amount, secret1, timestampNil, newHashLock(secret1, timestampNil), timeLock, expireHeight, state, initSecret},
// invalid secret
{false, senderAddr, receiverAddr, receiverOnOtherChain, amount, secret1, timestampNil, newHashLock(secret2, timestampNil), timeLock, expireHeight, state, initSecret},
}
for i, td := range testData {
if td.expectPass {
htlc := types.NewHTLC(
td.senderAddr,
td.toAddr,
td.receiverOnOtherChain,
td.amount,
td.initSecret,
td.timestamp,
td.expireHeight,
td.state,
)
_, err := keeper.CreateHTLC(ctx, htlc, td.hashLock)
require.Nil(t, err, "TestData: %d", i)
htlc, err = keeper.GetHTLC(ctx, td.hashLock)
require.Nil(t, err, "TestData: %d", i)
require.Equal(t, types.OPEN, htlc.State, "TestData: %d", i)
htlcAddr := auth.HTLCLockedCoinsAccAddr
originHTLCAmount := ak.GetAccount(ctx, htlcAddr).GetCoins()
originReceiverAmount := ak.GetAccount(ctx, receiverAddr).GetCoins()
_, err = keeper.ClaimHTLC(ctx, td.hashLock, td.secret)
require.Nil(t, err, "TestData: %d", i)
htlc, _ = keeper.GetHTLC(ctx, td.hashLock)
require.Equal(t, types.COMPLETED, htlc.State, "TestData: %d", i)
store := ctx.KVStore(keeper.storeKey)
require.True(t, !store.Has(KeyHTLCExpireQueue(htlc.ExpireHeight, td.hashLock)))
claimedHTLCAmount := ak.GetAccount(ctx, htlcAddr).GetCoins()
claimedReceiverAmount := ak.GetAccount(ctx, receiverAddr).GetCoins()
require.True(t, originHTLCAmount.Sub(amount).IsEqual(claimedHTLCAmount), "TestData: %d", i)
require.True(t, originReceiverAmount.Add(amount).IsEqual(claimedReceiverAmount), "TestData: %d", i)
} else {
htlc := types.NewHTLC(
td.senderAddr,
td.toAddr,
td.receiverOnOtherChain,
td.amount,
td.initSecret,
td.timestamp,
td.expireHeight,
td.state,
)
_, err := keeper.CreateHTLC(ctx, htlc, td.hashLock)
require.Nil(t, err, "TestData: %d", i)
htlc, err = keeper.GetHTLC(ctx, td.hashLock)
require.Nil(t, err, "TestData: %d", i)
require.Equal(t, types.OPEN, htlc.State, "TestData: %d", i)
htlcAddr := auth.HTLCLockedCoinsAccAddr
originHTLCAmount := ak.GetAccount(ctx, htlcAddr).GetCoins()
originReceiverAmount := ak.GetAccount(ctx, receiverAddr).GetCoins()
_, err = keeper.ClaimHTLC(ctx, td.hashLock, td.secret)
require.NotNil(t, err, "TestData: %d", i)
htlc, _ = keeper.GetHTLC(ctx, td.hashLock)
require.Equal(t, types.OPEN, htlc.State, "TestData: %d", i)
claimedHTLCAmount := ak.GetAccount(ctx, htlcAddr).GetCoins()
claimedReceiverAmount := ak.GetAccount(ctx, receiverAddr).GetCoins()
require.True(t, originHTLCAmount.IsEqual(claimedHTLCAmount), "TestData: %d", i)
require.True(t, originReceiverAmount.IsEqual(claimedReceiverAmount), "TestData: %d", i)
}
}
}
func TestKeeper_RefundHTLC(t *testing.T) {
ctx, keeper, ak, accs := createTestInput(t, sdk.NewInt(5000000000), 2)
senderAddr := accs[0].GetAddress().Bytes()
receiverAddr := accs[1].GetAddress().Bytes()
receiverOnOtherChain := "receiverOnOtherChain"
amount := sdk.NewCoins(sdk.NewCoin(sdk.IrisAtto, sdk.NewInt(10)))
timestamp := uint64(1580000000)
secret := []byte("___abcdefghijklmnopqrstuvwxyz___")
hashLock := sdk.SHA256(append(secret, sdk.Uint64ToBigEndian(timestamp)...))
timeLock := uint64(50)
expireHeight := timeLock + uint64(ctx.BlockHeight())
state := types.EXPIRED
initSecret := make([]byte, 0)
htlc := types.NewHTLC(
senderAddr,
receiverAddr,
receiverOnOtherChain,
amount,
initSecret,
timestamp,
expireHeight,
state,
)
_, err := keeper.CreateHTLC(ctx, htlc, hashLock)
require.Nil(t, err)
htlc, err = keeper.GetHTLC(ctx, hashLock)
require.Nil(t, err)
require.Equal(t, types.EXPIRED, htlc.State)
htlcAddr := auth.HTLCLockedCoinsAccAddr
originHTLCAmount := ak.GetAccount(ctx, htlcAddr).GetCoins()
originSenderAmount := ak.GetAccount(ctx, senderAddr).GetCoins()
_, err = keeper.RefundHTLC(ctx, hashLock)
require.Nil(t, err)
htlc, _ = keeper.GetHTLC(ctx, hashLock)
require.Equal(t, types.REFUNDED, htlc.State)
claimedHTLCAmount := ak.GetAccount(ctx, htlcAddr).GetCoins()
claimedSenderAmount := ak.GetAccount(ctx, senderAddr).GetCoins()
require.True(t, originHTLCAmount.Sub(amount).IsEqual(claimedHTLCAmount))
require.True(t, originSenderAmount.Add(amount).IsEqual(claimedSenderAmount))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.