text
stringlengths
11
4.05M
package gonbt import ( "errors" ) // TagType values const ( TagEnd byte = iota TagByte TagShort TagInt TagLong TagFloat TagDouble TagByteArray TagString TagList TagCompound TagIntArray TagLongArray ) // Tag interface to provide a nbt reader / writer type Tag interface { Read(reader Reader) error Write(writer Writer, printInfo bool) error } // NewTag instance func NewTag(tagT byte, name string) (Tag, error) { switch tagT { case TagEnd: return nil, errors.New(errorEnd) case TagByte: return &ByteT{Name: name}, nil case TagShort: return &ShortT{Name: name}, nil case TagInt: return &IntT{Name: name}, nil case TagLong: return &LongT{Name: name}, nil case TagFloat: return &FloatT{Name: name}, nil case TagDouble: return &DoubleT{Name: name}, nil case TagByteArray: return &ByteArrayT{Name: name}, nil case TagString: return &StringT{Name: name}, nil case TagList: return &ListT{Name: name}, nil case TagCompound: return &CompoundT{Name: name}, nil case TagIntArray: return &IntArrayT{Name: name}, nil case TagLongArray: return &LongArrayT{Name: name}, nil default: return nil, errors.New(errorTag) } } // TagType return the tag type from the Tag parameter func TagType(tag Tag) (byte, error) { switch tag.(type) { case *ByteT: return TagByte, nil case *ShortT: return TagShort, nil case *IntT: return TagInt, nil case *LongT: return TagLong, nil case *FloatT: return TagFloat, nil case *DoubleT: return TagDouble, nil case *ByteArrayT: return TagByteArray, nil case *StringT: return TagString, nil case *ListT: return TagList, nil case *CompoundT: return TagCompound, nil case *IntArrayT: return TagIntArray, nil case *LongArrayT: return TagLongArray, nil default: return byte('0'), errors.New(errorTag) } } // EndT to end type: 0 type EndT int // ByteT to byte type: 1 type ByteT struct { Name string Value byte } // ShortT to short type: 2 type ShortT struct { Name string Value int16 } // IntT to int type: 3 type IntT struct { Name string Value int32 } // LongT to long type: 4 type LongT struct { Name string Value int64 } // FloatT to float type: 5 type FloatT struct { Name string Value float32 } // DoubleT to double type: 6 type DoubleT struct { Name string Value float64 } // ByteArrayT to byte array type: 7 type ByteArrayT struct { Name string Value []byte } // StringT to string type: 8 type StringT struct { Name string Value string } // ListT to list type: 9 type ListT struct { Name string Value []interface{} } // CompoundT to compound type: 10 type CompoundT struct { Name string Value map[string]interface{} } // IntArrayT to int array type: 11 type IntArrayT struct { Name string Value []int32 } // LongArrayT to long array type: 12 type LongArrayT struct { Name string Value []int64 } // 1 TAG_Byte 1 byte / 8 bits, signed <number>b or <number>B A signed integral type. Sometimes used for booleans. Full range of -(27) to (27 - 1) // (-128 to 127) func (t *ByteT) Read(reader Reader) error { var err error if t.Value, err = reader.Byte(); err != nil { return err } return nil } func (t *ByteT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagByte); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Byte(t.Value); err != nil { return err } return nil } // 2 TAG_Short 2 bytes / 16 bits, signed, big endian <number>s or <number>S A signed integral type. Full range of -(215) to (215 - 1) // (-32,768 to 32,767) func (t *ShortT) Read(reader Reader) error { var err error if t.Value, err = reader.Short(); err != nil { return err } return nil } func (t *ShortT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagShort); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Short(t.Value); err != nil { return err } return nil } // 3 TAG_Int 4 bytes / 32 bits, signed, big endian <number> A signed integral type. Full range of -(231) to (231 - 1) // (-2,147,483,648 to 2,147,483,647) func (t *IntT) Read(reader Reader) error { var err error if t.Value, err = reader.Int(); err != nil { return err } return nil } func (t *IntT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagInt); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Int(t.Value); err != nil { return err } return nil } // 4 TAG_Long 8 bytes / 64 bits, signed, big endian <number>l or <number>L A signed integral type. Full range of -(263) to (263 - 1) // (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) func (t *LongT) Read(reader Reader) error { var err error if t.Value, err = reader.Long(); err != nil { return err } return nil } func (t *LongT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagLong); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Long(t.Value); err != nil { return err } return nil } // 5 TAG_Float 4 bytes / 32 bits, signed, big endian, IEEE 754-2008, binary32 <number>f or <number>F A signed floating point type. Precision varies throughout number line; // See Single-precision floating-point format. Maximum value about 3.4*1038 func (t *FloatT) Read(reader Reader) error { var err error if t.Value, err = reader.Float(); err != nil { return err } return nil } func (t *FloatT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagFloat); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Float(t.Value); err != nil { return err } return nil } // 6 TAG_Double 8 bytes / 64 bits, signed, big endian, IEEE 754-2008, binary64 <decimal number>, <number>d or <number>D A signed floating point type. Precision varies throughout number line; // See Double-precision floating-point format. Maximum value about 1.8*10308 func (t *DoubleT) Read(reader Reader) error { var err error if t.Value, err = reader.Double(); err != nil { return err } return nil } func (t *DoubleT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagDouble); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Double(t.Value); err != nil { return err } return nil } // 7 TAG_Byte_Array TAG_Int's payload size, then size TAG_Byte's payloads. [B;<byte>,<byte>,...] An array of bytes. Maximum number of elements ranges between (231 - 9) and (231 - 1) (2,147,483,639 and 2,147,483,647), depending on the specific JVM. func (t *ByteArrayT) Read(reader Reader) error { var err error if t.Value, err = reader.Bytes(); err != nil { return err } return nil } func (t *ByteArrayT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagByteArray); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Bytes(t.Value); err != nil { return err } return nil } // 8 TAG_String A TAG_Short-like, but instead unsigned[2] payload length, then a UTF-8 string resembled by length bytes. <a-zA-Z0-9 text>, "<text>" (" within needs to be escaped to \"), or '<text>' (' within needs to be escaped to \') A UTF-8 string. It has a size, rather than being null terminated. 65,535 bytes interpretable as UTF-8 (see modified UTF-8 format; most commonly-used characters are a single byte). func (t *StringT) Read(reader Reader) error { var err error if t.Value, err = reader.String(); err != nil { return err } return nil } func (t *StringT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagString); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.String(t.Value); err != nil { return err } return nil } // 9 TAG_List TAG_Byte's payload tagId, then TAG_Int's payload size, then size tags' payloads, all of type tagId. [<value>,<value>,...] A list of tag payloads, without repeated tag IDs or any tag names. Due to JVM limitations and the implementation of ArrayList, the maximum number of list elements is (231 - 9), or 2,147,483,639. Also note that List and Compound tags may not be nested beyond a depth of 512. func (t *ListT) Read(reader Reader) error { var err error var tagT byte var nbr int32 // get the the tagType if tagT, err = reader.Byte(); err != nil { return err } // get number element if nbr, err = reader.Int(); err != nil { return err } for i := int32(0); i < nbr; i++ { var elem Tag if elem, err = NewTag(tagT, ""); err != nil { return err } if err = elem.Read(reader); err != nil { return err } t.Value = append(t.Value, elem) } return nil } func (t *ListT) Write(writer Writer, printInfo bool) error { var err error var tagT byte var nbr int32 if printInfo { if err = writer.Byte(TagList); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } nbr = int32(len(t.Value)) if nbr > 0 { if _, ok := t.Value[0].(Tag); !ok { return errors.New(errorTag) } if tagT, err = TagType(t.Value[0].(Tag)); err != nil { return err } } if err = writer.Byte(tagT); err != nil { return err } if err = writer.Int(nbr); err != nil { return err } for _, t := range t.Value { if err = t.(Tag).Write(writer, false); err != nil { return err } } return nil } // 10 TAG_Compound Fully formed tags, followed by a TAG_End. {<tag name>:<value>,<tag name>:<value>,...} A list of fully formed tags, including their IDs, names, and payloads. No two tags may have the same name. Unlike lists, there is no hard limit to the number of tags within a Compound (of course, there is always the implicit limit of virtual memory). Note, however, that Compound and List tags may not be nested beyond a depth of 512. func (t *CompoundT) Read(reader Reader) error { var err error var tagT byte var name string t.Value = make(map[string]interface{}) for tagT, err = reader.Byte(); tagT != TagEnd && err == nil; tagT, err = reader.Byte() { if name, err = reader.String(); err != nil { return err } var elem Tag if elem, err = NewTag(tagT, name); err != nil { return err } if err = elem.Read(reader); err != nil { return err } t.Value[name] = elem } if err != nil { return err } return nil } func (t *CompoundT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagCompound); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } for key, value := range t.Value { var tagT byte if _, ok := value.(Tag); !ok { return errors.New(errorTag) } if tagT, err = TagType(value.(Tag)); err != nil { return err } if err = writer.Byte(tagT); err != nil { return err } if err = writer.String(key); err != nil { return err } if err = value.(Tag).Write(writer, false); err != nil { return err } } if err = writer.Byte(TagEnd); err != nil { return err } return nil } // 11 TAG_Int_Array TAG_Int's payload size, then size TAG_Int's payloads. [I;<integer>,<integer>,...] An array of TAG_Int's payloads. Maximum number of elements ranges between (231 - 9) and (231 - 1) (2,147,483,639 and 2,147,483,647), depending on the specific JVM. func (t *IntArrayT) Read(reader Reader) error { var err error if t.Value, err = reader.IntArray(); err != nil { return err } return nil } func (t *IntArrayT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagIntArray); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Int(int32(len(t.Value))); err != nil { return err } for _, v := range t.Value { if err = writer.Int(v); err != nil { return err } } return nil } // 12 TAG_Long_Array TAG_ func (t *LongArrayT) Read(reader Reader) error { var err error if t.Value, err = reader.LongArray(); err != nil { return err } return nil } func (t *LongArrayT) Write(writer Writer, printInfo bool) error { var err error if printInfo { if err = writer.Byte(TagLongArray); err != nil { return err } if err = writer.String(t.Name); err != nil { return err } } if err = writer.Long(int64(len(t.Value))); err != nil { return err } for _, v := range t.Value { if err = writer.Long(v); err != nil { return err } } return nil }
package 二分 import "math/rand" func smallestK(arr []int, k int) []int { makeKthSmallToRightPlace(arr,k) return arr[:k] } func makeKthSmallToRightPlace(nums []int, KthSmall int) { l, r := 0, len(nums)-1 for l <= r { index := randomPartition(nums, l, r) XthSmall := index+1 if XthSmall == KthSmall { return } if XthSmall > KthSmall { r = index - 1 } else { l = index + 1 } } } func makeKthBigToRightPlace(nums []int, KthBig int) { makeKthSmallToRightPlace(nums, len(nums)-KthBig+1) } func randomPartition(nums []int, l int, r int) int { upsetArrayRandomly(nums,l,r) return partition(nums,l,r) } func upsetArrayRandomly(nums []int, l int, r int) { randomIndex := rand.Intn(r-l+1) + l nums[randomIndex], nums[l] = nums[l], nums[randomIndex] } func partition(nums []int, l int, r int) int { guardIndex := l for l <= r { for l <= r && nums[l] <= nums[guardIndex] { l++ } for l <= r && nums[r] >= nums[guardIndex] { r-- } if l <= r { nums[l], nums[r] = nums[r], nums[l] } } nums[guardIndex], nums[r] = nums[r], nums[guardIndex] return r } /* 题目链接: https://leetcode-cn.com/problems/smallest-k-lcci/submissions/ */
package service import ( "backend/src/cache" "backend/src/constants" "backend/src/global" "backend/src/module" "backend/src/repository" "backend/src/utils" "errors" "gopkg.in/ldap.v2" "log" "reflect" "strings" "time" ) const ( // 默认密码 DefaultPassword string = "123456" // 登录token长度 LoginTokenLength int = 20 ) // 登录 func Login(loginUser module.UserVo) ResponseBody { dbUser := module.GetUser(loginUser.UserName) if reflect.DeepEqual(dbUser, module.User{}) { return NewCustomErrorResponseBody("用户名不存在") } if dbUser.State == constants.UserStateDisable { return NewCustomErrorResponseBody("用户已禁用") } // admin账号登录 if constants.Admin == loginUser.UserName { if dbUser.Password != utils.MD5Encryption(loginUser.Password, dbUser.Salt) { return NewCustomErrorResponseBody("密码不正确") } accessToken, _ := utils.CreateAccessIdToken(dbUser.UserName) refreshToken, _ := utils.CreateRefreshIdToken(dbUser.UserName) cache.Join(*dbUser, loginUser.UserName) return NewSuccessResponseBody(module.LoginResponse{ AccessToken: accessToken, RefreshToken: refreshToken, Privileges: buildMenuTree(loginUser.UserName), UserDto: *dbUser, }) } else { // 其他账号登录 return NewCustomErrorResponseBody("当前项目只能admin用户登录") } } func GetInfo(accessToken string) ResponseBody { mc, err := utils.ParseToken(accessToken) if err != nil { return NewAccessTokenExpireResponseBody() } userName := mc.Username //刷新refreshToken user, hasUser := cache.GetUser(userName) if !hasUser { user = *module.GetUser(user.UserName) } return NewSuccessResponseBody(module.LoginResponse{AccessToken: accessToken, Privileges: buildMenuTree(user.UserName), UserDto: user}) } func RefreshAccessToken(refreshToken string) ResponseBody { mc, err := utils.ParseToken(refreshToken) if err != nil { return NewRefreshTokenExpireResponseBody() } userName := mc.Username // 创建新的accessToken accessToken, err := utils.CreateAccessIdToken(userName) user, hasUser := cache.GetUser(userName) if !hasUser { user = *module.GetUser(user.UserName) } //刷新refreshToken // 判断是否刷新 refreshToken,如果refreshToken 快过期了 需要重新生成一个替换掉 // refreshToken 有效时长是应该为accessToken有效时长的2倍 minTimeOfRefreshToken := time.Duration(global.Config.Jwt.AccessTokenExpirationTime*2) * time.Second now := time.Duration(time.Now().UnixNano()) refreshTokenStartTime, _ := cache.GetStartTime(userName) refreshTokenExpirationTime := time.Duration(global.Config.Jwt.RefreshTokenExpirationTime) * time.Second // (refreshToken上次创建的时间点 + refreshToken的有效时长 - 当前时间点) // 表示refreshToken还剩余的有效时长,如果小于2倍accessToken时长 ,则刷新 refreshToken if (refreshTokenStartTime+refreshTokenExpirationTime)-now <= minTimeOfRefreshToken { cache.Invalid(userName) refreshToken, _ = utils.CreateRefreshIdToken(userName) cache.Join(user, refreshToken) cache.AddInvalidTime(userName) } return NewSuccessResponseBody(module.LoginResponse{AccessToken: accessToken, RefreshToken: refreshToken, Privileges: buildMenuTree(user.UserName), UserDto: user}) } // 登出 func Logout(userName, sessionId string) ResponseBody { dbUser := module.GetUser(userName) if reflect.DeepEqual(dbUser, module.User{}) { return NewCustomErrorResponseBody("用户名不存在") } cache.Invalid(userName) return NewSimpleSuccessResponseBody() } // 禁用账号 func DisableUser(userName string) ResponseBody { dbUser := module.GetUser(userName) if reflect.DeepEqual(dbUser, module.User{}) { return NewCustomErrorResponseBody("用户名不存在") } dbUser.State = constants.UserStateDisable repository.Save(&dbUser) return NewSimpleSuccessResponseBody() } // 启用账号 func EnableUser(userName string) ResponseBody { dbUser := module.GetUser(userName) if reflect.DeepEqual(dbUser, module.User{}) { return NewCustomErrorResponseBody("用户名不存在") } dbUser.State = constants.UserStateEnable repository.Save(&dbUser) return NewSimpleSuccessResponseBody() } // 域账户验证账号密码 func ldapCheckPwd(loginUser module.UserVo) error { domainName := loginUser.UserName if !strings.Contains(domainName, global.Config.Ldap.EmailSuffix) { domainName = domainName + global.Config.Ldap.EmailSuffix } con, e := ldap.Dial("tcp", global.Config.Ldap.Host+":"+global.Config.Ldap.Port) defer con.Close() if e != nil { log.Printf("LDAP dial fail %s", e.Error()) return errors.New("连接域账户失败") } e = con.Bind(domainName, loginUser.Password) if e != nil { log.Printf("LDAP bind fail %s", e.Error()) return errors.New("域账户校验失败") } return nil } // 修改ldap登陆类型的admin账号的密码 func UpdateLdapAdminPassword(param module.UserVo) ResponseBody { if global.Config.System.LoginType != constants.LoginTypeLDAP { return NewCustomErrorResponseBody("只支持修改 ldap登陆类型的 admin的密码") } if param.UserName != constants.Admin { return NewCustomErrorResponseBody("只支持修改 ldap登陆类型的 admin的密码") } if len(param.Password) < 6 || len(param.Password) > 18 { return NewCustomErrorResponseBody("密码长度6到18位") } user := module.GetUser(param.UserName) user.Salt = utils.GetPasswordSalt() user.Password = utils.MD5Encryption(param.Password, user.Salt) repository.Save(&user) return NewSimpleSuccessResponseBody() } func getCheckTokenUrl() string { sso := global.Config.SSO return sso.BaseUrl + sso.CheckTokenUrl } // 是否有这个子账户 func hasSubAccount(parentUserName, userName string) bool { subs := make([]module.User, 0) getSubAccountList(parentUserName, &subs) for _, sub := range subs { if sub.UserName == userName { return true } } return userName == parentUserName } // 获取子账号 func getSubAccountList(userName string, list *[]module.User) { currentLen := len(*list) subAccountList := repository.GetSubAccount(userName) for _, u := range subAccountList { *list = append(*list, u) getSubAccountList(u.UserName, list) } if currentLen == len(*list) { return } }
//import "github.com/solomonooo/mercury" //author : solomonooo //create time : 2016-09-08 package mercury import ( "errors" ) const ( CODE_SUCCESS = iota CODE_INVALID_PARAM CODE_ROUTER_FAILED CODE_INVALID_WORKER CODE_CLIENT_CONN = 100 CODE_CLIENT_READ = 101 CODE_CLIENT_WRITE = 102 CODE_UNKNOWN = 9999 ) var ( ERR_INVALID_PARAM = errors.New("invalid param") ERR_ROUTER_FAILLD = errors.New("request route failed") ERR_INVALID_WORKER = errors.New("invalid worker") ERR_CLIENT_CONN = errors.New("client connect failed") ERR_CLIENT_READ = errors.New("client read failed") ERR_CLIENT_WRITE = errors.New("client write failed") ERR_UNKNOWN = errors.New("unknown error") ) var ( codeList map[error]int32 errList map[int32]error ) func init() { errList = make(map[int32]error) errList[CODE_INVALID_PARAM] = ERR_INVALID_PARAM errList[CODE_ROUTER_FAILED] = ERR_ROUTER_FAILLD errList[CODE_INVALID_WORKER] = ERR_INVALID_WORKER errList[CODE_CLIENT_CONN] = ERR_CLIENT_CONN errList[CODE_CLIENT_READ] = ERR_CLIENT_READ errList[CODE_CLIENT_WRITE] = ERR_CLIENT_WRITE errList[CODE_UNKNOWN] = ERR_UNKNOWN codeList = make(map[error]int32) for k, v := range errList { codeList[v] = k } } func Code2Error(code int32) error { if code == 0 { return nil } if v, ok := errList[code]; ok { return v } return ERR_UNKNOWN } func Error2Code(err error) int32 { if err == nil { return CODE_SUCCESS } if v, ok := codeList[err]; ok { return v } return CODE_UNKNOWN }
package operators import ( "context" "fmt" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" 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" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" operatorsv1 "github.com/operator-framework/api/pkg/operators/v1" "github.com/operator-framework/operator-lifecycle-manager/pkg/controller/operators/decorators" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/testobj" ) var _ = Describe("Operator Controller", func() { var ( ctx context.Context operator *operatorsv1.Operator name types.NamespacedName expectedKey string expectedComponentLabelSelector *metav1.LabelSelector ) BeforeEach(func() { ctx = context.Background() operator = newOperator(genName("ghost-")).Operator name = types.NamespacedName{Name: operator.GetName()} expectedKey = decorators.ComponentLabelKeyPrefix + operator.GetName() expectedComponentLabelSelector = &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{ { Key: expectedKey, Operator: metav1.LabelSelectorOpExists, }, }, } Expect(k8sClient.Create(ctx, operator)).To(Succeed()) }) Describe("operator deletion", func() { var originalUID types.UID JustBeforeEach(func() { originalUID = operator.GetUID() Expect(k8sClient.Delete(ctx, operator)).To(Succeed()) }) Context("with components bearing its label", func() { var ( objs []runtime.Object namespace string ) BeforeEach(func() { namespace = genName("ns-") objs = testobj.WithLabel(expectedKey, "", testobj.WithName(namespace, &corev1.Namespace{}), ) for _, obj := range objs { Expect(k8sClient.Create(ctx, obj.(client.Object))).To(Succeed()) } }) AfterEach(func() { for _, obj := range objs { Expect(k8sClient.Delete(ctx, obj.(client.Object), deleteOpts)).To(Succeed()) } Expect(k8sClient.Delete(ctx, operator, deleteOpts)).To(Succeed()) }) It("should re-create it", func() { // There's a race condition between this test and the controller. By the time, // this function is running, we may be in one of three states. // 1. The original deletion in the test setup has not yet finished, so the original // operator resource still exists. // 2. The operator doesn't exist, and the controller has not yet re-created it. // 3. The operator has already been deleted and re-created. // // To solve this problem, we simply compare the UIDs and expect to eventually see a // a different UID. Eventually(func() (types.UID, error) { err := k8sClient.Get(ctx, name, operator) return operator.GetUID(), err }, timeout, interval).ShouldNot(Equal(originalUID)) }) }) Context("with no components bearing its label", func() { It("should not re-create it", func() { // We expect the operator deletion to eventually complete, and then we // expect the operator to consistently never be found. Eventually(func() bool { return apierrors.IsNotFound(k8sClient.Get(ctx, name, operator)) }, timeout, interval).Should(BeTrue()) Consistently(func() bool { return apierrors.IsNotFound(k8sClient.Get(ctx, name, operator)) }, timeout, interval).Should(BeTrue()) }) }) }) Describe("component selection", func() { BeforeEach(func() { Eventually(func() (*operatorsv1.Components, error) { err := k8sClient.Get(ctx, name, operator) return operator.Status.Components, err }, timeout, interval).ShouldNot(BeNil()) Eventually(func() (*metav1.LabelSelector, error) { err := k8sClient.Get(ctx, name, operator) return operator.Status.Components.LabelSelector, err }, timeout, interval).Should(Equal(expectedComponentLabelSelector)) }) AfterEach(func() { Expect(k8sClient.Delete(ctx, operator, deleteOpts)).To(Succeed()) }) Context("with no components bearing its label", func() { Specify("a status containing no component references", func() { Consistently(func() ([]operatorsv1.RichReference, error) { err := k8sClient.Get(ctx, name, operator) return operator.Status.Components.Refs, err }, timeout, interval).Should(BeEmpty()) }) }) Context("with components bearing its label", func() { var ( objs []runtime.Object expectedRefs []operatorsv1.RichReference namespace string ) BeforeEach(func() { namespace = genName("ns-") objs = testobj.WithLabel(expectedKey, "", testobj.WithName(namespace, &corev1.Namespace{}), ) for _, obj := range objs { Expect(k8sClient.Create(ctx, obj.(client.Object))).To(Succeed()) } expectedRefs = toRefs(scheme, objs...) }) AfterEach(func() { for _, obj := range objs { Expect(k8sClient.Delete(ctx, obj.(client.Object), deleteOpts)).To(Succeed()) } }) Specify("a status containing its component references", func() { Eventually(func() ([]operatorsv1.RichReference, error) { err := k8sClient.Get(ctx, name, operator) return operator.Status.Components.Refs, err }, timeout, interval).Should(ConsistOf(expectedRefs)) }) Context("when new components are labelled", func() { BeforeEach(func() { saName := &types.NamespacedName{Namespace: namespace, Name: genName("sa-")} newObjs := testobj.WithLabel(expectedKey, "", testobj.WithNamespacedName(saName, &corev1.ServiceAccount{}), testobj.WithName(genName("sa-admin-"), &rbacv1.ClusterRoleBinding{ Subjects: []rbacv1.Subject{ { Kind: rbacv1.ServiceAccountKind, Name: saName.Name, Namespace: saName.Namespace, }, }, RoleRef: rbacv1.RoleRef{ APIGroup: rbacv1.GroupName, Kind: "ClusterRole", Name: "cluster-admin", }, }), ) for _, obj := range newObjs { Expect(k8sClient.Create(ctx, obj.(client.Object))).To(Succeed()) } objs = append(objs, newObjs...) expectedRefs = append(expectedRefs, toRefs(scheme, newObjs...)...) }) It("should add the component references", func() { Eventually(func() ([]operatorsv1.RichReference, error) { err := k8sClient.Get(ctx, name, operator) return operator.Status.Components.Refs, err }, timeout, interval).Should(ConsistOf(expectedRefs)) }) }) Context("when multiple types of a gvk are labeled", func() { BeforeEach(func() { newObjs := make([]runtime.Object, 9) // Create objects in reverse order to ensure they are eventually ordered alphabetically in the status of the operator. for i := 8; i >= 0; i-- { newObjs[8-i] = testobj.WithLabels(map[string]string{expectedKey: ""}, testobj.WithNamespacedName( &types.NamespacedName{Namespace: namespace, Name: fmt.Sprintf("sa-%d", i)}, &corev1.ServiceAccount{}, )) } for _, obj := range newObjs { Expect(k8sClient.Create(ctx, obj.(client.Object))).To(Succeed()) } objs = append(objs, newObjs...) expectedRefs = append(expectedRefs, toRefs(scheme, newObjs...)...) }) It("should list each of the component references in alphabetical order by namespace and name", func() { Eventually(func() ([]operatorsv1.RichReference, error) { err := k8sClient.Get(ctx, name, operator) return operator.Status.Components.Refs, err }, timeout, interval).Should(ConsistOf(expectedRefs)) serviceAccountCount := 0 for _, ref := range operator.Status.Components.Refs { if ref.Kind != rbacv1.ServiceAccountKind { continue } Expect(ref.Name).Should(Equal(fmt.Sprintf("sa-%d", serviceAccountCount))) serviceAccountCount++ } Expect(serviceAccountCount).To(Equal(9)) }) }) Context("when component labels are removed", func() { BeforeEach(func() { for _, obj := range testobj.StripLabel(expectedKey, objs...) { Expect(k8sClient.Update(ctx, obj.(client.Object))).To(Succeed()) } }) It("should remove the component references", func() { Eventually(func() ([]operatorsv1.RichReference, error) { err := k8sClient.Get(ctx, name, operator) return operator.Status.Components.Refs, err }, timeout, interval).Should(BeEmpty()) }) }) }) }) })
package main import ( "errors" "io" "log" "os" "os/exec" "os/signal" "path/filepath" "syscall" "time" ) var file string var args []string func main() { if len(os.Args) < 2 { log.Fatal("at least two args are required") } file = os.Args[1] args = os.Args[2:] log.Printf("main file: %s", file) log.Printf("args: %s", args) cmd := run() go scanChanges(".", []string{}, func(path string) { kill(cmd) cmd = run() }) sysStop := make(chan os.Signal, 1) signal.Notify(sysStop, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP) select { case <-sysStop: kill(cmd) } } func build() error { command := exec.Command("go", "build", "-o", "proc", file) output, err := command.CombinedOutput() if !command.ProcessState.Success() { err = errors.New(string(output)) } return err } func run() *exec.Cmd { if err := build(); err != nil { log.Print(err) } cmd := exec.Command("./proc", args...) stdout, err := cmd.StdoutPipe() if err != nil { log.Fatal(err) } stderr, err := cmd.StderrPipe() if err != nil { log.Fatal(err) } if err := cmd.Start(); err != nil { log.Fatal(err) } go io.Copy(os.Stdout, stdout) go io.Copy(os.Stderr, stderr) time.Sleep(250 * time.Millisecond) return cmd } func kill(cmd *exec.Cmd) error { if cmd == nil || cmd.Process == nil { return nil } if err := cmd.Process.Signal(os.Interrupt); err != nil { log.Fatal(err) } if err := cmd.Wait(); err != nil { } return nil } var startTime = time.Now() func scanChanges(watchPath string, excludeDirs []string, callback func(path string)) { for { filepath.Walk(watchPath, func(path string, info os.FileInfo, err error) error { if path == ".git" && info.IsDir() { return filepath.SkipDir } for _, x := range excludeDirs { if x == path { return filepath.SkipDir } } // ignore hidden files if filepath.Base(path)[0] == '.' { return nil } if filepath.Ext(path) == ".go" && info.ModTime().After(startTime) { callback(path) startTime = time.Now() return errors.New("done") } return nil }) time.Sleep(500 * time.Millisecond) } }
package model import ( "database/sql" "github.com/barrydev/api-3h-shop/src/constants" ) type Shipping struct { /** Response Field */ Id *int64 `json:"_id,omitempty"` Carrier *string `json:"carrier,omitempty"` Status *string `json:"status,omitempty"` OrderId *int64 `json:"order_id,omitempty"` CreatedAt *string `json:"created_at,omitempty"` UpdatedAt *string `json:"updated_at,omitempty"` DeliveredAt *string `json:"delivered_at,omitempty"` Note *string `json:"note,omitempty"` Price *float64 `json:"price,omitempty"` /** Database Field */ RawId *int64 `json:"-"` RawCarrier *string `json:"-"` RawStatus *string `json:"-"` RawOrderId *int64 `json:"-"` RawCreatedAt *string `json:"-"` RawUpdatedAt *string `json:"-"` RawDeliveredAt *sql.NullString `json:"-"` RawNote *sql.NullString `json:"-"` RawPrice *float64 `json:"-"` } func (shipping *Shipping) FillResponse() { shipping.Id = shipping.RawId shipping.Carrier = shipping.RawCarrier shipping.Status = shipping.RawStatus shipping.OrderId = shipping.RawOrderId shipping.CreatedAt = shipping.RawCreatedAt shipping.UpdatedAt = shipping.RawUpdatedAt if shipping.RawDeliveredAt != nil { if shipping.RawDeliveredAt.Valid { shipping.DeliveredAt = &shipping.RawDeliveredAt.String } } if shipping.RawNote != nil { if shipping.RawNote.Valid { shipping.Note = &shipping.RawNote.String } } shipping.Price = shipping.RawPrice } type BodyShipping struct { Id *int64 `json:"_id" binding:"omitempty,gt=0"` Carrier *string `json:"carrier" binding:"omitempty"` Status *string `json:"status" binding:"omitempty"` OrderId *int64 `json:"order_id" binding:"omitempty,gt=0"` DeliveredAt *string `json:"delivered_at" binding:"omitempty"` Note *string `json:"note" binding:"omitempty"` Price *float64 `json:"price" binding:"omitempty,gt=0"` } func (body *BodyShipping) Normalize() error { //*body.Name = helpers.SanitizeString(*body.Name) //if body.ParentId != nil && *body.ParentId < 1 { // return errors.New("invalid parent_id") //} return nil } type QueryShipping struct { Id *int64 `form:"id" binding:"omitempty"` Carrier *string `json:"carrier" binding:"omitempty"` Status *string `json:"status" binding:"omitempty"` OrderId *int64 `json:"order_id" binding:"omitempty"` CreatedAtFrom *string `form:"created_at_from" binding:"omitempty,required_with=CreatedAtTo"` CreatedAtTo *string `form:"created_at_to" binding:"omitempty,required_with=CreatedAtFrom"` UpdatedAtFrom *string `form:"updated_at_from" binding:"omitempty,required_with=UpdatedAtTo"` UpdatedAtTo *string `form:"updated_at_to" binding:"omitempty,required_with=UpdatedAtFrom"` DeliveredAtFrom *string `form:"delivered_at_from" binding:"omitempty,required_with=DeliveredTo"` DeliveredAtTo *string `form:"delivered_at_to" binding:"omitempty,required_with=DeliveredFrom"` Page *int `form:"page" binding:"omitempty,gte=0"` Limit *int `form:"limit" binding:"omitempty,gte=0"` Offset *int } func (query *QueryShipping) ParsePaging() { if query.Page == nil { page := constants.DEFAULT_PAGE query.Page = &page } if query.Limit == nil { limit := constants.DEFAULT_LIMIT query.Limit = &limit } skip := (*query.Page - 1) * *query.Limit query.Offset = &skip }
package apiserver import ( "encoding/json" "errors" "fmt" "github.com/bolshagin/xsolla-be-2020/model" "github.com/dgrijalva/jwt-go" "github.com/google/uuid" "net/http" "strings" "time" ) var ( zeroDate = time.Date(1000, 1, 1, 0, 0, 0, 0, time.UTC) sessDuration float64 = 60 * 15 layout = "2006-01-02" secretKey = []byte("secretKey") ) var ( errSessionExpired = errors.New("session expired") errSessionAlreadyClosed = errors.New("session already closed") errTooLongPurpose = errors.New("purpose must be less than 210 symbols") errInvalidCardNum = errors.New("invalid card number") errInvalidCardDate = errors.New("invalid card date") errInvalidCardCode = errors.New("invalid card code") errNotAuthorized = errors.New("not authorized") errNotValidToken = errors.New("not valid jwt-token") errTokenIsExpired = errors.New("jwt-token is expired") errCantHandleToken = errors.New("cant handle jwt-token") ) func (s *APIServer) handleSessionsCreate() http.HandlerFunc { type request struct { Amount float64 `json:"amount"` Purpose string `json:"purpose"` } return func(w http.ResponseWriter, r *http.Request) { req := &request{} if err := json.NewDecoder(r.Body).Decode(req); err != nil { s.logger.Error(err) s.error(w, r, http.StatusBadRequest, err) return } if len(req.Purpose) > 210 { s.logger.Error(errTooLongPurpose) s.error(w, r, http.StatusBadRequest, errTooLongPurpose) return } session := &model.Session{ Amount: req.Amount, Purpose: req.Purpose, } session.SessionToken = uuid.New().String() session.CreatedAt = s.now() if err := s.store.Session().Create(session); err != nil { s.logger.Error(err) s.error(w, r, http.StatusUnprocessableEntity, err) return } s.logger.Info(fmt.Sprintf("create session with token %v", session.SessionToken)) s.respond(w, r, http.StatusCreated, session) } } func (s *APIServer) handlePayment() http.HandlerFunc { type request struct { SessionToken string `json:"session_token"` CardNumber string `json:"card_number"` Code string `json:"code"` Date string `json:"date"` } return func(w http.ResponseWriter, r *http.Request) { req := &request{} if err := json.NewDecoder(r.Body).Decode(req); err != nil { s.error(w, r, http.StatusBadRequest, err) return } session, err := s.store.Session().FindByToken(req.SessionToken) if err != nil { s.logger.Error(err) s.error(w, r, http.StatusInternalServerError, err) return } if !isZeroDate(session.ClosedAt) { s.logger.Error(errSessionAlreadyClosed) s.error(w, r, http.StatusBadRequest, errSessionAlreadyClosed) return } closedAt := s.now() delta := closedAt.Sub(session.CreatedAt) if delta.Seconds() > sessDuration { s.logger.Error(fmt.Sprintf("session token %v expired", session.SessionToken)) s.error(w, r, http.StatusBadRequest, errSessionExpired) return } if !IsCardDate(req.Date) { s.logger.Error(errInvalidCardDate) s.error(w, r, http.StatusBadRequest, errInvalidCardDate) return } if !IsCardCode(req.Code) { s.logger.Error(errInvalidCardDate) s.error(w, r, http.StatusBadRequest, errInvalidCardCode) return } if !IsCreditCard(req.CardNumber) { s.logger.Error(errInvalidCardNum) s.error(w, r, http.StatusBadRequest, errInvalidCardNum) return } if err := s.store.Session().CommitSession(session, closedAt); err != nil { s.logger.Error(err) s.error(w, r, http.StatusInternalServerError, err) return } s.logger.Info(fmt.Sprintf("session %v successfuly closed", session.SessionToken)) s.respond(w, r, http.StatusOK, map[string]string{"payment": "successful"}) } } func (s *APIServer) handleSessionsStats() http.HandlerFunc { type request struct { DateBegin string `json:"date_begin"` DateEnd string `json:"date_end"` } return func(w http.ResponseWriter, r *http.Request) { req := &request{} if err := json.NewDecoder(r.Body).Decode(req); err != nil { s.logger.Error(err) s.error(w, r, http.StatusBadRequest, err) return } dateB, dateE, err := s.parseDates(req.DateBegin, req.DateEnd) if err != nil { s.logger.Error(err) s.error(w, r, http.StatusBadRequest, err) return } var sessions []model.Session sessions, err = s.store.Session().GetStats(dateB, dateE) if err != nil { s.logger.Error(err) s.error(w, r, http.StatusInternalServerError, err) return } s.respond(w, r, http.StatusOK, sessions) } } func (s *APIServer) handleTokenCreate() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { claims := &jwt.MapClaims{ "exp": time.Now().Add(time.Hour * time.Duration(1)).Unix(), "user": "Default User", } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) tokenS, err := token.SignedString(secretKey) if err != nil { s.logger.Error(err) s.error(w, r, http.StatusInternalServerError, err) return } s.logger.Info(fmt.Sprintf("create jwt token %v", tokenS)) s.respond(w, r, http.StatusCreated, map[string]string{"jwt_token": tokenS}) } } func checkJWTToken(s *APIServer, next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { tokenH := r.Header.Get("Authorization") s.logger.Info(fmt.Sprintf("try authorizate with token header `%v`", tokenH)) auth := strings.SplitN(tokenH, " ", 2) if len(auth) != 2 { s.logger.Error(errNotAuthorized) s.error(w, r, http.StatusUnauthorized, errNotAuthorized) return } claims := &jwt.MapClaims{ "exp": time.Now().Add(time.Hour * time.Duration(1)).Unix(), "user": "Default User", } var tokenS = auth[1] token, err := jwt.ParseWithClaims(tokenS, claims, func(token *jwt.Token) (interface{}, error) { return secretKey, nil }) if token.Valid { next(w, r) } else if ve, ok := err.(*jwt.ValidationError); ok { if ve.Errors&jwt.ValidationErrorMalformed != 0 { s.logger.Error(errNotValidToken) s.error(w, r, http.StatusUnauthorized, errNotValidToken) return } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 { s.logger.Error(errTokenIsExpired) s.error(w, r, http.StatusUnauthorized, errTokenIsExpired) return } else { s.logger.Error(errCantHandleToken) s.error(w, r, http.StatusUnauthorized, errCantHandleToken) return } } else { s.logger.Error(errCantHandleToken) s.error(w, r, http.StatusUnauthorized, errCantHandleToken) return } } } func (s *APIServer) error(w http.ResponseWriter, r *http.Request, code int, err error) { s.respond(w, r, code, map[string]string{"error": err.Error()}) } func (s *APIServer) respond(w http.ResponseWriter, r *http.Request, code int, data interface{}) { w.WriteHeader(code) if data != nil { json.NewEncoder(w).Encode(data) } } func (s *APIServer) now() time.Time { loc, _ := time.LoadLocation("UTC") return time.Now().In(loc) } func (s *APIServer) parseDates(begin, end string) (time.Time, time.Time, error) { dateB, err := time.Parse(layout, begin) if err != nil { return zeroDate, zeroDate, err } dateE, err := time.Parse(layout, end) if err != nil { return zeroDate, zeroDate, err } return dateB, dateE, nil } func isZeroDate(t time.Time) bool { if t.Equal(zeroDate) { return true } return false }
package game_map import ( "fmt" "github.com/faiface/pixel/pixelgl" "github.com/steelx/go-rpg-cgm/animation" "github.com/steelx/go-rpg-cgm/state_machine" "math" "reflect" ) type CSMoveParams struct { Dir, Distance, Time float64 } type CSMove struct { Name string Character *Character CombatState *CombatState Entity *Entity Tween animation.Tween Anim animation.Animation AnimId string MoveTime, MoveDistance float64 PixelX, PixelY float64 } //char *Character, cs *CombatState func CSMoveCreate(args ...interface{}) state_machine.State { charV := reflect.ValueOf(args[0]) char := charV.Interface().(*Character) csV := reflect.ValueOf(args[1]) cs := csV.Interface().(*CombatState) return &CSMove{ Name: csMove, Character: char, CombatState: cs, Entity: char.Entity, Anim: animation.Create([]int{char.Entity.StartFrame}, true, 0.12), MoveTime: 0.3, MoveDistance: 32, } } func (s CSMove) IsFinished() bool { return s.Tween.IsFinished() } //data = CSMoveParams func (s *CSMove) Enter(data ...interface{}) { if len(data) == 0 || !reflect.ValueOf(data[0]).CanInterface() { panic(fmt.Sprintf("Please pass CSMoveParams while changing State")) return } backForth := reflect.ValueOf(data[0]).Interface().(CSMoveParams) if len(data) == 3 { s.MoveTime = backForth.Time s.MoveDistance = backForth.Distance } s.AnimId = s.Name frames := s.Character.GetCombatAnim(s.Name) var dir float64 = -1 if s.Character.Facing == CharacterFacingDirection[1] { s.AnimId = csRetreat frames = s.Character.GetCombatAnim(s.AnimId) dir = 1 } dir = dir * backForth.Dir s.Anim.SetFrames(frames) // Store current position s.PixelX = s.Entity.X s.PixelY = s.Entity.Y s.Tween = animation.TweenCreate(0, dir, s.MoveTime) } func (s *CSMove) Exit() { } func (s *CSMove) Update(dt float64) { s.Anim.Update(dt) s.Entity.SetFrame(s.Anim.Frame()) s.Tween.Update(dt) value := s.Tween.Value() x := s.PixelX + (value * s.MoveDistance) y := s.PixelY s.Entity.X = math.Floor(x) s.Entity.Y = math.Floor(y) } func (s *CSMove) Render(renderer *pixelgl.Window) { }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // TopicTransferSpec defines the desired state of TopicTransfer // +k8s:openapi-gen=true type TopicTransferSpec struct { // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster // Important: Run "operator-sdk generate k8s" to regenerate code after modifying this file // Add custom validation using kubebuilder tags: https://book-v1.book.kubebuilder.io/beyond_basics/generating_crd.html // Topic name Topic string `json:"topic,omitempty"` // The cluster where the transferred topic from SourceCluster string `json:"sourceCluster,omitempty"` // The cluster where the topic will be transferred to TargetCluster string `json:"targetCluster,omitempty"` } // TopicTransferStatus defines the observed state of TopicTransfer // +k8s:openapi-gen=true type TopicTransferStatus struct { // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster // Important: Run "operator-sdk generate k8s" to regenerate code after modifying this file // Add custom validation using kubebuilder tags: https://book-v1.book.kubebuilder.io/beyond_basics/generating_crd.html } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // TopicTransfer is the Schema for the topictransfers API // +k8s:openapi-gen=true // +kubebuilder:subresource:status type TopicTransfer struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec TopicTransferSpec `json:"spec,omitempty"` Status TopicTransferStatus `json:"status,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // TopicTransferList contains a list of TopicTransfer type TopicTransferList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []TopicTransfer `json:"items"` } func init() { SchemeBuilder.Register(&TopicTransfer{}, &TopicTransferList{}) }
package main import ( "fmt" "github.com/sunmi-OS/gocore/hbase" "github.com/sunmi-OS/gocore/log" "github.com/sunmi-OS/gocore/viper" "go.uber.org/zap" "os" ) func main() { // 初始化配置文件 viper.NewConfig("config", "conf") // 初始化日志库 log.InitLogger("example-Hbase") err := hbase.NewHbase() if err != nil { fmt.Println("连接失败,错误原因:", err.Error()) os.Exit(0) } talbeName := "sunmi6" rowkey := []byte("10009") cvarr := []*hbase.TColumnValue{ {Family: []byte("info"), Qualifier: []byte("age"), Value: []byte("23")}, {Family: []byte("info"), Qualifier: []byte("name"), Value: []byte("wenzhenxi")}, {Family: []byte("info"), Qualifier: []byte("sex"), Value: []byte("n")}, } // 写入数据 htput := hbase.TPut{Row: rowkey, ColumnValues: cvarr} err = hbase.HbaseClinet.Put(talbeName, &htput) if err != nil { log.Sugar.Infow("写入Hbase数据失败,原因:" + err.Error()) } else { log.Sugar.Infow("写入Hbase数据成功!") } // 获取数据 objs, err := hbase.HbaseClinet.Get(talbeName, &hbase.TGet{Row: rowkey}) if err != nil { log.Sugar.Infow("获取数据失败,原因:" + err.Error()) } else { log.Sugar.Infow("获取Hbase数据成功!", zap.Any("objs", objs)) } // 删除数据 err = hbase.HbaseClinet.Delete(talbeName, &hbase.TDelete{Row: rowkey}) if err != nil { log.Sugar.Infow("删除Hbase数据失败,原因:" + err.Error()) } else { log.Sugar.Infow("删除Hbase数据成功!") } // 判读数据是否存在 b, err := hbase.HbaseClinet.Exists(talbeName, &hbase.TGet{Row: rowkey}) if err != nil { log.Sugar.Infow("获取数据失败,原因:" + err.Error()) } else { if b { log.Sugar.Infow("数据存在") } else { log.Sugar.Infow("数据不存在") } } }
package aws import ( "net/http" "sort" "strings" survey "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/core" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/route53" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) // IsForbidden returns true if and only if the input error is an HTTP // 403 error from the AWS API. func IsForbidden(err error) bool { requestError, ok := err.(awserr.RequestFailure) return ok && requestError.StatusCode() == http.StatusForbidden } // GetBaseDomain returns a base domain chosen from among the account's // public routes. func GetBaseDomain() (string, error) { session, err := GetSession() if err != nil { return "", err } logrus.Debugf("listing AWS hosted zones") client := route53.New(session) publicZoneMap := map[string]struct{}{} exists := struct{}{} if err := client.ListHostedZonesPages( &route53.ListHostedZonesInput{}, func(resp *route53.ListHostedZonesOutput, lastPage bool) (shouldContinue bool) { for _, zone := range resp.HostedZones { if zone.Config != nil && !aws.BoolValue(zone.Config.PrivateZone) { publicZoneMap[strings.TrimSuffix(*zone.Name, ".")] = exists } } return !lastPage }, ); err != nil { return "", errors.Wrap(err, "list hosted zones") } publicZones := make([]string, 0, len(publicZoneMap)) for name := range publicZoneMap { publicZones = append(publicZones, name) } sort.Strings(publicZones) if len(publicZones) == 0 { return "", errors.New("no public Route 53 hosted zones found") } var domain string if err := survey.AskOne( &survey.Select{ Message: "Base Domain", Help: "The base domain of the cluster. All DNS records will be sub-domains of this base and will also include the cluster name.\n\nIf you don't see you intended base-domain listed, create a new public Route53 hosted zone and rerun the installer.", Options: publicZones, }, &domain, survey.WithValidator(func(ans interface{}) error { choice := ans.(core.OptionAnswer).Value i := sort.SearchStrings(publicZones, choice) if i == len(publicZones) || publicZones[i] != choice { return errors.Errorf("invalid base domain %q", choice) } return nil }), ); err != nil { return "", errors.Wrap(err, "failed UserInput") } return domain, nil } // GetPublicZone returns a public route53 zone that matches the name. func GetPublicZone(sess *session.Session, name string) (*route53.HostedZone, error) { var res *route53.HostedZone f := func(resp *route53.ListHostedZonesOutput, lastPage bool) (shouldContinue bool) { for idx, zone := range resp.HostedZones { if zone.Config != nil && !aws.BoolValue(zone.Config.PrivateZone) && strings.TrimSuffix(aws.StringValue(zone.Name), ".") == strings.TrimSuffix(name, ".") { res = resp.HostedZones[idx] return false } } return !lastPage } client := route53.New(sess) if err := client.ListHostedZonesPages(&route53.ListHostedZonesInput{}, f); err != nil { return nil, errors.Wrap(err, "listing hosted zones") } if res == nil { return nil, errors.Errorf("No public route53 zone found matching name %q", name) } return res, nil }
package staticdata type Mall_Data struct { ID int Name string Money int Discount float32 Icon int } func (self *Mall_Data) GetName() string { return "mall" } func (self *Mall_Data) GetFilePath() string { return "csv/mall_data.csv" }
package solution import ( "testing" ) func TestBasic(t *testing.T) { testcases := []int{1234567, 123456789, 1221, 12321, 11, 9, -1, 0, 11111} for _, testcase := range testcases { t.Log(testcase, isPalindrome3(testcase)) } }
package cache type CacheManager interface { // Cache returns kv cache with specific name Cache(name string) Cache }
package main import ( "fmt" "github.com/zdq0394/algorithm/base/tree" ) func main() { r := getCommontree() a := tree.InOrderTraversal(r) fmt.Printf("%s", "InOrder:") for _, v := range a { fmt.Printf("%d ", v) } fmt.Println() b := tree.PreorderTraversal(r) fmt.Printf("%s", "PreOrder:") for _, v := range b { fmt.Printf("%d ", v) } fmt.Println() c := tree.LevelOrder(r) fmt.Printf("%s", "LevelOrder:") for _, row := range c { for _, v := range row { fmt.Printf("%d ", v) } } fmt.Println("\nBST:") bst := getBStree() path := tree.FindPathOf(bst, 5) for _, p := range path { fmt.Printf("%d ", p.Val) } } func getCommontree() *tree.TreeNode { node4 := &tree.TreeNode{4, nil, nil} node5 := &tree.TreeNode{5, nil, nil} node6 := &tree.TreeNode{6, nil, nil} node7 := &tree.TreeNode{7, nil, nil} node2 := &tree.TreeNode{2, node4, node5} node3 := &tree.TreeNode{3, node6, node7} node1 := &tree.TreeNode{1, node2, node3} return node1 } func getBStree() *tree.TreeNode { node1 := &tree.TreeNode{1, nil, nil} node3 := &tree.TreeNode{3, nil, nil} node5 := &tree.TreeNode{5, nil, nil} node7 := &tree.TreeNode{7, nil, nil} node2 := &tree.TreeNode{2, node1, node3} node6 := &tree.TreeNode{6, node5, node7} node4 := &tree.TreeNode{4, node2, node6} return node4 }
package consumer import ( "sync" "container/list" "log" ) type memQueue struct { name string sync.RWMutex queue *list.List // exposed via ReadChan() readChan chan interface{} // internal channels writeChan chan interface{} writeResponseChan chan error exitChan chan int waitGroup WaitGroupWrapper } func newMemQueue(name string) *memQueue { q := list.New() m := memQueue{ name: name, queue: q, readChan: make(chan interface{}), writeChan: make(chan interface{}), writeResponseChan: make(chan error), exitChan: make(chan int), } m.waitGroup.Wrap( func() {m.ioLoop()} ) return &m } func (d *memQueue) Put(data interface{}) error { d.RLock() defer d.RUnlock() d.writeChan <- data return <-d.writeResponseChan } func (d *memQueue) ReadChan() chan interface{} { return d.readChan } func (d *memQueue) Close() error { close(d.exitChan) d.waitGroup.Wait() d.flush() return nil } func (d *memQueue) Depth() int64 { d.RLock() defer d.RUnlock() return int64(d.queue.Len() + len(d.readChan)) } func (d *memQueue) write(data interface{}) error { d.queue.PushBack(data) return nil } func (d *memQueue) read() interface{} { if n := d.queue.Front(); n != nil { data := n.Value return data } return nil } func (d *memQueue) flush() error { log.Printf("memQueue(%s): flushing ...", d.name) for { if ele := d.queue.Front(); ele != nil { log.Printf("memQueue(%s): flush request - %v", d.name, ele.Value) d.queue.Remove(ele) continue } break } return nil } func (d *memQueue) ioLoop() { log.Printf("memQueue(%s): starting ... ioLoop", d.name) var r chan interface{} var dataRead interface{} for { //! if storage has data,prepare data if dataRead == nil { dataRead = d.read() } if dataRead != nil { r = d.readChan } else { r = nil } //! select for the channel select { case r <- dataRead: d.queue.Remove(d.queue.Front()) dataRead = nil case dataWrite := <- d.writeChan: d.writeResponseChan <- d.write(dataWrite) case <- d.exitChan: goto exit } } exit: log.Printf("memQueue(%s): closing ... ioLoop", d.name) }
// unmarshal. package main import ( "encoding/json" "fmt" ) type JSON struct { String string `json:"string"` Array []string `json:"array"` } var str = []byte(`{ "string": "hello world", "array": [ "string 1", "string 2" ] }`) var invalidStr = []byte(`{ string: "hello world" }`) func main() { // valid var v JSON if err := json.Unmarshal(str, &v); err != nil { panic(err) } fmt.Printf("v:%+v\n", v) // invalid var v2 JSON if err := json.Unmarshal(invalidStr, &v2); err != nil { defer func() { fmt.Println(recover()) }() panic(err) } fmt.Printf("v2:%+v\n", v) }
package blocks import ( "bytes" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "cryptom/internal" "encoding/gob" "encoding/hex" "errors" "fmt" "log" "math/big" ) /** Outputs are where “coins” are stored. Each output comes with an unlocking script, which determines the logic of unlocking the output. Every new transaction must have at least one input and output. An input references an output from a previous transaction and provides data (the ScriptSig field) that is used in the output’s unlocking script to unlock it and use its value to create new outputs. */ const genesisBaseData = "we fight for a better world" type Tx struct { ID []byte Vin []TxInput Vout []TxOutput } // The input of the transaction type TxInput struct { TxID []byte Vout int Signature []byte //should have the signature from the wallet PubKey []byte } type TxOutput struct { Value int PubHashKey []byte } func (ti *TxInput) UsesKey(pubKey []byte) bool { lockingHash := HashPubKey(ti.PubKey) return bytes.Compare(lockingHash, pubKey) == 0 } func (tx *Tx) SetID() { var ( encoded bytes.Buffer hash [32]byte ) enc := gob.NewEncoder(&encoded) err := enc.Encode(tx) if err != nil { log.Panic(err) } hash = sha256.Sum256(encoded.Bytes()) tx.ID = hash[:] } // NewCoinBaseTx is the "egg" for the transactions. Is the beginning of the transaction history. func NewCoinBaseTx(to, data string) *Tx { if data == "" { data = fmt.Sprintf("Reward to '%s'", to) } in := TxInput{ TxID: []byte{}, Vout: -1, PubKey: []byte(data), } out := NewTXOutput(10, to) tx := Tx{ Vin: []TxInput{in}, Vout: []TxOutput{*out}, } tx.ID = tx.Hash() return &tx } func (tx *Tx) IsCoinBase() bool { return len(tx.Vin) == 1 && len(tx.Vin[0].TxID) == 0 && tx.Vin[0].Vout == -1 } func (tx *Tx) Serialize() []byte { var res bytes.Buffer encoder := gob.NewEncoder(&res) err := encoder.Encode(tx) if err != nil { panic(err) } return res.Bytes() } // Hash returns the hash of the Transaction func (tx *Tx) Hash() []byte { var hash [32]byte txCopy := *tx txCopy.ID = []byte{} hash = sha256.Sum256(txCopy.Serialize()) return hash[:] } // NewUTXOTransaction creates a new transaction func NewUTXOTransaction(from, to string, amount int, bc *Blockchain) *Tx { var inputs []TxInput var outputs []TxOutput wallets, err := NewWallets() if err != nil { log.Panic(err) } wallet := wallets.GetWallet(from) pubKeyHash := HashPubKey(wallet.PublicKey) acc, validOutputs := bc.FindSpendableOutputs(pubKeyHash, amount) if acc < amount { log.Panic("ERROR: Not enough funds") } // Build a list of inputs for txid, outs := range validOutputs { txID, err := hex.DecodeString(txid) if err != nil { log.Panic(err) } for _, out := range outs { input := TxInput{txID, out, nil, wallet.PublicKey} inputs = append(inputs, input) } } // Build a list of outputs outputs = append(outputs, *NewTXOutput(amount, to)) if acc > amount { outputs = append(outputs, *NewTXOutput(acc-amount, from)) // a change } tx := Tx{nil, inputs, outputs} tx.ID = tx.Hash() bc.SignTransaction(&tx, wallet.PrivateKey) return &tx } // FindTransaction finds a transaction by its ID func (bc *Blockchain) FindTransaction(ID []byte) (Tx, error) { bci := bc.Iterator() for { block := bci.Next() for _, tx := range block.Transactions { if bytes.Compare(tx.ID, ID) == 0 { return *tx, nil } } if len(block.PrevBlockHash) == 0 { break } } return Tx{}, errors.New("transaction is not found") } // Verify verifies signatures of Transaction inputs func (tx *Tx) Verify(prevTXs map[string]Tx) bool { if tx.IsCoinBase() { return true } for _, vin := range tx.Vin { if prevTXs[hex.EncodeToString(vin.TxID)].ID == nil { log.Panic("ERROR: Previous transaction is not correct") } } txCopy := tx.TrimmedCopy() curve := elliptic.P256() for inID, vin := range tx.Vin { prevTx := prevTXs[hex.EncodeToString(vin.TxID)] txCopy.Vin[inID].Signature = nil txCopy.Vin[inID].PubKey = prevTx.Vout[vin.Vout].PubHashKey txCopy.ID = txCopy.Hash() txCopy.Vin[inID].PubKey = nil r := big.Int{} s := big.Int{} sigLen := len(vin.Signature) r.SetBytes(vin.Signature[:(sigLen / 2)]) s.SetBytes(vin.Signature[(sigLen / 2):]) x := big.Int{} y := big.Int{} keyLen := len(vin.PubKey) x.SetBytes(vin.PubKey[:(keyLen / 2)]) y.SetBytes(vin.PubKey[(keyLen / 2):]) rawPubKey := ecdsa.PublicKey{Curve: curve, X: &x, Y: &y} if ecdsa.Verify(&rawPubKey, txCopy.ID, &r, &s) == false { return false } } return true } // TrimmedCopy creates a trimmed copy of Transaction to be used in signing func (tx *Tx) TrimmedCopy() Tx { var inputs []TxInput var outputs []TxOutput for _, vin := range tx.Vin { inputs = append(inputs, TxInput{vin.TxID, vin.Vout, nil, nil}) } for _, vout := range tx.Vout { outputs = append(outputs, TxOutput{vout.Value, vout.PubHashKey}) } txCopy := Tx{tx.ID, inputs, outputs} return txCopy } // IsLockedWithKey checks if the output can be used by the owner of the pubkey func (to *TxOutput) IsLockedWithKey(pubKeyHash []byte) bool { return bytes.Compare(to.PubHashKey, pubKeyHash) == 0 } // Lock signs the output func (to *TxOutput) Lock(address []byte) { pubHashKey := internal.Base58Decode(address) pubHashKey = pubHashKey[1 : len(pubHashKey)-4] to.PubHashKey = pubHashKey } // NewTXOutput create a new TXOutput func NewTXOutput(value int, address string) *TxOutput { txo := &TxOutput{value, nil} txo.Lock([]byte(address)) return txo } // Sign signs each input of a Transaction func (tx *Tx) Sign(privateKey ecdsa.PrivateKey, prevTXs map[string]Tx) { if tx.IsCoinBase() { return } for _, vin := range tx.Vin { if prevTXs[hex.EncodeToString(vin.TxID)].ID == nil { log.Panic("ERROR: Previous transaction is not correct") } } txCopy := tx.TrimmedCopy() for inID, vin := range txCopy.Vin { prevTx := prevTXs[hex.EncodeToString(vin.TxID)] txCopy.Vin[inID].Signature = nil txCopy.Vin[inID].PubKey = prevTx.Vout[vin.Vout].PubHashKey txCopy.ID = txCopy.Hash() txCopy.Vin[inID].PubKey = nil r, s, err := ecdsa.Sign(rand.Reader, &privateKey, txCopy.ID) if err != nil { log.Panic(err) } signature := append(r.Bytes(), s.Bytes()...) tx.Vin[inID].Signature = signature } }
package coins_test import ( "context" "testing" "google.golang.org/grpc" "github.com/stretchr/testify/assert" coins "github.com/angelospillos/coinsorchestrator" pricing "github.com/angelospillos/pricingservice/proto" ranking "github.com/angelospillos/rankingservice/proto" ) type MockPricingService struct { PricingResponse pricing.PricingResponse Err error } func (pr MockPricingService) GetPricing(ctx context.Context, in *pricing.PricingRequest, opts ...grpc.CallOption) (*pricing.PricingResponse, error) { return &pr.PricingResponse, pr.Err } type MockRankingService struct { RankingResponse ranking.RankingResponse Err error } func (rk MockRankingService) GetRankings(ctx context.Context, in *ranking.RankingRequest, opts ...grpc.CallOption) (*ranking.RankingResponse, error) { return &rk.RankingResponse, rk.Err } func TestGetTopCoinsByMarketCap(t *testing.T) { mockPricingService := MockPricingService{pricing.PricingResponse{ Quotes: map[string]float32{ "BTC": 1.1, "ETH": 2.2, "BNB": 3.3, "DOGE": 4.4, "ADA": 5.5, "USDT": 6.6, "XRP": 7.7, "DOT": 8.8, "BCH": 9.9, "LTC": 10.10, }, }, nil} mockRankingService := MockRankingService{ranking.RankingResponse{ Ranks: []*ranking.Rank{ {Order: 1, Symbol: "LTC"}, {Order: 2, Symbol: "BCH"}, {Order: 3, Symbol: "DOT"}, {Order: 4, Symbol: "XRP"}, {Order: 5, Symbol: "USDT"}, {Order: 6, Symbol: "ADA"}, {Order: 7, Symbol: "DOGE"}, {Order: 8, Symbol: "BNB"}, {Order: 9, Symbol: "ETH"}, {Order: 10, Symbol: "BTC"}, }, }, nil} service := coins.Service{ PricingService: mockPricingService, RankingService: mockRankingService, } result, err := service.GetTopCoinsByMarketCap(10) // With Testify assert.NoError(t, err) assert.Equal(t, "LTC", result[0].Symbol) assert.Equal(t, float32(10.10), result[0].Price) assert.Equal(t, int32(1), result[0].Rank) // Without Testify if result[0].Symbol!= "LTC" { t.Fatal("Symbol not what expected") } if result[0].Price!= 10.10 { t.Fatal("Price not what expected") } if result[0].Rank!= 1 { t.Fatal("Rank not what expected") } } func TestGetTopCoinsByMarketCapLimit(t *testing.T) { mockPricingService := MockPricingService{pricing.PricingResponse{ Quotes: map[string]float32{}, }, nil} mockRankingService := MockRankingService{ranking.RankingResponse{ Ranks: []*ranking.Rank{}, }, nil} service := coins.Service{ PricingService: mockPricingService, RankingService: mockRankingService, } result, err := service.GetTopCoinsByMarketCap(1) assert.Empty(t, result) assert.Error(t, err) }
package two_sums type Numbers interface { TwoSum() []int } type numbers struct { nums []int target int } func (n *numbers) TwoSum() []int { theMap := map[int]int{} for i, num := range n.nums { theMap[num] = i } for i, num := range n.nums { if val, ok := theMap[n.target-num]; ok { if val <= i { continue } return []int{i, val} } } return nil } func NewNumbers(nums []int, target int) Numbers { return &numbers{ nums: nums, target: target, } }
package iot import ( "encoding/json" "github.com/aliyun/alibaba-cloud-sdk-go/sdk" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/zhuiyi1997/go-gin-api/app/config" "log" "reflect" ) type Iot struct { RegionId string AccessKey string AccessSecret string Client *sdk.Client } func NewIot() (Iot,error){ var poac Iot = Iot{RegionId: config.IotConf["regionId"],AccessKey: config.IotConf["accessKey"],AccessSecret: config.IotConf["accessSecret"]} client, err := sdk.NewClientWithAccessKey(poac.RegionId,poac.AccessKey,poac.AccessSecret) poac.Client = client return poac,err } func (iot *Iot) RegisterDevice(device map[string]string) (bool,map[string]string){ request := requests.NewCommonRequest() request.Method = "POST" request.Scheme = "https" request.Domain = config.IotConf["iotHost"] request.Version = "2018-01-20" request.ApiName = "RegisterDevice" request.QueryParams["RegionId"] = config.IotConf["regionId"] request.QueryParams["ProductKey"] = config.IotConf["productKey"] request.QueryParams["IotInstanceId"] = config.IotConf["iotInstanceId"] request.QueryParams["DeviceName"] = device["DeviceName"] request.QueryParams["Nickname"] = device["Nickname"] response, err := iot.Client.ProcessCommonRequest(request) m := map[string]string{} if err != nil { m["error"] = err.Error() return false,m; } resp := response.GetHttpContentString() var d interface{} err = json.Unmarshal([]byte(resp),&d) if err != nil { m["error"] = err.Error() return false,m; } log.Println(resp) if reflect.ValueOf(d.(map[string]interface{})["Success"]).Bool() { for k,v := range d.(map[string]interface{}) { if k == "Data" { for k1,v1 := range v.(map[string]interface{}) { m[k1] = reflect.ValueOf(v1).String() } } } return true,m; } else { m["error"] = reflect.ValueOf(d.(map[string]interface{})["ErrorMessage"]).String() return false,m; } }
package wps import ( `encoding/json` ) type ( // UploadByLocalFileReq 本地文件上传 UploadLocalFileReq struct { // 文件 File string `json:"file"` } // UploadNetworkFileReq HTTP/HTTPS网络文件上传 UploadNetworkFileReq struct { // 网络文件地址 Url string `json:"url" url:"url"` } // UploadFileRsp 文件上传返回结果 UploadFileRsp struct { BaseRsp // 数据 Data struct { // WPS文件编号 Id string `json:"id"` } `json:"data"` } ) func (ur UploadLocalFileReq) String() string { jsonBytes, _ := json.MarshalIndent(ur, "", " ") return string(jsonBytes) } func (ur UploadNetworkFileReq) String() string { jsonBytes, _ := json.MarshalIndent(ur, "", " ") return string(jsonBytes) } func (ur UploadFileRsp) String() string { jsonBytes, _ := json.MarshalIndent(ur, "", " ") return string(jsonBytes) }
// Copyright 2020 MongoDB 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 convert import ( "strings" atlas "go.mongodb.org/atlas/mongodbatlas" "go.mongodb.org/ops-manager/opsmngr" ) const ( AdminDB = "admin" roleSep = "@" defaultUserDatabase = "admin" ) // BuildAtlasRoles converts the roles inside the array of string in an array of mongodbatlas.Role structs // r contains roles in the format roleName@dbName func BuildAtlasRoles(r []string) []atlas.Role { roles := make([]atlas.Role, len(r)) for i, roleP := range r { role := strings.Split(roleP, roleSep) roleName := role[0] databaseName := defaultUserDatabase if len(role) > 1 { databaseName = role[1] } roles[i] = atlas.Role{ RoleName: roleName, DatabaseName: databaseName, } } return roles } // BuildOMRoles converts the roles inside the array of string in an array of opsmngr.Role structs // r contains roles in the format roleName@dbName func BuildOMRoles(r []string) []*opsmngr.Role { roles := make([]*opsmngr.Role, len(r)) for i, roleP := range r { role := strings.Split(roleP, roleSep) roleName := role[0] databaseName := defaultUserDatabase if len(role) > 1 { databaseName = role[1] } roles[i] = &opsmngr.Role{ Role: roleName, Database: databaseName, } } return roles }
// This file was generated for SObject ContentWorkspaceMember, API Version v43.0 at 2018-07-30 03:47:23.111111129 -0400 EDT m=+9.454072311 package sobjects import ( "fmt" "strings" ) type ContentWorkspaceMember struct { BaseSObject ContentWorkspaceId string `force:",omitempty"` ContentWorkspacePermissionId string `force:",omitempty"` CreatedById string `force:",omitempty"` CreatedDate string `force:",omitempty"` Id string `force:",omitempty"` MemberId string `force:",omitempty"` MemberType string `force:",omitempty"` } func (t *ContentWorkspaceMember) ApiName() string { return "ContentWorkspaceMember" } func (t *ContentWorkspaceMember) String() string { builder := strings.Builder{} builder.WriteString(fmt.Sprintf("ContentWorkspaceMember #%s - %s\n", t.Id, t.Name)) builder.WriteString(fmt.Sprintf("\tContentWorkspaceId: %v\n", t.ContentWorkspaceId)) builder.WriteString(fmt.Sprintf("\tContentWorkspacePermissionId: %v\n", t.ContentWorkspacePermissionId)) builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById)) builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate)) builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id)) builder.WriteString(fmt.Sprintf("\tMemberId: %v\n", t.MemberId)) builder.WriteString(fmt.Sprintf("\tMemberType: %v\n", t.MemberType)) return builder.String() } type ContentWorkspaceMemberQueryResponse struct { BaseQuery Records []ContentWorkspaceMember `json:"Records" force:"records"` }
package transformation import ( "fmt" "time" ) //ModuleBuildTime type definition representing the build time of a Module type ModuleBuildTime struct { ModuleName string BuildTime time.Duration } //ReactorSummary type definition for the parsed Maven reactor summary of a build type ReactorSummary []ModuleBuildTime //Release type definition of a maven release number type Release string const unknownRelease = Release("unknown") //Report type definition of a Report containing all Reactor summaries type Report map[Release][]ReactorSummary //CliParameters type for input parameters from cli type CliParameters struct { SourceFolder *string OutputFormat OutputFormat OutputFile *string EsAddress *string Username *string Password *string } //OutputFormat type definition for output formats type OutputFormat string const ( //NoneFormat dummy output format when no format was provided NoneFormat = OutputFormat("NONE") //CSVFormat constant value for CSV output format CSVFormat = OutputFormat("CSV") //ElasticsearchFormat constant value for ElasticSearch output format ElasticsearchFormat = OutputFormat("ES") ) //Apply executs the transformation using the provided input parameters func Apply(params *CliParameters) error { r := createReader() err := r.Validate(params) if err != nil { return err } w, err := createWriter(params) if err != nil { return err } err = w.Validate(params) if err != nil { return err } data, err := r.Read(params) if err != nil { return err } return w.Write(params, data) } func createWriter(params *CliParameters) (writer, error) { switch params.OutputFormat { case CSVFormat: return &csvWriter{}, nil case ElasticsearchFormat: return &es7Writer{}, nil } return nil, fmt.Errorf("Unsupported output format %s", params.OutputFormat) } type writer interface { Write(parmas *CliParameters, summaries Report) error Validate(params *CliParameters) error } func createReader() reader { return &sourceFolderReader{} } type reader interface { Read(params *CliParameters) (Report, error) Validate(params *CliParameters) error }
package main import ( "log" "net/http" "strconv" "github.com/vlad-belogrudov/gopl/pkg/lissajous" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { var err error if err = r.ParseForm(); err != nil { log.Println("cannot parse params: ", err) w.WriteHeader(http.StatusBadRequest) return } params := lissajous.DefaultLissajousParams() for k, v := range r.Form { switch k { case "cycles": params.Cycles, err = strconv.Atoi(v[0]) if err != nil { log.Println("cannot parse cycles: ", err) w.WriteHeader(http.StatusBadRequest) return } case "res": params.Res, err = strconv.ParseFloat(v[0], 10) if err != nil { log.Println("cannot parse res: ", err) w.WriteHeader(http.StatusBadRequest) return } case "xsize": params.Xsize, err = strconv.Atoi(v[0]) if err != nil { log.Println("cannot parse xsize: ", err) w.WriteHeader(http.StatusBadRequest) return } case "ysize": params.Ysize, err = strconv.Atoi(v[0]) if err != nil { log.Println("cannot parse ysize: ", err) w.WriteHeader(http.StatusBadRequest) return } case "frames": params.Frames, err = strconv.Atoi(v[0]) if err != nil { log.Println("cannot parse frames: ", err) w.WriteHeader(http.StatusBadRequest) return } case "delay": params.Delay, err = strconv.Atoi(v[0]) if err != nil { log.Println("cannot parse delay ", err) w.WriteHeader(http.StatusBadRequest) return } } } lissajous.Lissajous(w, params) }) log.Fatal(http.ListenAndServe("localhost:8000", nil)) }
package iavl import ( "github.com/ColorPlatform/color-sdk/codec" ) var cdc = codec.New()
package main import ( "bytes" "fmt" "io/ioutil" //"ms/sun/shared/helper" "os" "path/filepath" "regexp" //"ms/sun/shared/helper" "io" "strconv" "time" ) //const DIR = `E:\WEB\files\file\dl\file\pic\music\2013\06\` /*const DIR = `E:\WEB\files\file\dl\file\pic\photo\` const OUT_LOG = `C:\Go\_gopath\src\ms\sun\scripts\server_migration\logs\` const MOVE_DIR = `E:\WEB\files\file\dl\file\pic\photo_moved\`*/ const DIR = `/dl/photo/` const OUT_LOG = `/dl/photo/` const MOVE_DIR = `/dl/photo_moved/` var filesToProcced = make(chan fileName, 10000) var dirsToProcced = make(chan string) var allFiles = make(map[string][]fileName, 1000000) var toIgnore = make([]fileName, 0) var toMove = make([]fileName, 0) var unknown = make([]fileName, 0) var cnt = 0 var fCall = 0 func main() { go proccedFiles() proccedDirs() go func() { for { time.Sleep(time.Minute * 1) fmt.Println("================= fCall: ", fCall) } }() walkDir(DIR) selectImage() logResult() // move(true) } func proccedDirs() { } func walkDir(dir string) { fmt.Println("dir: ", dir) fmt.Println("+++++++++++ walkDir() ") filepath.Walk(dir, func(path string, f os.FileInfo, err error) error { fCall++ if f == nil { fmt.Println("===============================it is nil: ", path) return nil } if f.IsDir() { //walkDir(path) //dirsToProcced <- path if dir != path { walkDir(path) } } else { fn := fileName{ path: path, name: f.Name(), } fn.extract() filesToProcced <- fn } return nil }) fmt.Println("+++++++++++ end of walkDir ") } func selectImage() { fmt.Println("+++++++++++ selectImage ") for _, fms := range allFiles { fCall++ sel := fms[0] for _, fn := range fms { if sel.size < fn.size { sel = fn } } toMove = append(toMove, sel) for _, fn := range fms { if sel != fn { toIgnore = append(toIgnore, fn) } } } fmt.Println("+++++++++++ end of selectImage ") } func proccedFiles() { for f := range filesToProcced { fCall++ //helper.PertyPrint(f) //fmt.Printf("%# v\n", f) if f.valid { allFiles[f.baseImageName] = append(allFiles[f.baseImageName], f) } else { unknown = append(unknown, f) } cnt++ if cnt%10000 == 0 { fmt.Println("procceded: ", cnt) fmt.Printf("%# v\n", f) } } } func sizeLog() { i := 0 var totalSize = 0 for _, fn := range toMove { info, err := os.Stat(fn.path) if err == nil { totalSize += int(info.Size()) } i++ } s := fmt.Sprintf("num: %d - size: %d ", i, totalSize) ioutil.WriteFile("size.txt", []byte(s), os.ModePerm) } func logResult() { fmt.Println("+++++++++++ logResult ") moveBuff := bytes.NewBufferString("") for _, fn := range toMove { fCall++ moveBuff.Write([]byte(fn.path + " \n")) } ignoreBuff := bytes.NewBufferString("") for _, fn := range toIgnore { fCall++ ignoreBuff.Write([]byte(fn.path + " \n")) } unknownBuff := bytes.NewBufferString("") for _, fn := range unknown { fCall++ unknownBuff.Write([]byte(fn.path + " \n")) } //movedResBuff := bytes.NewBufferString("") //for _, fn := range toMove { // o := fmt.Sprintf("%s -> %s \n", fn.path, MOVE_DIR+fn.name) // movedResBuff.Write([]byte(o)) //} os.Chdir(OUT_LOG) ioutil.WriteFile("./move.txt", moveBuff.Bytes(), os.ModePerm) ioutil.WriteFile("./ignore.txt", ignoreBuff.Bytes(), os.ModePerm) ioutil.WriteFile("./unknow.txt", unknownBuff.Bytes(), os.ModePerm) //ioutil.WriteFile("moved_locations.txt", movedResBuff.Bytes(), os.ModePerm) //move(true) removes() // sizeLog() //fmt.Printf("to moves: %# v\n", toMove) //fmt.Printf("to ignore: %# v\n", toIgnore) //fmt.Printf("unknown: %# v\n", unknown) } type fileName struct { name string ext string baseImageName string size int path string valid bool } var regSize = regexp.MustCompile(`_(\d+)_?\.?`) var regExt = regexp.MustCompile(`\.\w+`) func (f *fileName) extract() { //f.ext = f.path[strings.Index(f.path, "."):] //r:=regSize.MatchString(f.path) f.ext = regExt.FindString(f.path) groups := regSize.FindStringSubmatch(f.path) if len(groups) == 2 { f.size = StrToInt(groups[1], 0) } else { f.size = 9999999999 } if len(f.name) > 32 { f.baseImageName = f.name[:32] f.valid = true } else { f.valid = false } //fmt.Println(r) } func removes() { fmt.Println("+++++++++++ removes() ") removeResBuff := bytes.NewBufferString("") removeErrs := bytes.NewBufferString("") for _, fn := range toIgnore { fCall++ o := fmt.Sprintf("%s \n", fn.path) removeResBuff.Write([]byte(o)) err := os.Remove(fn.path) if err != nil { removeErrs.Write([]byte(fmt.Sprintf("%v\n", err))) fmt.Println("error in moving file: ", err, fn.path) } } ioutil.WriteFile("./remove_locations.txt", removeResBuff.Bytes(), os.ModePerm) ioutil.WriteFile("./remove_errs.txt", removeErrs.Bytes(), os.ModePerm) } func move(mov bool) { fmt.Println("+++++++++++ move() ") os.MkdirAll(MOVE_DIR, os.ModeDir) i := 0 dir_cnt := 0 // var errs []error movedResBuff := bytes.NewBufferString("") movedErrs := bytes.NewBufferString("") for _, fn := range toMove { fCall++ num := i % 2000 out_dir := fmt.Sprintf("%sout_%d/", MOVE_DIR, dir_cnt) if num == 0 { os.MkdirAll(out_dir, os.ModeDir) dir_cnt++ } oo := out_dir + fn.name o := fmt.Sprintf("%s -> %s \n", fn.path, oo) movedResBuff.Write([]byte(o)) if true { //err := os.Rename(fn.path, oo) err := cp(fn.path, oo) if err != nil { movedErrs.Write([]byte(fmt.Sprintf("%v\n", err))) fmt.Println("error in moving file: ", err, oo) } } i++ } ioutil.WriteFile("./moved_locations.txt", movedResBuff.Bytes(), os.ModePerm) ioutil.WriteFile("./moved_errs.txt", movedErrs.Bytes(), os.ModePerm) } func StrToInt(str string, defualt int) int { r64, err := strconv.ParseInt(str, 10, 64) if err != nil { return defualt } return int(r64) } func cp(src, dst string) error { s, err := os.Open(src) if err != nil { return err } // no need to check errors on read only file, we already got everything // we need from the filesystem, so nothing can go wrong now. defer s.Close() d, err := os.Create(dst) if err != nil { return err } if _, err := io.Copy(d, s); err != nil { d.Close() return err } return d.Close() }
package core import ( "net/http" "bytes" "os" "log" "io/ioutil" ) type DialogFlow struct { query string lang string sessionId string } const endpoint = "https://api.api.ai/v1/query" const envKeyVar = "SINGLE_TANGO_KEY" func (df *DialogFlow) MakeRequest() ([]byte, error) { client := &http.Client{} req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(df.GetIntent())) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "bearer" + df.GetClientAccessToken()) req.Header.Set("Content-Type", "application/json") resp, err := client.Do(req) if err != nil { return nil, err } return ResponseBody(resp) } func ResponseBody(res *http.Response) ([]byte, error) { body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } return body, nil } func (df *DialogFlow) GetIntent() []byte { return []byte(`{"query": "` + df.query + `", "lang": "` + df.lang + `", "sessionId": "` + df.sessionId + `"}`) } func (df *DialogFlow) GetClientAccessToken() string { return os.Getenv(envKeyVar) } func (df *DialogFlow) SetQuery(q string) { df.query = q } func (df *DialogFlow) GetQuery() string { return df.query } func (df *DialogFlow) SetSessionId(sid string) { df.sessionId = sid } func (df *DialogFlow) SetLang(lang string) { df.lang = lang }
package zigzag_conversion import ( "strings" ) func convert(s string, numRows int) string { if len(s) <= 2 { return s } lines := getLines(s, numRows) columns := len(lines)/2*(numRows-1) + 1 elements := make([][]string, numRows) for i, _ := range elements { elements[i] = make([]string, columns) } for i, line := range lines { if i%2 == 0 { fillVertical(elements, line, i/2*(numRows-1)) } else { fillSlanted(elements, line, i/2*(numRows-1), numRows) } } var output string for _, column := range elements { output += strings.Join(column, "") } return output } func getLines(s string, numRows int) []string { var ( lines = make([]string, 0) length = len(s) start = 0 i = 0 ) for start < length { end := start + numRows if end > length { end = length } lines = append(lines, s[start:end]) i++ start = i * (numRows - 1) } return lines } func fillVertical(elements [][]string, line string, start int) { for i, s := range line { elements[i][start] = string(s) } } func fillSlanted(elements [][]string, line string, start int, numRows int) { for i, s := range line { elements[numRows-i-1][start+i] = string(s) } }
package main import "testing" // TestGenerate tests that we can still generate the list, to catch // if anything changes on Chromium side. func TestGenerate(t *testing.T) { sites, err := get() if err != nil { t.Fatal(err) } // 2019-05-01 list was 69567 domains long. if len(sites) < 50000 { t.Errorf("too few sites: %v", len(sites)) } domains := map[string]bool{} for _, e := range sites { domains[e.Name] = e.IncludeSubDomains } // Domains we expect in the list and to include subdomains. for _, d := range []string{ "accounts.google.com", "login.yahoo.com", } { include, ok := domains[d] if !ok { t.Errorf("not in the list: %v", d) } else if !include { t.Errorf("does not include subdomains: %v", d) } } }
/* Adam West passed away, and I'd like to honor his memory here on PPCG, though I doubt he knew of our existence. While there are many, many different things that this man is known for, none are more prominent than his role as the original batman. I'll always remember my step-father still watching the old-school Batman and Robin to this day. This challenge is simplistic in nature, not at all in line with the complicated man that was Adam West. However, it's the best I could come up with, as this is the most iconic image of the man's career. I wanted to post this earlier, but I was waiting for someone to come up with something better. Output the following (with or without trailing spaces/newlines): * * **** * * **** **** ******* **** ****** ******* ****** ********* ********* ********* *********************************************** ************************************************* ************************************************* ************************************************* *********************************************** ***** ********************* ***** **** *** ***** *** **** ** * *** * ** This is code-golf, the lowest byte-count will win. */ package main import "fmt" func main() { fmt.Println(batman) } const batman = ` * * **** * * **** **** ******* **** ****** ******* ****** ********* ********* ********* *********************************************** ************************************************* ************************************************* ************************************************* *********************************************** ***** ********************* ***** **** *** ***** *** **** ** * *** * ** `
/* --- Day 2: Inventory Management System --- You stop falling through time, catch your breath, and check the screen on the device. "Destination reached. Current Year: 1518. Current Location: North Pole Utility Closet 83N10." You made it! Now, to find those anomalies. Outside the utility closet, you hear footsteps and a voice. "...I'm not sure either. But now that so many people have chimneys, maybe he could sneak in that way?" Another voice responds, "Actually, we've been working on a new kind of suit that would let him fit through tight spaces like that. But, I heard that a few days ago, they lost the prototype fabric, the design plans, everything! Nobody on the team can even seem to remember important details of the project!" "Wouldn't they have had enough fabric to fill several boxes in the warehouse? They'd be stored together, so the box IDs should be similar. Too bad it would take forever to search the warehouse for two similar box IDs..." They walk too far away to hear any more. Late at night, you sneak to the warehouse - who knows what kinds of paradoxes you could cause if you were discovered - and use your fancy wrist device to quickly scan every box and produce a list of the likely candidates (your puzzle input). To make sure you didn't miss any, you scan the likely candidate boxes again, counting the number that have an ID containing exactly two of any letter and then separately counting those with exactly three of any letter. You can multiply those two counts together to get a rudimentary checksum and compare it to what your device predicts. For example, if you see the following box IDs: abcdef contains no letters that appear exactly two or three times. bababc contains two a and three b, so it counts for both. abbcde contains two b, but no letter appears exactly three times. abcccd contains three c, but no letter appears exactly two times. aabcdd contains two a and two d, but it only counts once. abcdee contains two e. ababab contains three a and three b, but it only counts once. Of these box IDs, four of them contain a letter which appears exactly twice, and three of them contain a letter which appears exactly three times. Multiplying these together produces a checksum of 4 * 3 = 12. What is the checksum for your list of box IDs? --- Part Two --- Confident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric. The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs: abcde fghij klmno pqrst fguij axcye wvxyz The IDs abcde and axcye are close, but they differ by two characters (the second and fourth). However, the IDs fghij and fguij differ by exactly one character, the third (h and u). Those must be the correct boxes. What letters are common between the two correct box IDs? (In the example above, this is found by removing the differing character from either ID, producing fgij.) */ package main import ( "bufio" "fmt" "log" "os" ) func main() { l, err := getlines("2.txt") if err != nil { log.Fatal(err) } fmt.Println(checksum(l)) fmt.Println(letterbox(l)) } func getlines(name string) ([]string, error) { f, err := os.Open(name) if err != nil { return nil, err } defer f.Close() l := []string{} s := bufio.NewScanner(f) for s.Scan() { l = append(l, s.Text()) } return l, nil } func checksum(l []string) int { x, y := 0, 0 for _, s := range l { m := histogram(s) a, b := count(m) x, y = x+a, y+b } return x * y } func histogram(s string) map[rune]int { m := make(map[rune]int) for _, r := range s { m[r]++ } return m } func count(m map[rune]int) (int, int) { a, b := 0, 0 for _, v := range m { if v == 2 { a = 1 } else if v == 3 { b = 1 } } return a, b } func letterbox(l []string) string { n := len(l) for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { d, r := diff(l[i], l[j]) if d == 1 { return string(r) } } } return "" } func diff(a, b string) (int, []rune) { r := []rune{} p := []rune(a) q := []rune(b) if len(p) != len(q) { return -1, nil } c := 0 for i := range p { if p[i] != q[i] { c++ } else { r = append(r, p[i]) } } return c, r }
package cluster import ( "fmt" "github.com/pkg/errors" "k8s.io/klog" providerv1 "sigs.k8s.io/cluster-api-provider-openstack/pkg/apis/openstackproviderconfig/v1alpha1" "sigs.k8s.io/cluster-api-provider-openstack/pkg/cloud/openstack" clusterv1 "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1" client "sigs.k8s.io/cluster-api/pkg/client/clientset_generated/clientset/typed/cluster/v1alpha1" ) type Actuator struct { params openstack.ActuatorParams clustersGetter client.ClustersGetter } // NewActuator creates a new Actuator func NewActuator(params openstack.ActuatorParams) (*Actuator, error) { res := &Actuator{params: params} return res, nil } func (a *Actuator) Reconcile(cluster *clusterv1.Cluster) error { klog.Infof("Reconciling cluster %v.", cluster.Name) // Load provider config. _, err := providerv1.ClusterSpecFromProviderSpec(cluster.Spec.ProviderSpec) if err != nil { return errors.Errorf("failed to load cluster provider spec: %v", err) } // Load provider status. _, err = providerv1.ClusterStatusFromProviderStatus(cluster.Status.ProviderStatus) if err != nil { return errors.Errorf("failed to load cluster provider status: %v", err) } /* Uncomment when the clusterGetter is back to working defer func() { if err := a.storeClusterStatus(cluster, status); err != nil { klog.Errorf("failed to store provider status for cluster %q in namespace %q: %v", cluster.Name, cluster.Namespace, err) } }()*/ return nil } // Delete deletes a cluster and is invoked by the Cluster Controller func (a *Actuator) Delete(cluster *clusterv1.Cluster) error { klog.Infof("Deleting cluster %v.", cluster.Name) // Load provider config. _, err := providerv1.ClusterSpecFromProviderSpec(cluster.Spec.ProviderSpec) if err != nil { return errors.Errorf("failed to load cluster provider config: %v", err) } // Load provider status. _, err = providerv1.ClusterStatusFromProviderStatus(cluster.Status.ProviderStatus) if err != nil { return errors.Errorf("failed to load cluster provider status: %v", err) } // Delete other things return nil } func (a *Actuator) storeClusterStatus(cluster *clusterv1.Cluster, status *providerv1.OpenstackClusterProviderStatus) error { clusterClient := a.clustersGetter.Clusters(cluster.Namespace) ext, err := providerv1.EncodeClusterStatus(status) if err != nil { return fmt.Errorf("failed to update cluster status for cluster %q in namespace %q: %v", cluster.Name, cluster.Namespace, err) } cluster.Status.ProviderStatus = ext if _, err := clusterClient.UpdateStatus(cluster); err != nil { return fmt.Errorf("failed to update cluster status for cluster %q in namespace %q: %v", cluster.Name, cluster.Namespace, err) } return nil }
package p06 func checkPossibility(nums []int) bool { i := 0 j := len(nums) - 1 for i < len(nums)-1 && nums[i] <= nums[i+1] { i++ } if i == len(nums)-1 { return true } for j > 0 && nums[j] >= nums[j-1] { j-- } if i == j-1 { if i == 0 || j == len(nums)-1 { return true } if nums[j] >= nums[i-1] { return true } if nums[i] <= nums[j+1] { return true } return false } return false }
package mysqldb import ( "context" "time" ) // TransactionNumber 流水号 type TransactionNumber struct { TransactionDate time.Time `gorm:"primary_key"` // 日期 TransactionNumber int // 流水号 CreatedAt time.Time // 创建时间 UpdatedAt time.Time // 更新时间 } // TableName 返回 TransactionNumber 所在的表名 func (t TransactionNumber) TableName() string { return "transaction_number" } // FindTransactionNumberByCurrentDate 查询流水号 func (d *DbClient) FindTransactionNumberByCurrentDate(ctx context.Context) (*TransactionNumber, error) { var t TransactionNumber now := time.Now().UTC() format := "2006-01-02" d.Model(&TransactionNumber{}).Where("transaction_date = ?", now.Format(format)).Scan(&t) d.Model(&TransactionNumber{}).Where("transaction_date = ?", now.Format(format)).Update(map[string]interface{}{ "transaction_number": t.TransactionNumber + 1, "create_at": now, "updated_at": now, }) return &t, nil } // IsExistTransactionNumberByCurrentDate 流水号是否存在 func (d *DbClient) IsExistTransactionNumberByCurrentDate(ctx context.Context) (bool, error) { var count int now := time.Now().UTC() format := "2006-01-02" d.Model(&TransactionNumber{}).Where("transaction_date = ?", now.Format(format)).Count(&count) return count != 0, nil } // CreateTransactionNumber 创建流水号 func (d *DbClient) CreateTransactionNumber(ctx context.Context) (*TransactionNumber, error) { now := time.Now().UTC() tn := TransactionNumber{ TransactionDate: now, TransactionNumber: 1, CreatedAt: now, UpdatedAt: now, } if err := d.Create(&tn).Error; err != nil { return nil, err } return &tn, nil }
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type RangeTableFuncCol struct { Colname *string TypeName *TypeName ForOrdinality bool IsNotNull bool Colexpr ast.Node Coldefexpr ast.Node Location int } func (n *RangeTableFuncCol) Pos() int { return n.Location }
package controllers import ( "github.com/gin-gonic/gin" ) func Initialize(router *gin.Engine){ api := router.Group("/api") { UserController(api) FriendController(api) } }
package engine import ( "errors" "fmt" "io/ioutil" "log" "os" "os/user" "strings" "github.com/debarshibasak/go-kubeadmclient/kubeadmclient" "github.com/debarshibasak/go-kubeadmclient/kubeadmclient/networking" ) type KubeadmEngine struct { Networking Networking `yaml:"networking" json:"networking"` Masters []*kubeadmclient.MasterNode `yaml:"-" json:"-"` Workers []*kubeadmclient.WorkerNode `yaml:"-" json:"-"` HAProxy *kubeadmclient.HaProxyNode `yaml:"-" json:"-"` ClusterName string `yaml:"-" json:"-"` } type Networking struct { Plugin string `yaml:"plugin" json:"plugin"` PodCidr string `yaml:"podCidr" json:"podCidr"` ServiceCidr string `yaml:"serviceCidr" json:"serviceCidr"` } func (k *KubeadmEngine) AddNode() error { kadmClient := kubeadmclient.Kubeadm{ MasterNodes: []*kubeadmclient.MasterNode{ k.Masters[0], }, WorkerNodes: k.Workers, VerboseMode: true, SkipWorkerFailure: false, } return kadmClient.AddNode() } func (k *KubeadmEngine) DeleteCluster() error { kadmClient := kubeadmclient.Kubeadm{ ClusterName: k.ClusterName, MasterNodes: k.Masters, WorkerNodes: k.Workers, ResetOnDeleteCluster: true, VerboseMode: false, } return kadmClient.DeleteCluster() } func (k *KubeadmEngine) RemoveNode() error { kadmClient := kubeadmclient.Kubeadm{ MasterNodes: k.Masters, WorkerNodes: k.Workers, VerboseMode: false, SkipWorkerFailure: false, } return kadmClient.RemoveNode() } func (k *KubeadmEngine) CreateCluster() error { log.Println("[kubestrike] engine to be used - kubeadm") var networkingPlugin networking.Networking cni := strings.TrimSpace(k.Networking.Plugin) if cni == "" { networkingPlugin = *networking.Flannel } else { v := networking.LookupNetworking(cni) networkingPlugin = *v if networkingPlugin.Name == "" { return errors.New("network plugin in empty") } } kubeadmClient := kubeadmclient.Kubeadm{ ClusterName: k.ClusterName, HaProxyNode: k.HAProxy, MasterNodes: k.Masters, WorkerNodes: k.Workers, VerboseMode: false, Networking: &networkingPlugin, PodNetwork: k.Networking.PodCidr, ServiceNetwork: k.Networking.ServiceCidr, } err := kubeadmClient.CreateCluster() if err != nil { return err } kubeConfig, err := kubeadmClient.GetKubeConfig() if err != nil { return err } u, _ := user.Current() kubeconfigLocation := u.HomeDir + "/.kubeconfig_" + k.ClusterName if err := ioutil.WriteFile(kubeconfigLocation, []byte(kubeConfig), os.FileMode(0777)); err != nil { return err } log.Println("[kubestrike] You can access the cluster now") fmt.Println("") fmt.Println("KUBECONFIG=" + kubeconfigLocation + " kubectl get nodes") return nil }
package main import ( "fmt" "log" "os" "path" diskfs "github.com/diskfs/go-diskfs" "github.com/diskfs/go-diskfs/disk" "github.com/diskfs/go-diskfs/filesystem" "github.com/diskfs/go-diskfs/partition/mbr" ) func check(err error) { if err != nil { log.Fatal(err) } } func CreateFSAndDir(diskImg string) { if diskImg == "" { log.Fatal("must have a valid path for diskImg") } mydisk, err := diskfs.Open(diskImg) if err != nil { var diskSize int64 diskSize = 5 * 1024 * 1024 * 1024 // 5 GB mydisk, err = diskfs.Create(diskImg, diskSize, diskfs.Raw) check(err) } cloudInitSize := 1 * 1024 * 1024 * 1024 // 1 GB cloudInitSectors := uint32(cloudInitSize / 512) // we want to create it at the end of the disk // so find the disk sector count and minus the cloudinit sectors cloudInitStart := uint32(int(mydisk.Size)/512) - cloudInitSectors table := &mbr.Table{ LogicalSectorSize: 512, PhysicalSectorSize: 512, Partitions: []*mbr.Partition{ { Bootable: false, Type: mbr.Linux, Start: cloudInitStart, Size: cloudInitSectors, }, }, } log.Print("Writing partition table to disk") err = mydisk.Partition(table) check(err) fspec := disk.FilesystemSpec{Partition: 1, FSType: filesystem.TypeFat32, VolumeLabel: "config-2"} fs, err := mydisk.CreateFilesystem(fspec) check(err) cloudInitPrefix := path.Join("/", "openstack", "latest") // place down cloud-init info log.Print("Creating cloud init directory structure") err = fs.Mkdir(cloudInitPrefix) if err != nil { log.Fatalf("Error creating cloud init directory structure: %v", err) } } func main() { if len(os.Args) < 2 { fmt.Printf("Usage: %s <outfile>\n", os.Args[0]) os.Exit(1) } CreateFSAndDir(os.Args[1]) }
/* Copyright (C) 2018 Intel Corporation. SPDX-License-Identifier: Apache-2.0 */ package oimcommon import ( "context" "crypto/tls" "crypto/x509" "io/ioutil" "net" "strings" "time" // "github.com/grpc-ecosystem/go-grpc-middleware" // "github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc" // "github.com/opentracing/opentracing-go" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/pkg/errors" ) // GRPCDialer can be used with grpc.WithDialer. It supports // addresses of the format defined for ParseEndpoint. // Necessary because of https://github.com/grpc/grpc-go/issues/1741. func GRPCDialer(endpoint string, t time.Duration) (net.Conn, error) { network, address, err := ParseEndpoint(endpoint) if err != nil { return nil, err } ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(t)) defer cancel() return (&net.Dialer{}).DialContext(ctx, network, address) } // ChooseDialOpts sets certain default options for the given endpoint, // then adds the ones given as additional parameters. For unix:// // endpoints it activates the custom dialer and disables security. func ChooseDialOpts(endpoint string, opts ...grpc.DialOption) []grpc.DialOption { result := []grpc.DialOption{} if strings.HasPrefix(endpoint, "unix://") { result = append(result, grpc.WithDialer(GRPCDialer), ) } // TODO: kubernetes-csi uses grpc.WithBackoffMaxDelay(time.Second), // should we do the same? // Tracing of outgoing calls, including remote and local logging. formatter := StripSecretsFormatter{} // interceptor := grpc_middleware.ChainUnaryClient( // otgrpc.OpenTracingClientInterceptor( // opentracing.GlobalTracer(), // otgrpc.SpanDecorator(TraceGRPCPayload(formatter))), // LogGRPCClient(formatter)) interceptor := LogGRPCClient(formatter) opts = append(opts, grpc.WithUnaryInterceptor(interceptor)) result = append(result, opts...) return result } // LoadTLSConfig sets up the necessary TLS configuration for a // client or server. The peer name must be set when expecting the // peer to offer a certificate with that common name, otherwise it can // be left empty. // // caFile must be the full file name. keyFile can either be the .crt // file (foo.crt, implies foo.key) or the base name (foo for foo.crt // and foo.key). func LoadTLSConfig(caFile, key, peerName string) (*tls.Config, error) { var base string if strings.HasSuffix(key, ".key") || strings.HasSuffix(key, ".crt") { base = key[0 : len(key)-4] } else { base = key } crtFile := base + ".crt" keyFile := base + ".key" certificate, err := tls.LoadX509KeyPair(crtFile, keyFile) if err != nil { return nil, errors.Wrapf(err, "load X509 key pair for key=%q", key) } certPool := x509.NewCertPool() bs, err := ioutil.ReadFile(caFile) // nolint: gosec if err != nil { return nil, errors.Wrap(err, "read CA cert") } ok := certPool.AppendCertsFromPEM(bs) if !ok { return nil, errors.Errorf("failed to append certs from %q", caFile) } tlsConfig := &tls.Config{ ServerName: peerName, // Common name check when connecting to server. VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { // Common name check when accepting a connection from a client. if peerName == "" { // All names allowed. return nil } if len(verifiedChains) == 0 || len(verifiedChains[0]) == 0 { return errors.New("no valid certificate") } commonName := verifiedChains[0][0].Subject.CommonName if commonName != peerName { return errors.Errorf("expected CN %q, got %q", peerName, commonName) } return nil }, Certificates: []tls.Certificate{certificate}, RootCAs: certPool, ClientCAs: certPool, ClientAuth: tls.RequireAndVerifyClientCert, } return tlsConfig, nil } // LoadTLS is identical to LoadTLSConfig except that it returns // the TransportCredentials for a gRPC client or server. func LoadTLS(caFile, key, peerName string) (credentials.TransportCredentials, error) { tlsConfig, err := LoadTLSConfig(caFile, key, peerName) if err != nil { return nil, err } return credentials.NewTLS(tlsConfig), nil }
package config import "github.com/spf13/viper" func init() { viper.SetConfigName("visitor") viper.SetConfigType("yaml") viper.AddConfigPath(".") viper.AddConfigPath("..") viper.AddConfigPath("/etc/visitor") if err := viper.ReadInConfig(); err != nil { panic(err) } }
package main import ( "fmt" "log" "os" "time" bolt "github.com/coreos/bbolt" "github.com/labstack/echo" "github.com/labstack/echo/middleware" _ "github.com/joho/godotenv/autoload" ) func createMux() (*bolt.DB, *echo.Echo) { // Setup Bolt dbPath := os.Getenv("DB_PATH") dbFile := fmt.Sprintf("%s/imascg.db", dbPath) db, err := bolt.Open(dbFile, 0600, nil) if err != nil { log.Fatal(err) } // Setup Echo e := echo.New() e.Use(middleware.CORS()) e.Use(middleware.Logger()) e.Use(middleware.Recover()) e.Use(middleware.Gzip()) return db, e } func main() { ticker := time.NewTicker(time.Hour) go func() { for t := range ticker.C { createBackup(t) } }() defer db.Close() /// Setup target and serve host := os.Getenv("HOST") port := os.Getenv("PORT") target := fmt.Sprintf("%s:%s", host, port) e.Logger.Fatal(e.Start(target)) }
// 数组的组合算法,也是对二维数组的应用。 package main import ( "errors" "fmt" ) // pernutate1 和permutate2方法思想类似。permutate2简化一些,但是最后需要转换成实际的组合。 func main() { s := []int{1, 0, -1, 2, -2} if solution1, err := permutate1(s, 4); err == nil { fmt.Println(solution1) fmt.Println(len(solution1)) } if solution2, err := permutate2(s, 4); err == nil { fmt.Println(solution2) fmt.Println(len(solution2)) } } // 递归完成一个数组中n个元素的组合。根据序列,从小到大生产组合。 // 如C(5,3)。可以用5进制的排序过的3位数表示,各位数字不重复。最小的数字为012,最大的数字为234。 // 从012开始每次加1,当每位达到最大时进位。如124进位后为134,而不是132。 func permutate1(nums []int, n int) ([][]int, error) { lennum := len(nums) if n < 1 || lennum < 1 || lennum < n { return nil, errors.New("传入参数错误") } var solution = [][]int{} topsolution := make([]int, n) sequeSlice1(topsolution, 0) solution = append(solution, topsolution) for k := 0; ; { secondsolution := make([]int, n) if solution[k][0] >= lennum-n { break } k++ copy(secondsolution, solution[k-1]) for j := 0; j < n; j++ { if secondsolution[n-j-1] < lennum-j-1 { secondsolution[n-j-1]++ break } else if secondsolution[n-j-1] == lennum-j-1 { //这里是进位的逻辑,当某位达到最大时,如果前一位没达到最大,则给前一位加1,后面的位顺序设置为前一位加1. if n-j-1 > 0 && secondsolution[n-j-2] < lennum-j-2 { secondsolution[n-j-2]++ sequeSlice1(secondsolution, n-j-2) break } } } //fmt.Println(solution) solution = append(solution, secondsolution) } return solution, nil } // 当i>n时,将array[i+1]的元素设置为array[i]+1, 如传入([1,4,3],1),返回[1,4,5] func sequeSlice1(slice []int, n int) []int { if n < 0 { n = 0 } if n >= len(slice) { return slice } for i := n + 1; i < len(slice); i++ { slice[i] = slice[i-1] + 1 } return slice } // 递归完成一个数组中n个元素的组合。 // 一个集合中的元素可以用1表示选取,0表示未选。 // 如C(5,3),包括组合[11100],[00111] // 1,从右向左找第一个10。进行交换。 // 2,将上次找到10位置右边的1全部移动到左边。 // 3,重复1,2。 func permutate2(nums []int, n int) ([][]int, error) { lennum := len(nums) if n < 1 || lennum < 1 || lennum < n { return nil, errors.New("传入参数错误") } var solution = [][]int{} topsolution := make([]int, lennum) for i := 0; i < lennum; i++ { if i < n { topsolution[i] = 1 } else { topsolution[i] = 0 } } solution = append(solution, topsolution) for k := 0; ; { //fmt.Println(solution) secondsolution := make([]int, lennum) copy(secondsolution, solution[k]) var j int for j = lennum - 1; j > 0; j-- { if secondsolution[j] == 0 && secondsolution[j-1] == 1 { swap(secondsolution, j, j-1) secondsolution = sequeSlice2(secondsolution, j) solution = append(solution, secondsolution) k++ break } } if j <= 0 { break } } return solution, nil } // 将i>n的元素排序。 func sequeSlice2(slice []int, n int) []int { slen := len(slice) if n < 0 { n = 0 } if n >= slen { return slice } for i := n + 1; i < slen; i++ { for j := i + 1; j < slen; j++ { if slice[i] < slice[j] { swap(slice, i, j) } } } return slice } // slice 元素交换 func swap(slice []int, m int, n int) { swap := slice[m] slice[m] = slice[n] slice[n] = swap }
package git import ( "bytes" "fmt" "os" "os/exec" "path/filepath" "strings" "sync" "github.com/abhinav/git-pr/gateway" "go.uber.org/multierr" ) // Gateway is a git gateway. type Gateway struct { mu sync.RWMutex dir string } var _ gateway.Git = (*Gateway)(nil) // NewGateway builds a new Git gateway. func NewGateway(startDir string) (*Gateway, error) { if startDir == "" { dir, err := os.Getwd() if err != nil { return nil, fmt.Errorf( "failed to determine current working directory: %v", err) } startDir = dir } else { dir, err := filepath.Abs(startDir) if err != nil { return nil, fmt.Errorf( "failed to determine absolute path of %v: %v", startDir, err) } startDir = dir } dir := startDir for { _, err := os.Stat(filepath.Join(dir, ".git")) if err == nil { break } newDir := filepath.Dir(dir) if dir == newDir { return nil, fmt.Errorf( "could not find git repository at %v", startDir) } dir = newDir } return &Gateway{dir: dir}, nil } // CurrentBranch determines the current branch name. func (g *Gateway) CurrentBranch() (string, error) { g.mu.RLock() defer g.mu.RUnlock() out, err := g.output("rev-parse", "--abbrev-ref", "HEAD") if err != nil { return "", fmt.Errorf("could not determine current branch: %v", err) } return strings.TrimSpace(out), nil } // DoesBranchExist checks if this branch exists locally. func (g *Gateway) DoesBranchExist(name string) bool { g.mu.RLock() defer g.mu.RUnlock() err := g.cmd("show-ref", "--verify", "--quiet", "refs/heads/"+name).Run() return err == nil } // CreateBranchAndCheckout creates a branch with the given name and head and // switches to it. func (g *Gateway) CreateBranchAndCheckout(name, head string) error { g.mu.Lock() defer g.mu.Unlock() if err := g.cmd("checkout", "-b", name, head).Run(); err != nil { return fmt.Errorf( "failed to create and checkout branch %q at ref %q: %v", name, head, err) } return nil } // CreateBranch creates a branch with the given name and head but does not // check it out. func (g *Gateway) CreateBranch(name, head string) error { g.mu.Lock() defer g.mu.Unlock() if err := g.cmd("branch", name, head).Run(); err != nil { return fmt.Errorf("failed to create branch %q at ref %q: %v", name, head, err) } return nil } // SHA1 gets the SHA1 hash for the given ref. func (g *Gateway) SHA1(ref string) (string, error) { g.mu.RLock() defer g.mu.RUnlock() out, err := g.output("rev-parse", "--verify", "-q", ref) if err != nil { return "", fmt.Errorf("could not resolve ref %q: %v", ref, err) } return strings.TrimSpace(out), nil } // DeleteBranch deletes the given branch. func (g *Gateway) DeleteBranch(name string) error { g.mu.Lock() defer g.mu.Unlock() if err := g.cmd("branch", "-D", name).Run(); err != nil { return fmt.Errorf("failed to delete branch %q: %v", name, err) } return nil } // DeleteRemoteTrackingBranch deletes the remote tracking branch with the // given name. func (g *Gateway) DeleteRemoteTrackingBranch(remote, name string) error { g.mu.Lock() defer g.mu.Unlock() if err := g.cmd("branch", "-dr", remote+"/"+name).Run(); err != nil { return fmt.Errorf("failed to delete remote tracking branch %q: %v", name, err) } return nil } // Checkout checks the given branch out. func (g *Gateway) Checkout(name string) error { g.mu.Lock() defer g.mu.Unlock() if err := g.cmd("checkout", name).Run(); err != nil { err = fmt.Errorf("failed to checkout branch %q: %v", name, err) } return nil } // Fetch a git ref func (g *Gateway) Fetch(req *gateway.FetchRequest) error { ref := req.RemoteRef if req.LocalRef != "" { ref = ref + ":" + req.LocalRef } g.mu.Lock() defer g.mu.Unlock() if err := g.cmd("fetch", req.Remote, ref).Run(); err != nil { return fmt.Errorf("failed to fetch %q from %q: %v", ref, req.Remote, err) } return nil } // Push pushes refs to a remote. func (g *Gateway) Push(req *gateway.PushRequest) error { if len(req.Refs) == 0 { return nil } args := append(make([]string, 0, len(req.Refs)+2), "push") if req.Force { args = append(args, "-f") } args = append(args, req.Remote) for ref, remote := range req.Refs { if remote != "" { ref = ref + ":" + remote } args = append(args, ref) } g.mu.Lock() defer g.mu.Unlock() if err := g.cmd(args...).Run(); err != nil { return fmt.Errorf("failed to push refs to %q: %v", req.Remote, err) } return nil } // Pull pulls the given branch. func (g *Gateway) Pull(remote, name string) error { g.mu.Lock() defer g.mu.Unlock() if err := g.cmd("pull", remote, name).Run(); err != nil { return fmt.Errorf("failed to pull %q from %q: %v", name, remote, err) } return nil } // Rebase a branch. func (g *Gateway) Rebase(req *gateway.RebaseRequest) error { var _args [5]string args := append(_args[:0], "rebase") if req.Onto != "" { args = append(args, "--onto", req.Onto) } if req.From != "" { args = append(args, req.From) } args = append(args, req.Branch) g.mu.Lock() defer g.mu.Unlock() if err := g.cmd(args...).Run(); err != nil { return multierr.Append( fmt.Errorf("failed to rebase %q: %v", req.Branch, err), // If this failed, abort the rebase so that we're not left in a // bad state. g.cmd("rebase", "--abort").Run(), ) } return nil } // ResetBranch resets the given branch to the given head. func (g *Gateway) ResetBranch(branch, head string) error { curr, err := g.CurrentBranch() if err != nil { return fmt.Errorf("could not reset %q to %q: %v", branch, head, err) } g.mu.Lock() defer g.mu.Unlock() if curr == branch { err = g.cmd("reset", "--hard", head).Run() } else { err = g.cmd("branch", "-f", branch, head).Run() } if err != nil { err = fmt.Errorf("could not reset %q to %q: %v", branch, head, err) } return err } // RemoteURL gets the URL for the given remote. func (g *Gateway) RemoteURL(name string) (string, error) { g.mu.RLock() defer g.mu.RUnlock() out, err := g.output("remote", "get-url", name) if err != nil { return "", fmt.Errorf("failed to get URL for remote %q: %v", name, err) } return strings.TrimSpace(out), nil } // run the given git command. func (g *Gateway) cmd(args ...string) *exec.Cmd { cmd := exec.Command("git", args...) cmd.Dir = g.dir cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout return cmd } func (g *Gateway) output(args ...string) (string, error) { var stdout bytes.Buffer cmd := g.cmd(args...) cmd.Stdout = &stdout err := cmd.Run() return stdout.String(), err }
package rp_kit import ( "time" ) const ( DATETIME_LAYOUT = "2006-01-02 15:04:05" DATE_LAYOUT = "2006-01-02" DATE_LAYOUT_SHORT_CN = "01月02日" DATE_LAYOUT_SHORT_EN = "01-02" TIME_LAYOUT = "15:04:05" TIME_LAYOUT_SHORT = "15:04" ) //获取当前标准格式时间 func GetTimeNow(time2 ...time.Time) string { if len(time2) == 0 { return time.Now().Format(DATETIME_LAYOUT) } return time2[0].Format(DATETIME_LAYOUT) }
// Copyright 2020 orivil.com. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found at https://mit-license.org. package modes import ( "github.com/orivil/morgine/utils/sql" "time" ) type Book struct { ID int PtID int `gorm:"index"` PtBookID int `gorm:"index"` Title string `gorm:"index"` Desc string Pic string Author string `gorm:"index"` CreatedAt *time.Time `gorm:"index"` Finished sql.Boolean `gorm:"index"` Forbidden sql.Boolean `gorm:"index"` } func CreateBook(book *Book) error { return db.Create(book).Error } func UpdateBook(book *Book) { }
package popcount import ( "testing" ) func bench(b *testing.B, f func(uint64) int) { for i := 0; i < b.N; i++ { f(uint64(i)) } } func BenchmarkTable(b *testing.B) { bench(b, PopCountTable) } func BenchmarkTableLoop(b *testing.B) { bench(b, PopCountTableLoop) } func BenchmarkShiftValue(b *testing.B) { bench(b, PopCountShiftValue) } func BenchmarkClearRightmost(b *testing.B) { bench(b, PopCountClearRightmost) }
package helper import ( "log" "net/http" "github.com/PuerkitoBio/goquery" ) // BookScraper is... func Scraper() []string { url := "https://www.penguin.co.uk/articles/2018/100-must-read-classic-books.html" res, err := http.Get(url) if err != nil { log.Fatal(err) } defer res.Body.Close() if res.StatusCode != 200 { log.Fatalf("error: %d, status:, %s", res.StatusCode, res.Status) } doc, err := goquery.NewDocumentFromReader(res.Body) if err != nil { log.Fatal(err) } var title []string // var title []string doc.Find(".bookCard__wrapper").Each(func(i int, sel *goquery.Selection) { text := sel.Find("h5").Text() title = append(title, text) }) return title }
package taxjar type Category struct { Name string `json:"name"` ProductTaxCode string `json:"product_tax_code"` Description string `json:"description"` } type CategoryList struct { Categories []Category `json:"categories"` } type categoryListParams struct{} type CategoryService struct { Repository CategoryRepository } // List all Categories func (s *CategoryService) List() (CategoryList, error) { return s.Repository.list(categoryListParams{}) }
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger import ( "net/url" "strings" "encoding/json" "fmt" ) type UniverseApi struct { Configuration *Configuration } func NewUniverseApi() *UniverseApi { configuration := NewConfiguration() return &UniverseApi{ Configuration: configuration, } } func NewUniverseApiWithBasePath(basePath string) *UniverseApi { configuration := NewConfiguration() configuration.BasePath = basePath return &UniverseApi{ Configuration: configuration, } } /** * Get bloodlines * Get a list of bloodlines --- Alternate route: &#x60;/v1/universe/bloodlines/&#x60; Alternate route: &#x60;/legacy/universe/bloodlines/&#x60; Alternate route: &#x60;/dev/universe/bloodlines/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []GetUniverseBloodlines200Ok */ func (a UniverseApi) GetUniverseBloodlines(datasource string, language string, userAgent string, xUserAgent string) ([]GetUniverseBloodlines200Ok, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/bloodlines/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]GetUniverseBloodlines200Ok) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseBloodlines", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get item categories * Get a list of item categories --- Alternate route: &#x60;/v1/universe/categories/&#x60; Alternate route: &#x60;/legacy/universe/categories/&#x60; Alternate route: &#x60;/dev/universe/categories/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []int32 */ func (a UniverseApi) GetUniverseCategories(datasource string, userAgent string, xUserAgent string) ([]int32, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/categories/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]int32) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseCategories", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get item category information * Get information of an item category --- Alternate route: &#x60;/v1/universe/categories/{category_id}/&#x60; Alternate route: &#x60;/legacy/universe/categories/{category_id}/&#x60; Alternate route: &#x60;/dev/universe/categories/{category_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param categoryId An Eve item category ID * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseCategoriesCategoryIdOk */ func (a UniverseApi) GetUniverseCategoriesCategoryId(categoryId int32, datasource string, language string, userAgent string, xUserAgent string) (*GetUniverseCategoriesCategoryIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/categories/{category_id}/" localVarPath = strings.Replace(localVarPath, "{"+"category_id"+"}", fmt.Sprintf("%v", categoryId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseCategoriesCategoryIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseCategoriesCategoryId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get constellations * Get a list of constellations --- Alternate route: &#x60;/v1/universe/constellations/&#x60; Alternate route: &#x60;/legacy/universe/constellations/&#x60; Alternate route: &#x60;/dev/universe/constellations/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []int32 */ func (a UniverseApi) GetUniverseConstellations(datasource string, userAgent string, xUserAgent string) ([]int32, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/constellations/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]int32) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseConstellations", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get constellation information * Get information on a constellation --- Alternate route: &#x60;/v1/universe/constellations/{constellation_id}/&#x60; Alternate route: &#x60;/legacy/universe/constellations/{constellation_id}/&#x60; Alternate route: &#x60;/dev/universe/constellations/{constellation_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param constellationId constellation_id integer * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseConstellationsConstellationIdOk */ func (a UniverseApi) GetUniverseConstellationsConstellationId(constellationId int32, datasource string, language string, userAgent string, xUserAgent string) (*GetUniverseConstellationsConstellationIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/constellations/{constellation_id}/" localVarPath = strings.Replace(localVarPath, "{"+"constellation_id"+"}", fmt.Sprintf("%v", constellationId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseConstellationsConstellationIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseConstellationsConstellationId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get factions * Get a list of factions --- Alternate route: &#x60;/v1/universe/factions/&#x60; Alternate route: &#x60;/legacy/universe/factions/&#x60; Alternate route: &#x60;/dev/universe/factions/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []GetUniverseFactions200Ok */ func (a UniverseApi) GetUniverseFactions(datasource string, language string, userAgent string, xUserAgent string) ([]GetUniverseFactions200Ok, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/factions/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]GetUniverseFactions200Ok) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseFactions", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get graphics * Get a list of graphics --- Alternate route: &#x60;/v1/universe/graphics/&#x60; Alternate route: &#x60;/legacy/universe/graphics/&#x60; Alternate route: &#x60;/dev/universe/graphics/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []int32 */ func (a UniverseApi) GetUniverseGraphics(datasource string, userAgent string, xUserAgent string) ([]int32, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/graphics/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]int32) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseGraphics", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get graphic information * Get information on a graphic --- Alternate route: &#x60;/v1/universe/graphics/{graphic_id}/&#x60; Alternate route: &#x60;/legacy/universe/graphics/{graphic_id}/&#x60; Alternate route: &#x60;/dev/universe/graphics/{graphic_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param graphicId graphic_id integer * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseGraphicsGraphicIdOk */ func (a UniverseApi) GetUniverseGraphicsGraphicId(graphicId int32, datasource string, userAgent string, xUserAgent string) (*GetUniverseGraphicsGraphicIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/graphics/{graphic_id}/" localVarPath = strings.Replace(localVarPath, "{"+"graphic_id"+"}", fmt.Sprintf("%v", graphicId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseGraphicsGraphicIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseGraphicsGraphicId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get item groups * Get a list of item groups --- Alternate route: &#x60;/v1/universe/groups/&#x60; Alternate route: &#x60;/legacy/universe/groups/&#x60; Alternate route: &#x60;/dev/universe/groups/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param page Which page to query * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []int32 */ func (a UniverseApi) GetUniverseGroups(datasource string, page int32, userAgent string, xUserAgent string) ([]int32, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/groups/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("page", a.Configuration.APIClient.ParameterToString(page, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]int32) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseGroups", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get item group information * Get information on an item group --- Alternate route: &#x60;/v1/universe/groups/{group_id}/&#x60; Alternate route: &#x60;/legacy/universe/groups/{group_id}/&#x60; Alternate route: &#x60;/dev/universe/groups/{group_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param groupId An Eve item group ID * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseGroupsGroupIdOk */ func (a UniverseApi) GetUniverseGroupsGroupId(groupId int32, datasource string, language string, userAgent string, xUserAgent string) (*GetUniverseGroupsGroupIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/groups/{group_id}/" localVarPath = strings.Replace(localVarPath, "{"+"group_id"+"}", fmt.Sprintf("%v", groupId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseGroupsGroupIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseGroupsGroupId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get moon information * Get information on a moon --- Alternate route: &#x60;/v1/universe/moons/{moon_id}/&#x60; Alternate route: &#x60;/legacy/universe/moons/{moon_id}/&#x60; Alternate route: &#x60;/dev/universe/moons/{moon_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param moonId moon_id integer * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseMoonsMoonIdOk */ func (a UniverseApi) GetUniverseMoonsMoonId(moonId int32, datasource string, userAgent string, xUserAgent string) (*GetUniverseMoonsMoonIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/moons/{moon_id}/" localVarPath = strings.Replace(localVarPath, "{"+"moon_id"+"}", fmt.Sprintf("%v", moonId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseMoonsMoonIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseMoonsMoonId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get planet information * Get information on a planet --- Alternate route: &#x60;/v1/universe/planets/{planet_id}/&#x60; Alternate route: &#x60;/legacy/universe/planets/{planet_id}/&#x60; Alternate route: &#x60;/dev/universe/planets/{planet_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param planetId planet_id integer * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniversePlanetsPlanetIdOk */ func (a UniverseApi) GetUniversePlanetsPlanetId(planetId int32, datasource string, userAgent string, xUserAgent string) (*GetUniversePlanetsPlanetIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/planets/{planet_id}/" localVarPath = strings.Replace(localVarPath, "{"+"planet_id"+"}", fmt.Sprintf("%v", planetId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniversePlanetsPlanetIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniversePlanetsPlanetId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get character races * Get a list of character races --- Alternate route: &#x60;/v1/universe/races/&#x60; Alternate route: &#x60;/legacy/universe/races/&#x60; Alternate route: &#x60;/dev/universe/races/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []GetUniverseRaces200Ok */ func (a UniverseApi) GetUniverseRaces(datasource string, language string, userAgent string, xUserAgent string) ([]GetUniverseRaces200Ok, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/races/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]GetUniverseRaces200Ok) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseRaces", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get regions * Get a list of regions --- Alternate route: &#x60;/v1/universe/regions/&#x60; Alternate route: &#x60;/legacy/universe/regions/&#x60; Alternate route: &#x60;/dev/universe/regions/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []int32 */ func (a UniverseApi) GetUniverseRegions(datasource string, userAgent string, xUserAgent string) ([]int32, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/regions/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]int32) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseRegions", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get region information * Get information on a region --- Alternate route: &#x60;/v1/universe/regions/{region_id}/&#x60; Alternate route: &#x60;/legacy/universe/regions/{region_id}/&#x60; Alternate route: &#x60;/dev/universe/regions/{region_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param regionId region_id integer * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseRegionsRegionIdOk */ func (a UniverseApi) GetUniverseRegionsRegionId(regionId int32, datasource string, language string, userAgent string, xUserAgent string) (*GetUniverseRegionsRegionIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/regions/{region_id}/" localVarPath = strings.Replace(localVarPath, "{"+"region_id"+"}", fmt.Sprintf("%v", regionId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseRegionsRegionIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseRegionsRegionId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get stargate information * Get information on a stargate --- Alternate route: &#x60;/v1/universe/stargates/{stargate_id}/&#x60; Alternate route: &#x60;/legacy/universe/stargates/{stargate_id}/&#x60; Alternate route: &#x60;/dev/universe/stargates/{stargate_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param stargateId stargate_id integer * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseStargatesStargateIdOk */ func (a UniverseApi) GetUniverseStargatesStargateId(stargateId int32, datasource string, userAgent string, xUserAgent string) (*GetUniverseStargatesStargateIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/stargates/{stargate_id}/" localVarPath = strings.Replace(localVarPath, "{"+"stargate_id"+"}", fmt.Sprintf("%v", stargateId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseStargatesStargateIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseStargatesStargateId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get station information * Get information on a station --- Alternate route: &#x60;/v2/universe/stations/{station_id}/&#x60; Alternate route: &#x60;/dev/universe/stations/{station_id}/&#x60; --- This route is cached for up to 300 seconds * * @param stationId station_id integer * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseStationsStationIdOk */ func (a UniverseApi) GetUniverseStationsStationId(stationId int32, datasource string, userAgent string, xUserAgent string) (*GetUniverseStationsStationIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/stations/{station_id}/" localVarPath = strings.Replace(localVarPath, "{"+"station_id"+"}", fmt.Sprintf("%v", stationId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseStationsStationIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseStationsStationId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * List all public structures * List all public structures --- Alternate route: &#x60;/v1/universe/structures/&#x60; Alternate route: &#x60;/legacy/universe/structures/&#x60; Alternate route: &#x60;/dev/universe/structures/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []int64 */ func (a UniverseApi) GetUniverseStructures(datasource string, userAgent string, xUserAgent string) ([]int64, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/structures/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]int64) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseStructures", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get structure information * Returns information on requested structure, if you are on the ACL. Otherwise, returns \&quot;Forbidden\&quot; for all inputs. --- Alternate route: &#x60;/v1/universe/structures/{structure_id}/&#x60; Alternate route: &#x60;/legacy/universe/structures/{structure_id}/&#x60; Alternate route: &#x60;/dev/universe/structures/{structure_id}/&#x60; * * @param structureId An Eve structure ID * @param datasource The server name you would like data from * @param token Access token to use, if preferred over a header * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseStructuresStructureIdOk */ func (a UniverseApi) GetUniverseStructuresStructureId(structureId int64, datasource string, token string, userAgent string, xUserAgent string) (*GetUniverseStructuresStructureIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/structures/{structure_id}/" localVarPath = strings.Replace(localVarPath, "{"+"structure_id"+"}", fmt.Sprintf("%v", structureId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // authentication '(evesso)' required // oauth required if a.Configuration.AccessToken != ""{ localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("token", a.Configuration.APIClient.ParameterToString(token, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseStructuresStructureIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseStructuresStructureId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get solar systems * Get a list of solar systems --- Alternate route: &#x60;/v1/universe/systems/&#x60; Alternate route: &#x60;/legacy/universe/systems/&#x60; Alternate route: &#x60;/dev/universe/systems/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []int32 */ func (a UniverseApi) GetUniverseSystems(datasource string, userAgent string, xUserAgent string) ([]int32, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/systems/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]int32) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseSystems", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get solar system information * Get information on a solar system --- Alternate route: &#x60;/v2/universe/systems/{system_id}/&#x60; Alternate route: &#x60;/dev/universe/systems/{system_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param systemId system_id integer * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseSystemsSystemIdOk */ func (a UniverseApi) GetUniverseSystemsSystemId(systemId int32, datasource string, language string, userAgent string, xUserAgent string) (*GetUniverseSystemsSystemIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/systems/{system_id}/" localVarPath = strings.Replace(localVarPath, "{"+"system_id"+"}", fmt.Sprintf("%v", systemId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseSystemsSystemIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseSystemsSystemId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get types * Get a list of type ids --- Alternate route: &#x60;/v1/universe/types/&#x60; Alternate route: &#x60;/legacy/universe/types/&#x60; Alternate route: &#x60;/dev/universe/types/&#x60; --- This route is cached for up to 3600 seconds * * @param datasource The server name you would like data from * @param page Which page to query * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []int32 */ func (a UniverseApi) GetUniverseTypes(datasource string, page int32, userAgent string, xUserAgent string) ([]int32, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/types/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("page", a.Configuration.APIClient.ParameterToString(page, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new([]int32) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseTypes", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err } /** * Get type information * Get information on a type --- Alternate route: &#x60;/v2/universe/types/{type_id}/&#x60; --- This route is cached for up to 3600 seconds * * @param typeId An Eve item type ID * @param datasource The server name you would like data from * @param language Language to use in the response * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return *GetUniverseTypesTypeIdOk */ func (a UniverseApi) GetUniverseTypesTypeId(typeId int32, datasource string, language string, userAgent string, xUserAgent string) (*GetUniverseTypesTypeIdOk, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/types/{type_id}/" localVarPath = strings.Replace(localVarPath, "{"+"type_id"+"}", fmt.Sprintf("%v", typeId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("language", a.Configuration.APIClient.ParameterToString(language, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") var successPayload = new(GetUniverseTypesTypeIdOk) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "GetUniverseTypesTypeId", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return successPayload, localVarAPIResponse, err } /** * Get names and categories for a set of ID&#39;s * Resolve a set of IDs to names and categories. Supported ID&#39;s for resolving are: Characters, Corporations, Alliances, Stations, Solar Systems, Constellations, Regions, Types. --- Alternate route: &#x60;/v2/universe/names/&#x60; Alternate route: &#x60;/dev/universe/names/&#x60; * * @param ids The ids to resolve * @param datasource The server name you would like data from * @param userAgent Client identifier, takes precedence over headers * @param xUserAgent Client identifier, takes precedence over User-Agent * @return []PostUniverseNames200Ok */ func (a UniverseApi) PostUniverseNames(ids []int32, datasource string, userAgent string, xUserAgent string) ([]PostUniverseNames200Ok, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Post") // create path and map variables localVarPath := a.Configuration.BasePath + "/universe/names/" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := make(map[string]string) var localVarPostBody interface{} var localVarFileName string var localVarFileBytes []byte // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } localVarQueryParams.Add("datasource", a.Configuration.APIClient.ParameterToString(datasource, "")) localVarQueryParams.Add("user_agent", a.Configuration.APIClient.ParameterToString(userAgent, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // header params "X-User-Agent" localVarHeaderParams["X-User-Agent"] = a.Configuration.APIClient.ParameterToString(xUserAgent, "") // body params localVarPostBody = &ids var successPayload = new([]PostUniverseNames200Ok) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() var localVarAPIResponse = &APIResponse{Operation: "PostUniverseNames", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { return *successPayload, localVarAPIResponse, err } err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) return *successPayload, localVarAPIResponse, err }
package main import "fmt" func main() { <<<<<<< HEAD fmt.Println("hey hey hey") ======= fmt.Println("hey") >>>>>>> 940aeb5dcd3c44eddf54018f79a6c1bc55d1eab9 }
// Copyright 2016-2017 The psh Authors. All rights reserved. package psh import ( "bytes" "fmt" ) const ( // SegmentHostnameBackground is the background color to use SegmentHostnameBackground = 238 // #444444 ) // SegmentHostname implements the hostname partial of the prompt. // // It renders the current hostname up to the first '.' // // TODO: // * Add support for long/conmplete hostname. type SegmentHostname struct { Data []byte } // NewSegmentHostname creates an instace of SegmentHostname type. func NewSegmentHostname() *SegmentHostname { segment := &SegmentHostname{} return segment } // Compile collects the data for this segment. func (s *SegmentHostname) Compile() { s.Data = []byte("\\h") } // Render renders the segment results. func (s *SegmentHostname) Render() []byte { var b bytes.Buffer if len(s.Data) != 0 { b.Write(SetBackground(SegmentHostnameBackground)) fmt.Fprint(&b, " ") b.Write(s.Data) fmt.Fprint(&b, " ") } return b.Bytes() }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 nmble import ( "fmt" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/runtimeco/go-coap" . "mynewt.apache.org/newtmgr/nmxact/bledefs" "mynewt.apache.org/newtmgr/nmxact/nmxutil" "mynewt.apache.org/newtmgr/nmxact/scan" "mynewt.apache.org/newtmgr/nmxact/sesn" "mynewt.apache.org/newtmgr/nmxact/xact" ) const scanRetryRate = time.Second // Implements scan.Scanner. type BleScanner struct { cfg scan.Cfg bx *BleXport scanBlocker nmxutil.Blocker suspendBlocker nmxutil.Blocker mtx sync.Mutex // Protected by the mutex. discoverer *Discoverer reportedDevs map[BleDev]string failedDevs map[BleDev]struct{} ses *BleSesn enabled bool } func NewBleScanner(bx *BleXport) *BleScanner { return &BleScanner{ bx: bx, reportedDevs: map[BleDev]string{}, failedDevs: map[BleDev]struct{}{}, } } func (s *BleScanner) isEnabled() bool { s.mtx.Lock() defer s.mtx.Unlock() return s.enabled } // Performs a compare-and-swap of the enabled state. func (s *BleScanner) toggleEnabled(to bool) bool { s.mtx.Lock() defer s.mtx.Unlock() if s.enabled == to { return false } s.enabled = to return true } func (s *BleScanner) setDiscoverer(d *Discoverer) { s.mtx.Lock() defer s.mtx.Unlock() s.discoverer = d } func (s *BleScanner) setSession(ses *BleSesn) { s.mtx.Lock() defer s.mtx.Unlock() nmxutil.Assert(s.ses == nil || ses == nil) s.ses = ses } func (s *BleScanner) addReportedDev(dev BleDev, hwid string) { s.mtx.Lock() defer s.mtx.Unlock() s.reportedDevs[dev] = hwid } func (s *BleScanner) addFailedDev(dev BleDev) { s.mtx.Lock() defer s.mtx.Unlock() s.failedDevs[dev] = struct{}{} } func (s *BleScanner) discover() (*BleDev, error) { s.setDiscoverer(NewDiscoverer(DiscovererParams{ Bx: s.bx, OwnAddrType: s.cfg.SesnCfg.Ble.OwnAddrType, Passive: false, Duration: 15 * time.Second, })) defer s.setDiscoverer(nil) var dev *BleDev advRptCb := func(r BleAdvReport) { if s.cfg.Ble.ScanPred(r) { s.mtx.Lock() defer s.mtx.Unlock() dev = &r.Sender s.discoverer.Stop() } } if err := s.discoverer.Start(advRptCb); err != nil { return nil, err } return dev, nil } func (s *BleScanner) connect(dev BleDev) error { s.cfg.SesnCfg.PeerSpec.Ble = dev ses, err := NewBleSesn(s.bx, s.cfg.SesnCfg, MASTER_PRIO_SCAN) if err != nil { return err } s.setSession(ses) if err := s.ses.Open(); err != nil { s.setSession(nil) return err } return nil } func (s *BleScanner) readHwId() (string, error) { c := xact.NewGetResCmd() c.Path = "dev" c.Typ = sesn.RES_TYPE_PUBLIC res, err := c.Run(s.ses) if err != nil { return "", fmt.Errorf("failed to read hardware ID; %s", err.Error()) } cres := res.(*xact.GetResResult) if cres.Code != coap.Content { return "", fmt.Errorf("failed to read hardware ID; CoAP status=%s", cres.Code.String()) } m, err := nmxutil.DecodeCborMap(cres.Value) if err != nil { return "", fmt.Errorf("failed to read hardware ID; %s", err.Error()) } itf := m["hwid"] if itf == nil { return "", fmt.Errorf("failed to read hardware ID; \"hwid\" " + "item missing from dev resource") } str, ok := itf.(string) if !ok { return "", fmt.Errorf("failed to read hardware ID; invalid \"hwid\" "+ "item: %#v", itf) } return str, nil } func (s *BleScanner) scan() (*scan.ScanPeer, error) { // Ensure subsequent calls to suspend() block until scanning has stopped. s.scanBlocker.Start() defer s.scanBlocker.Unblock(nil) // Discover the first device which matches the specified predicate. dev, err := s.discover() if err != nil { return nil, err } if dev == nil { return nil, nil } if err := s.connect(*dev); err != nil { return nil, err } defer func() { s.ses.Close() s.setSession(nil) }() // Now that we have successfully connected to this device, we will report // it regardless of success or failure. peer := scan.ScanPeer{ HwId: "", PeerSpec: sesn.PeerSpec{ Ble: *dev, }, } hwId, err := s.readHwId() if err != nil { return &peer, err } peer.HwId = hwId return &peer, nil } // Caller must lock mutex. func (s *BleScanner) seenDevice(dev BleDev) bool { s.mtx.Lock() defer s.mtx.Unlock() if _, ok := s.reportedDevs[dev]; ok { return true } if _, ok := s.failedDevs[dev]; ok { return true } return false } func (s *BleScanner) Start(cfg scan.Cfg) error { if !s.toggleEnabled(true) { return nmxutil.NewAlreadyError("Attempt to start BLE scanner twice") } // Wrap predicate with logic that discards duplicates. innerPred := cfg.Ble.ScanPred cfg.Ble.ScanPred = func(adv BleAdvReport) bool { // Filter devices that have already been reported. if s.seenDevice(adv.Sender) { return false } else { return innerPred(adv) } } s.cfg = cfg // Start background scanning. go func() { for { // Wait for suspend-in-progress to complete, if any. s.suspendBlocker.Wait(nmxutil.DURATION_FOREVER, nil) if !s.isEnabled() { break } p, err := s.scan() if err != nil { log.Debugf("Scan error: %s", err.Error()) if p != nil { s.addFailedDev(p.PeerSpec.Ble) } time.Sleep(scanRetryRate) } else if p != nil { s.addReportedDev(p.PeerSpec.Ble, p.HwId) s.cfg.ScanCb(*p) } } }() return nil } func (s *BleScanner) suspend() error { s.suspendBlocker.Start() defer s.suspendBlocker.Unblock(nil) discoverer := s.discoverer ses := s.ses if discoverer != nil { discoverer.Stop() } if ses != nil { ses.Close() } // Block until scan is fully terminated. s.scanBlocker.Wait(nmxutil.DURATION_FOREVER, nil) s.discoverer = nil s.ses = nil return nil } // Aborts the current scan but leaves the scanner enabled. This function is // called when a higher priority procedure (e.g., connecting) needs to acquire // master privileges. When the high priority procedures are complete, scanning // will resume. func (s *BleScanner) Preempt() error { return s.suspend() } // Stops the scanner. Scanning won't resume unless Start() gets called. func (s *BleScanner) Stop() error { if !s.toggleEnabled(false) { return nmxutil.NewAlreadyError("Attempt to stop BLE scanner twice") } return s.suspend() } // @return true if the specified device was found and // forgetten; // false if the specified device is unknown. func (s *BleScanner) ForgetDevice(hwId string) bool { s.mtx.Lock() defer s.mtx.Unlock() for discoverer, h := range s.reportedDevs { if h == hwId { delete(s.reportedDevs, discoverer) return true } } return false } func (s *BleScanner) ForgetAllDevices() { s.mtx.Lock() defer s.mtx.Unlock() for discoverer, _ := range s.reportedDevs { delete(s.reportedDevs, discoverer) } for discoverer, _ := range s.failedDevs { delete(s.failedDevs, discoverer) } }
//go:generate pkger -o cmd/bofhchan package main import ( "github.com/gofiber/fiber" "github.com/gofiber/template/html" "github.com/imdario/BOFHchan/internal/post" "github.com/markbates/pkger" ) var ( mode = "debug" ) func main() { app := fiber.New(&fiber.Settings{ Views: views(), }) post.RegisterURLs(app) if err := app.Listen(3000); err != nil { panic(err) } } func views() fiber.Views { dir := pkger.Dir("/templates") engine := html.NewFileSystem(dir, ".html") if mode == "debug" { engine.Debug(true) engine.Reload(true) } return engine }
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02900101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.029.001.01 Document"` Message *ResolutionOfInvestigation `xml:"camt.029.001.01"` } func (d *Document02900101) AddMessage() *ResolutionOfInvestigation { d.Message = new(ResolutionOfInvestigation) return d.Message } // Scope // The Resolution Of Investigation message is sent by a case assignee to a case creator/case assigner. // This message is used to inform of the resolution of a case, and optionally provides details about . // - the corrective action undertaken by the case assignee // - information on the return where applicable // Usage // The Resolution Of Investigation message is used by the case assignee to inform a case creator or case assigner about the resolution of a: // - request to cancel payment case // - request to modify payment case // - unable to apply case // - claim non receipt case // The Resolution Of Investigation message covers one and only one case at a time. If the case assignee needs to communicate about several cases, then several Resolution Of Investigation messages must be sent. // The Resolution Of Investigation message provides: // - the final outcome of the case, whether positive or negative // - optionally, the details of the corrective action undertaken by the case assignee and the information of the return // Whenever a payment instruction has been generated to solve the case under investigation, the optional CorrectionTransaction component present in the message must be completed. // Whenever the action of modifying or cancelling a payment results in funds being returned, an investigating agent may attached some details in this message. These details facilitates the account reconciliations at the initiating bank and the intermediaries. It must be stressed that returning of funds is outside the scope of this Exceptions and Investigation service. The features given here is only meant to transmit the information of returns when it is available. // The Resolution Of Investigation message must // - be forwarded by all subsequent case assignee(s) until it reaches the case creator // - not be used in place of a Reject Case Assignment or Case Status Report or Notification Of Case Assignment message. // Take note of an exceptional rule that allows the use of Resolution Of Investigation in lieu of a Case Status Report. Case Status Report is a response-message to a Case Status Report Request. The latter which is sent when the assigner has waited too long (by his standard) for an answer. However it may happen that when the Request arrives, the investigating agent has just obtained a resolution. In such a situation, it would be redundant to send a Case Status Report when then followed immediately by a Resolution Of Investigation. It is therefore quite acceptable for the investigating agent, the assignee, to skip the Case Status Report and send the Resolution Of Investigation message directly. type ResolutionOfInvestigation struct { // Note: the Assigner must be the sender of this confirmation and the Assignee must be the receiver. Assignment *iso20022.CaseAssignment `xml:"Assgnmt"` // Identifies a resolved case. ResolvedCase *iso20022.Case `xml:"RslvdCase"` // Indicates the status of the investigation. Status *iso20022.InvestigationStatusChoice `xml:"Sts,omitempty"` // References a transaction intitiated to fix the case under investigation. CorrectionTransaction *iso20022.PaymentInstructionExtract `xml:"CrrctnTx,omitempty"` } func (r *ResolutionOfInvestigation) AddAssignment() *iso20022.CaseAssignment { r.Assignment = new(iso20022.CaseAssignment) return r.Assignment } func (r *ResolutionOfInvestigation) AddResolvedCase() *iso20022.Case { r.ResolvedCase = new(iso20022.Case) return r.ResolvedCase } func (r *ResolutionOfInvestigation) AddStatus() *iso20022.InvestigationStatusChoice { r.Status = new(iso20022.InvestigationStatusChoice) return r.Status } func (r *ResolutionOfInvestigation) AddCorrectionTransaction() *iso20022.PaymentInstructionExtract { r.CorrectionTransaction = new(iso20022.PaymentInstructionExtract) return r.CorrectionTransaction }
package protocol_test import ( "encoding/hex" "strings" "testing" "time" // Frameworks "github.com/djthorpe/gopi" "github.com/djthorpe/sensors" // Modules _ "github.com/djthorpe/gopi/sys/logger" _ "github.com/djthorpe/sensors/protocol/ook" ) func Test_OOK_000(t *testing.T) { // Create an OOK module if app, err := gopi.NewAppInstance(gopi.NewAppConfig("sensors/protocol/ook")); err != nil { t.Fatal(err) } else if _, ok := app.ModuleInstance("sensors/protocol/ook").(sensors.OOKProto); ok == false { t.Fatal("OOK does not comply to OOK interface") } } func Test_OOK_001(t *testing.T) { if ook := OOK(); ook == nil { t.Fatal("Missing OOK module") } else if _, err := ook.New(0x12345, 0, false, nil); err != nil { t.Fatal(err) } } func Test_OOK_002(t *testing.T) { if ook := OOK(); ook == nil { t.Fatal("Missing OOK module") } else if _, err := ook.New(0x112345, 0, false, nil); err == nil { t.Fatal("Expected parameter error due to bad address") } else if _, err := ook.New(0x12345, 5, false, nil); err == nil { t.Fatal("Expected parameter error due to bad socket") } } func Test_OOK_003(t *testing.T) { if ook := OOK(); ook == nil { t.Fatal("Missing OOK module") } else { for addr := uint32(0); addr <= uint32(0xFFFFF); addr += 0x1234 { for socket := uint(0); socket < uint(5); socket++ { if off, err := ook.New(addr, socket, false, nil); err != nil { t.Error(err) } else { t.Log(off) if off.Addr() != addr { t.Error("Unexpected addr") } if off.State() != false { t.Error("Unexpected state") } if off.Socket() != socket { t.Error("Unexpected socket") } } if on, err := ook.New(addr, socket, true, nil); err != nil { t.Error(err) } else { t.Log(on) if on.Addr() != addr { t.Error("Unexpected addr") } if on.State() != true { t.Error("Unexpected state") } if on.Socket() != socket { t.Error("Unexpected socket") } } } } } } func Test_OOK_004(t *testing.T) { if ook := OOK(); ook == nil { t.Fatal("Missing OOK module") } else if msg, err := ook.New(0x789AB, 0, true, nil); err != nil { t.Fatal(err) } else { t.Logf("message=%v", msg) t.Logf(" payload=%v", strings.ToUpper(hex.EncodeToString(ook.Encode(msg)))) } } func Test_OOK_005(t *testing.T) { if ook := OOK(); ook == nil { t.Fatal("Missing OOK module") } else if msg, err := ook.New(0x789AB, 0, true, nil); err != nil { t.Fatal(err) } else if msg_out, err := ook.Decode(ook.Encode(msg), time.Time{}); err != nil { t.Fatal(err) } else { t.Logf(" in=%v", msg) t.Logf(" payload=%v", strings.ToUpper(hex.EncodeToString(ook.Encode(msg)))) t.Logf(" out=%v", msg_out) } } func Test_OOK_006(t *testing.T) { if ook := OOK(); ook == nil { t.Fatal("Missing OOK module") } else { for addr := uint32(0); addr < uint32(0xFFFFF); addr += uint32(0x245) { t.Logf("addr=0x%05X", addr) if msg_in, err := ook.New(addr, uint(addr%5), uint(addr%2) == 0, nil); err != nil { t.Fatal(err) } else if msg_out, err := ook.Decode(ook.Encode(msg_in), time.Time{}); err != nil { t.Fatal(err) } else if Equals(msg_in, msg_out) == false { t.Errorf("Messages don't match: %v and %v", msg_in, msg_out) } } } } //////////////////////////////////////////////////////////////////////////////// // OOK func OOK() sensors.OOKProto { if app, err := gopi.NewAppInstance(gopi.NewAppConfig("sensors/protocol/ook")); err != nil { return nil } else if ook, ok := app.ModuleInstance("sensors/protocol/ook").(sensors.OOKProto); ok == false { return nil } else { return ook } } func Equals(m1, m2 sensors.Message) bool { return m1.IsDuplicate(m2) }
package main import ( "context" "fmt" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter7/grpc/greeter" "google.golang.org/grpc" ) func main() { conn, err := grpc.Dial(":4444", grpc.WithInsecure()) if err != nil { panic(err) } defer conn.Close() client := greeter.NewGreeterServiceClient(conn) ctx := context.Background() req := greeter.GreetRequest{Greeting: "Hello", Name: "Reader"} resp, err := client.Greet(ctx, &req) if err != nil { panic(err) } fmt.Println(resp) req.Greeting = "Goodbye" resp, err = client.Greet(ctx, &req) if err != nil { panic(err) } fmt.Println(resp) }
package analyzer import ( "search-engine/chapter7/analysis" "search-engine/chapter7/analysis/token" "search-engine/chapter7/analysis/tokenizer" ) // 定义简单分析器 = 不分词 + N-Gram func SimpleAnalyzer() (*analysis.Analyzer, error) { analyzer := &analysis.Analyzer{ Tokenizer: tokenizer.NewSingleTokenTokenizer(), TokenFilters: []analysis.TokenFilter{ token_filter.NewNgramFilter(1, 2), }, } return analyzer, nil }
/* =============What is Unsafe code?================================ unsafe code is th code in go program that bypasses safety and security of yur program.mostly it is related to pointers.using it is dangerous for your program. ============= */ package main import ( "fmt" "unsafe" ) // func main() { // var value int64 = 345 // var P1 = &value // var P2 = (*int32)(unsafe.Pointer(P1)) // fmt.Println("P1 ", *P1) // fmt.Println("P2 ", *P2) // *P1 = 5434123412312431212 // fmt.Println(value) // fmt.Println("P2 ", *P2) // *P2 = 54341234 // fmt.Println(value) // fmt.Println("*P2: ", *P2) // } func main() { array := [...]int{0, 1, -2, 3, 4} pointer := &array[0] fmt.Print(*pointer, " ") memoryAddress := uintptr(unsafe.Pointer(pointer)) + unsafe.Sizeof(array[0]) for i := 0; i < len(array)-1; i++ { pointer = (*int)(unsafe.Pointer(memoryAddress)) fmt.Print(*pointer, " ") memoryAddress = uintptr(unsafe.Pointer(pointer)) + unsafe.Sizeof(array[0]) } fmt.Println() pointer = (*int)(unsafe.Pointer(memoryAddress)) fmt.Print("One more: ", *pointer, " ") memoryAddress = uintptr(unsafe.Pointer(pointer)) + unsafe.Sizeof(array[0]) fmt.Println() }
package accesscontrol import ( "net/http" "testing" "encoding/base64" "github.com/danielsomerfield/authful/server/service/oauth" ) var validClientId = "valid-client-id" var validClientSecret = "valid-client-secret" var invalidClientSecret = "invalid-client-secret" type MockClient struct { } func (MockClient) CheckSecret(secret string) bool { return secret == validClientSecret } func (mc MockClient) GetScopes() []string { return []string{} } func (mc MockClient) IsValidRedirectURI(uri string) bool { return true } func (mc MockClient) GetDefaultRedirectURI() string { return "" } func MockClientLookupFn(clientId string) (oauth.Client, error) { if clientId == validClientId { return MockClient{ }, nil } else { return nil, nil } } var mockClientLookup = MockClientLookupFn var clientAccessControlFn = NewClientAccessControlFn(mockClientLookup) func TestIntrospect_FailsWithoutCredentials(t *testing.T) { request := http.Request{ } passed, err := clientAccessControlFn(request) if err != nil { t.Errorf("Unexpected error %+v\n", err) return } if passed { t.Error("Succeeded with request that should have failed") } } func TestIntrospect_FailsWithInvalidSecret(t *testing.T) { request := http.Request{ Header: http.Header{ "Authorization": []string{"Basic " + base64.StdEncoding.EncodeToString([]byte(validClientId+":"+invalidClientSecret))}, }, } passed, err := clientAccessControlFn(request) if err != nil { t.Errorf("Unexpected error %+v\n", err) return } if passed { t.Error("Succeeded with request that should have failed") } } func TestIntrospect_PassesWithValidCredentials(t *testing.T) { request := http.Request{ Header: http.Header{ "Authorization": []string{"Basic " + base64.StdEncoding.EncodeToString([]byte(validClientId+":"+validClientSecret))}, }, } passed, err := clientAccessControlFn(request) if err != nil { t.Errorf("Unexpected error %+v\n", err) return } if !passed { t.Error("Failed with request that should have succeeded") } }
package chart import ( "io/ioutil" "os" "path" "testing" "github.com/bitnami-labs/charts-syncer/api" "github.com/bitnami-labs/charts-syncer/pkg/repo" "github.com/bitnami-labs/charts-syncer/pkg/utils" ) var ( source = &api.SourceRepo{ Repo: &api.Repo{ Url: "https://charts.bitnami.com/bitnami", Kind: api.Kind_HELM, }, } target = &api.TargetRepo{ Repo: &api.Repo{ Url: "http://fake.target/com", Kind: api.Kind_CHARTMUSEUM, Auth: &api.Auth{ Username: "user", Password: "password", }, }, ContainerRegistry: "test.registry.io", ContainerRepository: "test/repo", } ) func TestDownload(t *testing.T) { // Create temporary working directory testTmpDir, err := ioutil.TempDir("", "charts-syncer-tests") if err != nil { t.Fatalf("error creating temporary: %s", testTmpDir) } defer os.RemoveAll(testTmpDir) chartPath := path.Join(testTmpDir, "nginx-5.3.1.tgz") // Create client for source repo sc, err := repo.NewClient(source.Repo) if err != nil { t.Fatal("could not create a client for the source repo", err) } sourceIndex, err := utils.LoadIndexFromRepo(source.Repo) if err != nil { t.Fatalf("error loading index.yaml: %v", err) } if err := sc.DownloadChart(chartPath, "nginx", "5.3.1", source.Repo, sourceIndex); err != nil { t.Fatal(err) } if _, err := os.Stat(chartPath); err != nil { t.Errorf("chart package does not exist") } } func TestUpdateValuesFile(t *testing.T) { originalValues := `## ## Simplified values yaml file to test registry and repository substitutions ## global: imageRegistry: "" image: registry: new.registry.io repository: test/repo/new/zookeeper tag: 3.5.7-r7 volumePermissions: enabled: false image: registry: new.registry.io repository: repo/new/custom-base-image tag: r0` want := `## ## Simplified values yaml file to test registry and repository substitutions ## global: imageRegistry: "" image: registry: test.registry.io repository: test/repo/zookeeper tag: 3.5.7-r7 volumePermissions: enabled: false image: registry: test.registry.io repository: test/repo/custom-base-image tag: r0` // Create temporary working directory testTmpDir, err := ioutil.TempDir("", "charts-syncer-tests") if err != nil { t.Fatalf("error creating temporary: %s", testTmpDir) } defer os.RemoveAll(testTmpDir) destValuesFilePath := path.Join(testTmpDir, ValuesFilename) // Write file err = ioutil.WriteFile(destValuesFilePath, []byte(originalValues), 0644) if err != nil { t.Fatalf("error writting destination file") } updateValuesFile(destValuesFilePath, target) valuesFile, err := ioutil.ReadFile(destValuesFilePath) if err != nil { t.Fatal(err) } got := string(valuesFile) if want != got { t.Errorf("incorrect modification, got: \n %s \n, want: \n %s \n", got, want) } } func TestUpdateReadmeFile(t *testing.T) { originalValues := ` # Ghost [Ghost](https://ghost.org/) is one of the most versatile open source content management systems on the market. ## TL;DR; $ helm repo add bitnami https://charts.bitnami.com/bitnami $ helm install my-release bitnami/ghost ... The above parameters map to the env variables defined in [bitnami/ghost](http://github.com/bitnami/bitnami-docker-ghost). ` want := ` # Ghost [Ghost](https://ghost.org/) is one of the most versatile open source content management systems on the market. ## TL;DR; $ helm repo add mytestrepo https://my-new-chart-repo.com $ helm install my-release mytestrepo/ghost ... The above parameters map to the env variables defined in [bitnami/ghost](http://github.com/bitnami/bitnami-docker-ghost). ` // Create temporary working directory testTmpDir, err := ioutil.TempDir("", "charts-syncer-tests") if err != nil { t.Fatalf("error creating temporary: %s", testTmpDir) } defer os.RemoveAll(testTmpDir) destValuesFilePath := path.Join(testTmpDir, ReadmeFilename) // Write file err = ioutil.WriteFile(destValuesFilePath, []byte(originalValues), 0644) if err != nil { t.Fatalf("error writting destination file") } updateReadmeFile(destValuesFilePath, "https://charts.bitnami.com/bitnami", "https://my-new-chart-repo.com", "ghost", "mytestrepo") readmeFile, err := ioutil.ReadFile(destValuesFilePath) if err != nil { t.Fatal(err) } got := string(readmeFile) if want != got { t.Errorf("incorrect modification, got: \n %s \n, want: \n %s \n", got, want) } }
package sqlx import ( "testing" "fmt" "github.com/ellsol/gox/testx" ) func TestStatementBuilder(t *testing.T) { stb, params := NewSelectStatement("*", "tablename"). AddEqualCondition("label", 45). AddInCondition("inlabel", []string{"p1", "p2"}). AddEqualCondition("label2", 88). AddOffset(1200). AddLimit(120).GetStatementAndParams() expectedStatement := "SELECT * FROM tablename WHERE label = $1 AND inlabel IN ($2,$3) AND label2 = $4 OFFSET $5 LIMIT $6" if testx.CompareString("statement", expectedStatement, stb, t) { return } fmt.Println(params) if len(params) != 6 { t.Errorf("Param length is wrong [Expected 6, Actual: %v", len(params)) return } if params[0] != 45 { t.Errorf("Param[0[ is wrong [Expected 45, Actual: %v", params[0]) return } if params[1] != "p1" { t.Errorf("Param[1] is wrong [Expected 45, Actual: %v", params[1]) return } if params[2] != "p2" { t.Errorf("Param[2] is wrong [Expected p2, Actual: %v", params[2]) return } if params[3] != 88 { t.Errorf("Param[3] is wrong [Expected 45, Actual: %v", params[3]) return } if params[4] != 1200 { t.Errorf("Param[4] is wrong [Expected 1200, Actual: %v", params[4]) return } if params[5] != 120 { t.Errorf("Param[5] is wrong [Expected 120, Actual: %v", params[5]) return } }
/***************************************************************** * Copyright©,2020-2022, email: 279197148@qq.com * Version: 1.0.0 * @Author: yangtxiang * @Date: 2020-07-30 17:11 * Description: *****************************************************************/ package xthrift import ( "fmt" "github.com/apache/thrift/lib/go/thrift" ) type TPList struct { ElemType TProtocolDataType Body []ProtocolDataToken } var _ ProtocolDataToken = (*TPList)(nil) func NewPList(elemType TProtocolDataType) *TPList { return &TPList{ ElemType: elemType, Body: make([]ProtocolDataToken, 0), } } func (p *TPList) Write(out thrift.TTransport) error { return nil } func (p *TPList) Read(in thrift.TTransport) error { return nil } func (p *TPList) GetType() TProtocolDataType { return thrift.LIST } func (p *TPList) GetElemType() TProtocolDataType { return p.ElemType } func (p *TPList) AddItem(item ProtocolDataToken) error { if item == nil { return nil } if item.GetType() != p.ElemType { return fmt.Errorf("列表项期望类型%s,不接受类型:%s", p.ElemType, item.GetType()) } p.Body = append(p.Body, item) return nil }
package repository type ThroughRepository interface { Get() []string }
// デフォルトで標準入力のSHA256ハッシュを表示するプログラムを書きなさい。 // ただし、SHA384ハッシュやSHA512ハッシュを表示するコマンドラインのフラグもサポートしなさい。 package main import ( "crypto/sha256" "crypto/sha512" "flag" "fmt" "io/ioutil" "log" "os" ) var width = flag.Int("w", 256, "hash width (256, 384 or 512)") func main() { flag.Parse() b, err := ioutil.ReadAll(os.Stdin) if err != nil { log.Fatal(err) } switch *width { case 256: h := sha256.Sum256(b) print(h[:]) case 384: h := sha512.Sum384(b) print(h[:]) case 512: h := sha512.Sum512(b) print(h[:]) default: log.Fatal("invalid hash widh specified.") } } func print(hash []byte) { for _, v := range hash { fmt.Printf("%X", v) } fmt.Println() }
package models import ( "github.com/evil-router/isfired/database" uuid2 "github.com/satori/go.uuid" "log" "golang.org/x/net/idna" ) type comment struct { Name string Reason string Time string Location string Status bool } type site struct { ID string Name string Site string } func GetSite(name string) (string, error) { var id string log.Printf("get site %v", name) db, err := database.GetDB() if err != nil { log.Print(err) return "", err } err = db.QueryRow("select site.Site_ID From site where Site = ?", name).Scan(&id) if err != nil { log.Print(err) return "", err } return id, nil } func GetComment(site string, count int64, offset int64) ([]comment, error) { var c []comment db, err := database.GetDB() if err != nil { log.Print(err) return c, err } rows, err := db.Query(`select site.Name, comment.message, comment.Status,comment.time,comment.location from comment ,site where comment.FK_Site_ID = site.Site_ID AND site.Site = ? Order by comment.PK_comment_ID desc limit ? OFFSET ?;`, site, count, offset) if err != nil { log.Print(err) return c, err } defer rows.Close() for rows.Next() { var n, m, t, l string var s bool err := rows.Scan(&n, &m, &s, &t, &l) if err != nil { log.Fatal(err) } n, _= idna.ToUnicode(n) m, _ = idna.ToUnicode(m) c = append(c, comment{n, m, t, l, s}) } return c, nil } func SetComment(site string, comment string, city string, status bool) error { db, err := database.GetDB() if err != nil { log.Print(err) return err } site,_ = idna.ToASCII(site) id, err := GetSite(site) if err != nil { log.Print(err) return err } comment,_= idna.ToASCII(comment) rows, err := db.Query("INSERT INTO `Fired`.`comment` (`FK_Site_ID`, `message`, `time`, `location`, `Status`)"+ "VALUES (?, ?, DEFAULT, ? , ?)", id, comment, city, status) defer rows.Close() if err != nil { log.Print(err) return err } return nil } func GetActiveSites() ([]site, error) { var sites []site db, err := database.GetDB() if err != nil { log.Print(err) return sites, err } rows, err := db.Query("Select Site,Name,PK_ID from site") defer rows.Close() if err != nil { log.Print(err) return sites, err } for rows.Next() { var s, n, i string err := rows.Scan(&s, &n, &i) if err != nil { log.Fatal(err) } n,_ = idna.ToUnicode(n) s,_= idna.ToUnicode(s) sites = append(sites, site{i, n, s}) } return sites, nil } func AddSite(site, name string) error { db, err := database.GetDB() if err != nil { log.Print(err) return err } uuid, _ := uuid2.NewV4() rows, err := db.Query("INSERT INTO `Fired`.`site` (`Site_ID`, `Name`, `Site`, `PK_ID`)"+ "VALUES (?, ?, ? , DEFAULT)", uuid.String(), name, site) defer rows.Close() if err != nil { log.Printf("Site Add %v", err) return err } SetComment(site, "Welcome", "xn--no8h", false) return nil }
// GoFigure is a small utility library for reading configuration files. It's usefuly especially if you want // to load many files recursively (think /etc/apache2/mods-enabled/*.conf). // // It can support multiple formats, as long as you take a file and unmarshal it into a struct containing // your configurations. Right now the only implemented formats are YAML and JSON files, but feel free to // add more :) package gofigure import ( "io" "io/ioutil" "log" "os" "path/filepath" "time" ) // Decoder is the interface for config decoders (right now we've just implemented a YAML one) type Decoder interface { // Decode reads data from the io stream, and unmarshals it to the config struct. Decode(r io.Reader, config interface{}) error // CanDecode should return true if a file is decode-able by the decoder, // based on extension or similar mechanisms CanDecode(path string) bool } // Loader traverses directories recursively and lets the decoder decode relevant files. // // It can also explicitly decode single files type Loader struct { decoder Decoder // StrictMode determines whether the loader will completely fail on any IO or decoding error, // or whether it will continue traversing all files even if one of them is invalid. StrictMode bool } // LoadRecursive takes a pointer to a struct containing configurations, and a series of paths. // It then traverses the paths recursively in their respective order, and lets the decoder decode // every relevant file. func (l Loader) LoadRecursive(config interface{}, paths ...string) error { for path := range walk(paths...) { log.Println(path) if l.decoder.CanDecode(path) { err := l.LoadFile(config, path) if err != nil { log.Printf("Error loading %s: %s", path, err) if l.StrictMode { return err } } } } return nil } // LoadFile takes a pointer to a struct containing configurations, and a path to a file, // and uses the decoder to read the file's contents into the struct. It returns an // error if the file could not be opened or properly decoded func (l Loader) LoadFile(config interface{}, path string) error { fp, err := os.Open(path) if err != nil { log.Printf("Error opening file %s: %s", path, err) if l.StrictMode { return err } } defer fp.Close() err = l.decoder.Decode(fp, config) if err != nil { log.Printf("Error decodeing file %s: %s", path, err) if l.StrictMode { return err } } return nil } func isDirectory(path string) (bool, error) { fileInfo, err := os.Stat(path) if err != nil { return false, err } return fileInfo.IsDir(), nil } // walkDir recursively traverses a directory, sending every found file's path to the channel ch. // If no one is reading from ch, it times out after a second of waiting, and quits func walkDir(path string, ch chan string) { files, err := ioutil.ReadDir(path) if err != nil { log.Printf("Could not read path %s: %s", path, err) return } for _, file := range files { fullpath := filepath.Join(path, file.Name()) if isdir, err := isDirectory(fullpath); err != nil { log.Printf("Could not stat dir %s: %s", fullpath, err) continue } else if isdir { walkDir(fullpath, ch) continue } select { case ch <- fullpath: case <-time.After(100 * time.Millisecond): //if the reader has quit we will time out writing if the channel buffer is full log.Printf("Cannot write to channel, timing out") return } } } // walk takes a series of paths, and traverses them recursively by order, sending all found files // in the returned channel. It then closes the channel func walk(paths ...string) (pathchan <-chan string) { // we make the channel buffered so it can be filled while the consumer loads files ch := make(chan string, 100) go func() { defer close(ch) for _, path := range paths { walkDir(path, ch) } }() return ch }
package main // This is an example of using go-iapclient for a purpose that is not usage by // a golang http.Client. It uses GetToken() to retrieve the token, then inserts // it into a curl commandline // Example usage: // go run iapwrap.go --client-id $CLIENT_ID -- -v -k https://$HOST import ( "context" "fmt" "log" "os" "os/exec" "syscall" "github.com/urbanairship/go-iapclient" "gopkg.in/alecthomas/kingpin.v2" ) var ( cid = kingpin.Flag("client-id", "OAuth Client ID").Required().String() args = kingpin.Arg("args", "remaining args").Strings() ) func main() { kingpin.Parse() iap, err := iapclient.NewIAP(*cid, nil) if err != nil { log.Fatalf("Failed to create new IAP object: %v", err) } token, err := iap.GetToken(context.Background()) if err != nil { log.Fatalf("Failed to get token: %v", err) } curl, err := exec.LookPath("curl") args := append([]string{"curl", "-H", fmt.Sprintf("Authorization: Bearer %s", token)}, *args...) env := os.Environ() if err := syscall.Exec(curl, args, env); err != nil { log.Fatal(err) } }
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package e2enode import ( "context" "time" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/kubernetes/pkg/features" kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config" "k8s.io/kubernetes/test/e2e/common" "k8s.io/kubernetes/test/e2e/framework" e2epod "k8s.io/kubernetes/test/e2e/framework/pod" testutils "k8s.io/kubernetes/test/utils" imageutils "k8s.io/kubernetes/test/utils/image" "github.com/onsi/ginkgo" ) const ( defaultObservationTimeout = time.Minute * 4 ) var _ = framework.KubeDescribe("StartupProbe [Serial] [Disruptive]", func() { f := framework.NewDefaultFramework("startup-probe-test") var podClient *framework.PodClient ginkgo.BeforeEach(func() { podClient = f.PodClient() }) /* These tests are located here as they require tempSetCurrentKubeletConfig to enable the feature gate for startupProbe. Once the feature gate has been removed, these tests should come back to test/e2e/common/container_probe.go. */ ginkgo.Context("when a container has a startup probe", func() { tempSetCurrentKubeletConfig(f, func(initialConfig *kubeletconfig.KubeletConfiguration) { if initialConfig.FeatureGates == nil { initialConfig.FeatureGates = make(map[string]bool) } initialConfig.FeatureGates[string(features.StartupProbe)] = true }) /* Release : v1.16 Testname: Pod startup probe restart Description: A Pod is created with a failing startup probe. The Pod MUST be killed and restarted incrementing restart count to 1, even if liveness would succeed. */ ginkgo.It("should be restarted startup probe fails", func() { cmd := []string{"/bin/sh", "-c", "sleep 600"} livenessProbe := &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"/bin/true"}, }, }, InitialDelaySeconds: 15, FailureThreshold: 1, } startupProbe := &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"/bin/false"}, }, }, InitialDelaySeconds: 15, FailureThreshold: 3, } pod := startupPodSpec(startupProbe, nil, livenessProbe, cmd) common.RunLivenessTest(f, pod, 1, defaultObservationTimeout) }) /* Release : v1.16 Testname: Pod liveness probe delayed (long) by startup probe Description: A Pod is created with failing liveness and startup probes. Liveness probe MUST NOT fail until startup probe expires. */ ginkgo.It("should *not* be restarted by liveness probe because startup probe delays it", func() { cmd := []string{"/bin/sh", "-c", "sleep 600"} livenessProbe := &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"/bin/false"}, }, }, InitialDelaySeconds: 15, FailureThreshold: 1, } startupProbe := &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"/bin/false"}, }, }, InitialDelaySeconds: 15, FailureThreshold: 60, } pod := startupPodSpec(startupProbe, nil, livenessProbe, cmd) common.RunLivenessTest(f, pod, 0, defaultObservationTimeout) }) /* Release : v1.16 Testname: Pod liveness probe fails after startup success Description: A Pod is created with failing liveness probe and delayed startup probe that uses 'exec' command to cat /temp/health file. The Container is started by creating /tmp/startup after 10 seconds, triggering liveness probe to fail. The Pod MUST now be killed and restarted incrementing restart count to 1. */ ginkgo.It("should be restarted by liveness probe after startup probe enables it", func() { cmd := []string{"/bin/sh", "-c", "sleep 10; echo ok >/tmp/startup; sleep 600"} livenessProbe := &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"/bin/false"}, }, }, InitialDelaySeconds: 15, FailureThreshold: 1, } startupProbe := &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"cat", "/tmp/startup"}, }, }, InitialDelaySeconds: 15, FailureThreshold: 60, } pod := startupPodSpec(startupProbe, nil, livenessProbe, cmd) common.RunLivenessTest(f, pod, 1, defaultObservationTimeout) }) /* Release : v1.16 Testname: Pod readiness probe, delayed by startup probe Description: A Pod is created with startup and readiness probes. The Container is started by creating /tmp/startup after 45 seconds, delaying the ready state by this amount of time. This is similar to the "Pod readiness probe, with initial delay" test. */ ginkgo.It("should not be ready until startupProbe succeeds", func() { cmd := []string{"/bin/sh", "-c", "echo ok >/tmp/health; sleep 45; echo ok >/tmp/startup; sleep 600"} readinessProbe := &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"cat", "/tmp/health"}, }, }, InitialDelaySeconds: 0, } startupProbe := &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{"cat", "/tmp/startup"}, }, }, InitialDelaySeconds: 0, FailureThreshold: 60, } p := podClient.Create(startupPodSpec(startupProbe, readinessProbe, nil, cmd)) p, err := podClient.Get(context.TODO(), p.Name, metav1.GetOptions{}) framework.ExpectNoError(err) e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, p.Name, f.Namespace.Name, framework.PodStartTimeout) p, err = podClient.Get(context.TODO(), p.Name, metav1.GetOptions{}) framework.ExpectNoError(err) isReady, err := testutils.PodRunningReady(p) framework.ExpectNoError(err) framework.ExpectEqual(isReady, true, "pod should be ready") // We assume the pod became ready when the container became ready. This // is true for a single container pod. readyTime, err := common.GetTransitionTimeForReadyCondition(p) framework.ExpectNoError(err) startedTime, err := common.GetContainerStartedTime(p, "busybox") framework.ExpectNoError(err) framework.Logf("Container started at %v, pod became ready at %v", startedTime, readyTime) if readyTime.Sub(startedTime) < 40*time.Second { framework.Failf("Pod became ready before startupProbe succeeded") } }) }) }) func startupPodSpec(startupProbe, readinessProbe, livenessProbe *v1.Probe, cmd []string) *v1.Pod { return &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "startup-" + string(uuid.NewUUID()), Labels: map[string]string{"test": "startup"}, }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "busybox", Image: imageutils.GetE2EImage(imageutils.BusyBox), Command: cmd, LivenessProbe: livenessProbe, ReadinessProbe: readinessProbe, StartupProbe: startupProbe, }, }, }, } }
package dynamic_programming func numDecodings(s string) int { if len(s) == 0 { return 0 } dp := make([]int, len(s)+1) dp[0] = 1 for i := 1; i <= len(s); i++ { if s[i-1] > '0' { dp[i] = dp[i-1] } if i > 1 && s[i-2:i] >= "10" && s[i-2:i] <= "26" { dp[i] += dp[i-2] } } return dp[len(s)] }
package WeightedRandomChoice import ( "math/rand" "sort" "time" ) type WeightedRandomChoice struct { Elements [] string Weights [] int TotalWeight int calibratedWeights bool precision int calibrateValue int } func (wrc *WeightedRandomChoice) AddElement(element string, weight int) { weight *= wrc.calibrateValue i := sort.Search(len(wrc.Weights), func(i int) bool { return wrc.Weights[i] > weight }) wrc.Weights = append(wrc.Weights, 0) wrc.Elements = append(wrc.Elements, "") copy(wrc.Weights[i+1:], wrc.Weights[i:]) copy(wrc.Elements[i+1:], wrc.Elements[i:]) wrc.Weights[i] = weight wrc.Elements[i] = element wrc.TotalWeight += weight } func (wrc *WeightedRandomChoice) AddElements(elements map[string]int) { for element, weight := range elements{ wrc.AddElement(element, weight) } } func (wrc *WeightedRandomChoice) GetRandomChoice() string { rand.Seed(time.Now().UnixNano()) value := rand.Intn(wrc.TotalWeight) if !wrc.calibratedWeights { wrc.calibrateWeights() } for key, weight := range wrc.Weights { value -= weight if value <= 0 { return wrc.Elements[key] } } return "" } func (wrc *WeightedRandomChoice) calibrateWeights() { if wrc.TotalWeight/wrc.precision < 1 { wrc.calibrateValue = wrc.precision / wrc.TotalWeight wrc.TotalWeight = 0 for key := range wrc.Weights { wrc.Weights[key] *= wrc.calibrateValue wrc.TotalWeight += wrc.Weights[key] } wrc.calibratedWeights = true } } func New(arguments ...int) WeightedRandomChoice { var precision = 1000 if len(arguments) > 0 { precision = arguments[0] } return WeightedRandomChoice{ precision: precision, calibratedWeights: false, calibrateValue: 1, } }
package schema import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" gojsonschema "github.com/xeipuuv/gojsonschema" ) //map of resources : schemaLoader var Schemas = make(map[string]gojsonschema.JSONLoader) func init() { loadAllSchemas() } // Read /schemas directory contents, and create schemaLoader for all .json. func loadAllSchemas() { wd, _ := os.Getwd() schemaDir := wd + "/schemas/" files, _ := ioutil.ReadDir(schemaDir) for _, f := range files { name := f.Name() if filepath.Ext(name) == ".json" { Schemas[name[0:len(name)-len(".json")]] = gojsonschema.NewReferenceLoader( "file://" + schemaDir + name, ) } } } func ValidateCreation(schemaName string, input interface{}) error { return validate(true, schemaName, input) } func ValidateUpdate(schemaName string, input interface{}) error { return validate(false, schemaName, input) } func validate(enforceRequired bool, schemaName string, input interface{}) error { schemaLoader := Schemas[schemaName] documentLoader := gojsonschema.NewGoLoader(input) result, err := gojsonschema.Validate(schemaLoader, documentLoader) if err != nil { panic(err.Error()) } if !result.Valid() { validationErrors := result.Errors() if len(validationErrors) == 0 { return nil } errorMessage := "" for _, err := range validationErrors { if !enforceRequired && err.Type() == "required" { continue } errorMessage += fmt.Sprintf(", %s", err.Description()) } return errors.New(errorMessage) } return nil }
package sns import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sns" "github.com/aws/aws-sdk-go/service/sns/snsiface" "github.com/pkg/errors" "github.com/utilitywarehouse/go-pubsub" ) type messageSink struct { client snsiface.SNSAPI topic string } // NewSNSSink is a constructor for new AWS SNS MessageSink type func NewSNSSink(conf *aws.Config, topic string) (pubsub.MessageSink, error) { sess, err := session.NewSession(conf) if err != nil { return nil, errors.Wrap(err, "could not construct AWS Session") } return &messageSink{ client: sns.New(sess), topic: topic, }, nil } // PutMessage sends ProducerMessage types to AWS SNS func (s *messageSink) PutMessage(message pubsub.ProducerMessage) error { b, err := message.Marshal() if err != nil { return errors.Wrap(err, "SNS Sink could not marshal ProducerMessage") } input := &sns.PublishInput{ Message: aws.String(string(b)), TopicArn: &s.topic, } _, err = s.client.Publish(input) if err != nil { return errors.Wrap(err, "error publishing to SNS") } return nil } // Status used to check status of connection to AWS SNS func (s *messageSink) Status() (*pubsub.Status, error) { topics, err := s.client.ListTopics(&sns.ListTopicsInput{}) if err != nil { return nil, err } status := &pubsub.Status{} if len(topics.Topics) < 1 { status.Working = false status.Problems = append(status.Problems, "no SNS topics") return status, nil } for _, x := range topics.Topics { if *x.TopicArn == s.topic { status.Working = true return status, nil } } status.Working = false status.Problems = append(status.Problems, fmt.Sprintf("%s not in topic list [%v]", s.topic, topics.Topics)) return status, nil } // Close is stubbed as there is no equivalent on the SNS Client. func (s *messageSink) Close() error { return nil }
package sploit import ( "bytes" "debug/elf" "encoding/binary" "errors" "io/ioutil" "os" ) // ELF is a struct that contains methods for operating on an ELF file type ELF struct { E *elf.File Processor *Processor PIE bool Mitigations *Mitigations raw []byte } // NewELF loads an ELF file from disk and initializes the ELF struct func NewELF(filename string) (*ELF, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() rawData, err := ioutil.ReadAll(f) if err != nil { return nil, err } e, err := elf.Open(filename) if err != nil { return nil, err } processor, err := getArchInfo(e) if err != nil { return nil, err } isPIE := (e.Type == elf.ET_DYN) mitigations, err := checkMitigations(e) if err != nil { return nil, err } return &ELF{ E: e, Processor: processor, PIE: isPIE, Mitigations: mitigations, raw: rawData, }, nil } // OffsetToAddr determines the virtual address for the specified file offset func (e *ELF) OffsetToAddr(offset uint64) (uint64, error) { for i := 0; i < len(e.E.Progs); i++ { s := e.E.Progs[i] start := s.Off end := s.Off + s.Filesz if offset >= start && offset < end { return offset - s.Off + s.Vaddr, nil } } return 0, errors.New("Offset is not in range of an ELF segment") } // AddrToOffset determines the offset for the specified virtual address func (e *ELF) AddrToOffset(address uint64) (uint64, error) { for i := 0; i < len(e.E.Progs); i++ { s := e.E.Progs[i] start := s.Vaddr end := s.Vaddr + s.Filesz if address >= start && address < end { return address - s.Vaddr + s.Off, nil } } return 0, errors.New("Address is not in range of an ELF segment") } // BSS returns the virtual address of the specified offset into the .bss section func (e *ELF) BSS(offset uint64) (uint64, error) { section := e.E.Section(".bss") if section == nil { return 0, errors.New("No .bss section") } if offset >= section.Size { return 0, errors.New("Offset exceeds end of .bss") } return section.Addr + offset, nil } // Read returns a slice of bytes read from the ELF at the specified virtual address func (e *ELF) Read(address uint64, nBytes int) ([]byte, error) { s, err := getVASegment(e.E, address) if err != nil { return nil, err } offset := address - s.Vaddr if s.Filesz-offset < uint64(nBytes) { nBytes = int(s.Filesz - offset) } buf := make([]byte, nBytes) _, err = s.ReadAt(buf, int64(offset)) if err != nil { return nil, err } return buf, nil } // Write copies data to the in-memory raw ELF data at the specified virtual address func (e *ELF) Write(data []byte, address uint64) error { offset, err := e.AddrToOffset(address) if err != nil { return err } copy(e.raw[offset:offset+uint64(len(data))], data) return nil } // Write8 copies a uint8 to the in-memory ELF data at the specified address func (e *ELF) Write8(i uint8, address uint64) error { return e.Write([]byte{i}, address) } // Write16LE copies a uint16 (little endian) to the in-memory ELF data at the specified address func (e *ELF) Write16LE(i uint16, address uint64) error { return e.Write(PackUint16LE(i), address) } // Write16BE copies a uint16 (big endian) to the in-memory ELF data at the specified address func (e *ELF) Write16BE(i uint16, address uint64) error { return e.Write(PackUint16BE(i), address) } // Write32LE copies a uint32 (little endian) to the in-memory ELF data at the specified address func (e *ELF) Write32LE(i uint32, address uint64) error { return e.Write(PackUint32LE(i), address) } // Write32BE copies a uint32 (big endian) to the in-memory ELF data at the specified address func (e *ELF) Write32BE(i uint32, address uint64) error { return e.Write(PackUint32BE(i), address) } // Write64LE copies a uint64 (little endian) to the in-memory ELF data at the specified address func (e *ELF) Write64LE(i uint64, address uint64) error { return e.Write(PackUint64LE(i), address) } // Write64BE copies a uint64 (big endian) to the in-memory ELF data at the specified address func (e *ELF) Write64BE(i uint64, address uint64) error { return e.Write(PackUint64BE(i), address) } // Read8 reads 8 bits from the ELF at the specified address and returns the data as a uint8 func (e *ELF) Read8(address uint64) (uint8, error) { b, err := e.readIntBytes(address, 1) if err != nil { return 0, err } return b[0], nil } // Read16LE reads 16 bits from the ELF at the specified address and returns a Uint16 in little endian byte order func (e *ELF) Read16LE(address uint64) (uint16, error) { b, err := e.readIntBytes(address, 2) if err != nil { return 0, err } return binary.LittleEndian.Uint16(b), nil } // Read16BE reads 16 bits from the ELF at the specified address and returns a Uint16 in big endian byte order func (e *ELF) Read16BE(address uint64) (uint16, error) { b, err := e.readIntBytes(address, 2) if err != nil { return 0, err } return binary.BigEndian.Uint16(b), nil } // Read32LE reads 32 bits from the ELF at the specified address and returns a Uint32 in little endian byte order func (e *ELF) Read32LE(address uint64) (uint32, error) { b, err := e.readIntBytes(address, 4) if err != nil { return 0, err } return binary.LittleEndian.Uint32(b), nil } // Read32BE reads 32 bits from the ELF at the specified address and returns a Uint32 in big endian byte order func (e *ELF) Read32BE(address uint64) (uint32, error) { b, err := e.readIntBytes(address, 4) if err != nil { return 0, err } return binary.BigEndian.Uint32(b), nil } // Read64LE reads 64 bits from the ELF at the specified address and returns a Uint64 in little endian byte order func (e *ELF) Read64LE(address uint64) (uint64, error) { b, err := e.readIntBytes(address, 8) if err != nil { return 0, err } return binary.LittleEndian.Uint64(b), nil } // Read64BE reads 64 bits from the ELF at the specified address and returns a Uint64 in big endian byte order func (e *ELF) Read64BE(address uint64) (uint64, error) { b, err := e.readIntBytes(address, 8) if err != nil { return 0, err } return binary.BigEndian.Uint64(b), nil } // Disasm disassembles code at the specified virtual address and returns a string containing assembly instructions func (e *ELF) Disasm(address uint64, nBytes int) (string, error) { data, err := e.Read(address, nBytes) if err != nil { return "", err } arch := getCapstoneArch(e.Processor) mode := getCapstoneMode(e.Processor) return disasm(data, address, arch, mode, false) } // ROP locates all ROP gadgets in the ELF's executable segments and returns a ROP object func (e *ELF) ROP() (*ROP, error) { file := e.E gadgets := ROP{} for i := 0; i < len(file.Progs); i++ { // Check if segment is executable if file.Progs[i].Flags&elf.PF_X == 0 { continue } // Segment is executable, read segment data data, err := e.Read(file.Progs[i].Vaddr, int(file.Progs[i].Filesz)) if err != nil { return nil, err } // Search for gadgets in data gadgetsSeg, err := findGadgets(e.Processor, data, file.Progs[i].Vaddr) if err != nil { return nil, err } gadgets = append(gadgets, gadgetsSeg...) } return &gadgets, nil } // GetSignatureVAddrs searches for the specified sequence of bytes in all segments func (e *ELF) GetSignatureVAddrs(signature []byte) ([]uint64, error) { return e.getSignatureVAddrs(signature, false) } // GetOpcodeVAddrs searches for the specified sequence of bytes in executable segments only func (e *ELF) GetOpcodeVAddrs(signature []byte) ([]uint64, error) { return e.getSignatureVAddrs(signature, true) } // Save saves the raw ELF content to a specified file path func (e *ELF) Save(filePath string, fileMode os.FileMode) error { return ioutil.WriteFile(filePath, e.raw, fileMode) } // AsmPatch compiles an assembly patch and writes it to the in-memory raw ELF data at the specified virtual address func (e *ELF) AsmPatch(code string, address uint64) error { opcode, err := Asm(e.Processor, code) if err != nil { return err } return e.Write(opcode, address) } func (e *ELF) getSignatureVAddrs(signature []byte, exeOnly bool) ([]uint64, error) { file := e.E vaddrs := []uint64{} for i := 0; i < len(file.Progs); i++ { if exeOnly { if file.Progs[i].Flags&elf.PF_X == 0 { continue } } data, err := e.Read(file.Progs[i].Vaddr, int(file.Progs[i].Filesz)) if err != nil { return nil, errors.New("Failed to read from segment") } // Search for byte signature in segment n := 0 for { idx := bytes.Index(data[n:], signature) if idx == -1 { break } vaddrs = append(vaddrs, file.Progs[i].Vaddr+uint64(n)+uint64(idx)) n += idx + 1 } } return vaddrs, nil } func getVASegment(e *elf.File, address uint64) (*elf.Prog, error) { for i := 0; i < len(e.Progs); i++ { s := e.Progs[i] start := s.Vaddr end := s.Vaddr + s.Filesz if address >= start && address < end { return s, nil } } return nil, errors.New("Address is not in range of an ELF section") } func getArchInfo(e *elf.File) (*Processor, error) { supported := map[elf.Machine]Architecture{ elf.EM_X86_64: ArchX8664, elf.EM_386: ArchI386, elf.EM_ARM: ArchARM, elf.EM_AARCH64: ArchAARCH64, elf.EM_PPC: ArchPPC, elf.EM_MIPS: ArchMIPS, elf.EM_IA_64: ArchIA64, } endian := LittleEndian if e.Data == elf.ELFDATA2MSB { endian = BigEndian } if arch, ok := supported[e.Machine]; ok { return &Processor{ Architecture: arch, Endian: endian, }, nil } return nil, errors.New("Unsupported machine type") } func checkMitigations(e *elf.File) (*Mitigations, error) { // Check if there's a stack canary symbols, err := e.Symbols() if err != nil { return nil, err } canary := false for _, symbol := range symbols { if symbol.Name == "__stack_chk_fail" { canary = true break } } // Check for executable stack (NX) nx := false for _, prog := range e.Progs { if uint32(prog.Type) == uint32(0x6474e551) { // PT_GNU_STACK if (uint32(prog.Flags) & uint32(elf.PF_X)) == 0 { nx = true break } } } return &Mitigations{ Canary: canary, NX: nx, }, nil } func (e *ELF) readIntBytes(address uint64, width int) ([]byte, error) { b, err := e.Read(address, width) if err != nil { return nil, err } if len(b) != width { return nil, errors.New("Read truncated do to end of segment") } return b, nil }
package day9 import ( "testing" "github.com/achakravarty/30daysofgo/assert" ) type testCase struct { num int expected int } var testCases = []testCase{ testCase{num: 3, expected: 6}, } func TestRecursion(t *testing.T) { for _, testInput := range testCases { actual := GetFactorial(testInput.num) assert.Equal(t, testInput.expected, actual) } }
package main import ( "fmt" ) type User struct { Id string `json:"id"` Name string `json:"name"` Balance int `json:"balance"` } func main() { //user := User{"Baby", 12} //user1 := user //user1.Name = "Val" //inc(&user) //fmt.Println(user) //fmt.Println(GetUser().Balance) //str := ` {"name":"Ali", "balance":12} ` //user := User{} //json.Unmarshal([]byte(str), &user) //fmt.Printf("%v\n", user) user1 := User{"ab", "Ali", 12} user2 := User{"ba", "Ali", 12} m := map[string]User{user1.Id: user1, user2.Id: user2} u := m["ab"] fmt.Println(u) } func inc(user *User) { user.Balance++ fmt.Println(user.Balance) } //func GetUser() *User { // return &User{"Baby", 12} //}
package main import ( "bufio" "crypto/tls" "flag" "math/rand" "net" "net/http" "net/url" "os" "strings" "sync" "sync/atomic" "syscall" "time" "github.com/gorilla/websocket" "github.com/sirupsen/logrus" ) const ( RULE_MAX = 500000 TCP_QUICK_ACK = 1 TCP_NO_DELAY = 2 ) var outTimeLess1Cnt uint32 = 0 var outTime1to2Cnt uint32 = 0 var outTime2to3Cnt uint32 = 0 var outTime3to4Cnt uint32 = 0 var outTime4to5Cnt uint32 = 0 var outTime5to10Cnt uint32 = 0 var outTime10to15Cnt uint32 = 0 var outTime15to20Cnt uint32 = 0 var outTimeOver20Cnt uint32 = 0 var mineDomain [RULE_MAX]string var msgHead string = "1111111122222222333333334444444455555555666666667777777788888888" var addr = flag.String("addr", "nil", "please input addr: Use -addr . Like -addr 10.91.117.179:8443") var thread = flag.Int("thread", 0, "please input thread count(Better less 100): Use -thread ") var getnum = flag.Int("getnum", 0, "please input get num in each goroutine: Use -getnum") var logLevel = flag.Int("logLevel", 5, "Panic:0, Fatal:1, Error:2, Warn:3, Info:4, Debug:5, Trace:6. ex: -logLevel 5") var log *logrus.Logger func tlsConn() (conn *websocket.Conn, tconn *net.TCPConn, e error) { u := url.URL{Scheme: "ws", Host: *addr, Path: "/websocket"} conf := &tls.Config{ InsecureSkipVerify: true, } tcpAddr, err := net.ResolveTCPAddr("tcp4", u.Host) if err != nil { log.Printf("Resolve Tcp Addr %s failed\n", u.Host) return nil, nil, err } tcpConn, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { log.Printf("Dial %s failed\n", u.Host) return nil, nil, err } c := tls.Client(tcpConn, conf) err = c.Handshake() if err != nil { log.Printf("Tls hadnshake to %s failed\n", u.Host) return nil, nil, err } wsHeaders := http.Header{ "Origin": {u.Host}, "Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"}, } ws, _, err := websocket.NewClient(c, &u, wsHeaders, 1024, 1024) if err != nil { log.Fatal("NewClient dial failed:", err) return nil, nil, err } log.Debugf("connecting to %s", u.String()) return ws, tcpConn, nil } func main() { flag.Parse() if *addr == "nil" { log.Errorf("please input addr: Use -addr . Like -addr 10.91.117.179:8443") return } if *thread == 0 { log.Errorf("please input thread count(Better less 100): Use -thread") return } if *getnum == 0 { log.Errorf("please input get num in each goroutine: Use -getnum") return } LogInit() ruleCnt := loadMineFile() rand.Seed(time.Now().UnixNano()) log.Infof("------------------Start a New Test----------------------------") log.Infof(" Connecting to %s ", *addr) log.Infof(" Concurrency cnt: %d ", *thread) log.Infof(" Each conn test num: %d ", *getnum) log.Infof(" Test seed: %d ", ruleCnt) var wg sync.WaitGroup wg.Add(*thread) for i := 1; i <= int(*thread); i++ { log.Debugf("-------THREAD(%d) start", i) go func(id int) { wc, tc, err := tlsConn() if err != nil { log.Fatalf("dial:", err) } defer wg.Done() defer wc.Close() setTcpOption(tc, TCP_NO_DELAY) setTcpOption(tc, TCP_QUICK_ACK) /*并发,等待其他连接就绪*/ time.Sleep(3 * time.Second) for j := 0; j < int(*getnum); j++ { if *thread > 50 { time.Sleep(time.Second) } t := time.Now() index := rand.Intn(ruleCnt) if len(mineDomain[index]) == 0 { log.Debugf("mineDomain[%d] = :%s", index, mineDomain[index]) } key := []byte(msgHead + mineDomain[index]) log.Debugf("key :%s", key) //key := []byte(msgHead + "guold.net") err := wc.WriteMessage(websocket.TextMessage, key) if err != nil { log.Errorf("write:", err) return } _, message, err := wc.ReadMessage() if err != nil { log.Errorf("read:", err) return } setTcpOption(tc, TCP_QUICK_ACK) log.Debugf("message:%s", message) if len(message) <= 32 { log.Warnf("can not find key: %s", key) } /*统计查询延时*/ tDur := time.Since(t) if tDur < 1000000 { atomic.AddUint32(&outTimeLess1Cnt, 1) } else if (tDur > 1000000) && (tDur < 20000000) { atomic.AddUint32(&outTime1to2Cnt, 1) } else if (tDur > 2000000) && (tDur < 3000000) { atomic.AddUint32(&outTime2to3Cnt, 1) } else if (tDur > 3000000) && (tDur < 4000000) { atomic.AddUint32(&outTime3to4Cnt, 1) } else if (tDur > 4000000) && (tDur < 5000000) { atomic.AddUint32(&outTime4to5Cnt, 1) } else if (tDur > 5000000) && (tDur < 10000000) { atomic.AddUint32(&outTime5to10Cnt, 1) } else if (tDur > 10000000) && (tDur < 15000000) { atomic.AddUint32(&outTime10to15Cnt, 1) } else if (tDur > 10000000) && (tDur < 15000000) { atomic.AddUint32(&outTime10to15Cnt, 1) } else if (tDur > 15000000) && (tDur < 20000000) { atomic.AddUint32(&outTime15to20Cnt, 1) } else { log.Warnf("----toooooooooooo long time :%v localaddr:%s key:%s", tDur, wc.LocalAddr(), mineDomain[index]) atomic.AddUint32(&outTimeOver20Cnt, 1) } } }(i) } wg.Wait() time.Sleep(5 * time.Second) log.Infof("------------------------------------------------ ") log.Infof("----outTimeCnt <1ms :%d ", outTimeLess1Cnt) log.Infof("----outTimeCnt 1--2ms :%d ", outTime1to2Cnt) log.Infof("----outTimeCnt 2--3ms :%d ", outTime2to3Cnt) log.Infof("----outTimeCnt 3--4ms :%d ", outTime3to4Cnt) log.Infof("----outTimeCnt 4--5ms :%d ", outTime4to5Cnt) log.Infof("----outTimeCnt 5--10ms :%d ", outTime5to10Cnt) log.Infof("----outTimeCnt 10--15ms :%d ", outTime10to15Cnt) log.Infof("----outTimeCnt 15--20ms :%d ", outTime15to20Cnt) log.Infof("----outTimeCnt >20ms :%d ", outTimeOver20Cnt) log.Infof("------------------------------------------------ ") } func loadMineFile() int { var i int file, err := os.Open("mine.rules") if err != nil { log.Errorf("Open mine.rules failed err:%s", err) } defer file.Close() scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) //是否有下一行 for scanner.Scan() { if len(scanner.Text()) > 0 { key := strings.Split(scanner.Text(), "|") mineDomain[i] = key[0] i++ } } log.Debugf("--mine rules cnt[%d]\n", i) return i } func setTcpOption(tcpConn *net.TCPConn, t int) { f, err := tcpConn.File() if err != nil { log.Errorf("tcpConn File error: %s\n", err) return } if t == TCP_QUICK_ACK { err = syscall.SetsockoptInt(int(f.Fd()), syscall.IPPROTO_TCP, syscall.TCP_QUICKACK, 1) } else if t == TCP_NO_DELAY { err = syscall.SetsockoptInt(int(f.Fd()), syscall.IPPROTO_TCP, syscall.TCP_NODELAY, 1) } if err != nil { log.Errorf("setTcpOption ERROR: %s\n", err) return } } func LogInit() { log = logrus.New() file, err := os.OpenFile("websocket_client.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err == nil { log.Out = file } else { log.Infof("Failed to log to file") } log.SetLevel(logrus.Level(*logLevel)) }
package mavlink2 /* Generated using mavgen - https://github.com/ArduPilot/pymavlink/ Copyright 2020 queue-b <https://github.com/queue-b> Permission is hereby granted, free of charge, to any person obtaining a copy of the generated software (the "Generated Software"), to deal in the Generated Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Generated Software, and to permit persons to whom the Generated Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Generated Software. THE GENERATED SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE GENERATED SOFTWARE OR THE USE OR OTHER DEALINGS IN THE GENERATED SOFTWARE. */ import ( "bytes" "encoding/binary" "fmt" "text/tabwriter" ) // Frame represents a MAVLink frame containing a MAVLink message type Frame interface { GetVersion() int GetMessageLength() uint8 GetMessageSequence() uint8 GetSenderSystemID() uint8 GetSenderComponentID() uint8 GetMessageBytes() []byte GetMessageID() uint32 GetChecksum() uint16 GetChecksumInput() []byte Bytes() []byte } // FrameV1 represents a MAVLink V1 Frame type FrameV1 []byte // Bytes returns the Frame as a byte array func (frame FrameV1) Bytes() []byte { return frame } // GetVersion returns the version of the Frame func (frame FrameV1) GetVersion() int { return 1 } // GetMessageLength returns the length of the message contained in the Frame func (frame FrameV1) GetMessageLength() uint8 { return frame[1] } // GetMessageSequence the sequence number of the message contained in the Frame func (frame FrameV1) GetMessageSequence() uint8 { return frame[2] } // GetMessageBytes returns the message contained in the Frame as a byte array func (frame FrameV1) GetMessageBytes() []byte { return frame[6 : 6+frame.GetMessageLength()] } // GetSenderSystemID returns the ID of the system that sent the Frame func (frame FrameV1) GetSenderSystemID() uint8 { return frame[3] } // GetSenderComponentID returns the ID of the component that sent the Frame func (frame FrameV1) GetSenderComponentID() uint8 { return frame[4] } // GetMessageID returns the ID of the message contained in the Frame func (frame FrameV1) GetMessageID() uint32 { return uint32(frame[5]) } // GetChecksum returns the checksum of the Frame contents func (frame FrameV1) GetChecksum() uint16 { return binary.LittleEndian.Uint16(frame[len(frame)-2:]) } // GetChecksumInput returns the contents of the Frame used to calculate the checksum func (frame FrameV1) GetChecksumInput() []byte { return frame[1 : len(frame)-2] } func (frame FrameV1) String() string { var buffer bytes.Buffer writer := tabwriter.NewWriter(&buffer, 0, 0, 2, ' ', 0) fmt.Fprintf(writer, "Version:\t%v\nMessageLength:\t%v\nSenderSystemID:\t%v\nSenderComponentID:\t%v\nMessageID:\t%v\nChecksum:\t%v", frame.GetVersion(), frame.GetMessageLength(), frame.GetSenderSystemID(), frame.GetSenderComponentID(), frame.GetMessageID(), frame.GetChecksum(), ) writer.Flush() return string(buffer.Bytes()) } // FrameV2 represents a MAVLink V1 Frame type FrameV2 []byte // GetBytes returns the Frame as a byte array func (frame FrameV2) Bytes() []byte { return frame } // GetVersion returns the version of the Frame func (frame FrameV2) GetVersion() int { return 2 } // GetMessageLength returns the length of the message contained in the Frame func (frame FrameV2) GetMessageLength() uint8 { return frame[1] } // GetIncompatibilityFlags returns the incompatibility flags for the Frame func (frame FrameV2) GetIncompatibilityFlags() uint8 { return frame[2] } // GetCompatibilityFlags returns the compatibility flags for the Frame func (frame FrameV2) GetCompatibilityFlags() uint8 { return frame[3] } // GetMessageSequence the sequence number of the message contained in the Frame func (frame FrameV2) GetMessageSequence() uint8 { return frame[4] } // GetSenderSystemID returns the ID of the system that sent the Frame func (frame FrameV2) GetSenderSystemID() uint8 { return frame[5] } // GetSenderComponentID returns the ID of the component that sent the Frame func (frame FrameV2) GetSenderComponentID() uint8 { return frame[6] } // GetMessageID returns the ID of the message contained in the Frame func (frame FrameV2) GetMessageID() uint32 { messageID := make([]byte, 4) copy(messageID[0:3], frame[7:10]) return binary.LittleEndian.Uint32(messageID) } // GetMessageBytes returns the message contained in the Frame as a byte array func (frame FrameV2) GetMessageBytes() []byte { start := 10 end := start + int(frame.GetMessageLength()) return frame[start:end] } // GetChecksum returns the checksum of the Frame contents func (frame FrameV2) GetChecksum() uint16 { start := int(frame.GetMessageLength()) + 10 end := start + 2 return binary.LittleEndian.Uint16(frame[start:end]) } // GetChecksumInput returns the contents of the Frame used to calculate the checksum func (frame FrameV2) GetChecksumInput() []byte { start := 1 end := int(frame.GetMessageLength()) + 10 return frame[start:end] } // GetSignature returns the V2 Signature of the frame, if it exists func (frame FrameV2) GetSignature() []byte { if frame.GetCompatibilityFlags()&CompatibilityFlagSignature != CompatibilityFlagSignature { return nil } return frame[frame.GetMessageLength()+12:] } func (frame FrameV2) String() string { var buffer bytes.Buffer writer := tabwriter.NewWriter(&buffer, 0, 0, 2, ' ', 0) fmt.Fprintf(writer, "Version:\t%v\nSigned:\t%v\nMessageLength:\t%v\nIncompatibilityFlags:\t%v\nCompatibilityFlags:\t%v\nSenderSystemID:\t%v\nSenderComponentID:\t%v\nMessageID:\t%v\nChecksum:\t0x%x", frame.GetVersion(), frame.GetSignature() != nil, frame.GetMessageLength(), frame.GetIncompatibilityFlags(), frame.GetCompatibilityFlags(), frame.GetSenderSystemID(), frame.GetSenderComponentID(), frame.GetMessageID(), frame.GetChecksum(), ) if frame.GetSignature() != nil { fmt.Fprintf(writer, "\nSignature:\t%x", frame.GetSignature()) } writer.Flush() return string(buffer.Bytes()) } // ErrFrameTooShort indicates the Frame did not contain enough bytes to complete the requested operation var ErrFrameTooShort = fmt.Errorf("Not enough bytes in Frame") // ErrUnknownStartByte indicates the Frame started with an unknown start byte (magic byte) var ErrUnknownStartByte = fmt.Errorf("Start byte is not 0x%x (V1) or 0x%x (V2)", V1StartByte, V2StartByte) // ErrMessageTooShort indicates that the Message length in the header is shorter than the // minimum length allowed for the Message var ErrMessageTooShort = fmt.Errorf("Message too short") // ErrMessageTooLong indicates that the Message length in the header is longer than the // maximum length allowed for the Message var ErrMessageTooLong = fmt.Errorf("Message too long") // ErrInvalidChecksum indicates that the Message checksum is invalid var ErrInvalidChecksum = fmt.Errorf("Invalid checksum") // ErrUnknownMessage indicates that the Message is not defined in one of the loaded Dialects var ErrUnknownMessage = fmt.Errorf("Unknown message") // ErrPrivateField indicates that a Message contains private fields and cannot be unmarshalled using binary.Read var ErrPrivateField = fmt.Errorf("Struct contains one or more private fields that cannot be unmarshalled using binary.Read") // ErrUnsupportedVersion indicates that the version requested is not supported by this library var ErrUnsupportedVersion = fmt.Errorf("The version requested is not supported by this library") // ErrDecodeV2MessageV1Frame indicates that a request was made to decode a V2 Message from a V1 Frame var ErrDecodeV2MessageV1Frame = fmt.Errorf("Unable to decode a V2 message from a V1 Frame") // ErrEncodeV2MessageV1Frame indicates that a request was made to encode a V2 Message for use with a V1 Frame var ErrEncodeV2MessageV1Frame = fmt.Errorf("Unable to encode a V2 message to a V1 Frame") // ErrValueTooLong indicates that a Message field is unable to hold the requested string // and that the string was truncated to fit var ErrValueTooLong = fmt.Errorf("The input string was too long and was truncated") // FrameFromBytes returns a Frame containing the input bytes, // or an error if the first byte is not a valid frame start func FrameFromBytes(raw []byte) (frame Frame, err error) { if len(raw) == 0 { err = ErrFrameTooShort return } startByte := raw[0] if startByte == V1StartByte { frame = FrameV1(raw) } else if startByte == V2StartByte { frame = FrameV2(raw) } else { err = ErrUnknownStartByte } return }
package strings import ( "strings" "testing" ) func TestIndex(t *testing.T) { t.Parallel() type args struct { str string strPart string } tests := []struct { name string args args want int }{ {"Mass 1", args{"Cod3r é show", "Cod3r"}, 0}, {"Mass 2", args{"", ""}, 0}, {"Mass 3", args{"Opa", "opa"}, -1}, {"Mass 4", args{"leonardo", "o"}, 2}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := strings.Index(tt.args.str, tt.args.strPart); got != tt.want { t.Errorf("strings.Index() = %v, want %v", got, tt.want) } }) } } // Teste da aula do curso // const msgIndex = "%s (parte: %s) - índices: esperado (%d) <> encontrado (%d)." // func TestIndex(t *testing.T) { // t.Parallel() // testes := []struct { // texto string // parte string // esperado int // }{ // {"Cod3r é show", "Cod3r", 0}, // {"", "", 0}, // {"Opa", "opa", -1}, // {"leonardo", "o", 2}, // } // for _, teste := range testes { // t.Logf("Massa: %v", teste) // atual := strings.Index(teste.texto, teste.parte) // if atual != teste.esperado { // t.Errorf(msgIndex, teste.texto, teste.parte, teste.esperado, atual) // } // } // }
package main import ( "os" "github.com/infra-whizz/wzsd" "github.com/isbm/go-nanoconf" "github.com/urfave/cli/v2" ) func run(ctx *cli.Context) error { stateDaemon := wzsd.NewWzStateDaemon() stateDaemon.Run().AppLoop() conf := nanoconf.NewConfig(ctx.String("config")) stateDaemon.GetTransport().AddNatsServerURL( conf.Find("transport").String("host", ""), conf.Find("transport").DefaultInt("port", "", 4222), ) stateDaemon.Run().AppLoop() cli.ShowAppHelpAndExit(ctx, 1) return nil } func main() { appname := "wz-state" confpath := nanoconf.NewNanoconfFinder(appname).DefaultSetup(nil) app := &cli.App{ Version: "0.1 Alpha", Name: appname, Usage: "Whizz State Worker Daemon", Action: run, Flags: []cli.Flag{ &cli.StringFlag{ Name: "config", Aliases: []string{"c"}, Usage: "Path to configuration file", Required: false, Value: confpath.SetDefaultConfig(confpath.FindFirst()).FindDefault(), }, }, } if err := app.Run(os.Args); err != nil { panic(err) } }
package main import "fmt" type Test interface { } type Stu struct { Name string } func main() { var stu Stu var t Test = stu fmt.Println(t) var t2 interface{} = stu fmt.Println(t2) var num = 888 t2 = num fmt.Println(t2) }
package main import ( "flag" "fmt" "os" "path/filepath" "strings" "github.com/pkg/errors" "github.com/syncromatics/go-kit/database" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) type settings struct { KubernetesConfig *rest.Config DatabaseSettings *database.PostgresDatabaseSettings ShouldScan bool } func getSettings() (*settings, error) { var config *rest.Config var err error _, ok := os.LookupEnv("KUBERNETES_SERVICE_HOST") if !ok { config, err = getLocalConfig() if err != nil { return nil, errors.Wrap(err, "failed getting kubernetes config") } } else { config, err = getClusterConfig() if err != nil { return nil, errors.Wrap(err, "failed getting kubernetes config") } } shouldScan := true _, ok = os.LookupEnv("NO_SCAN") if ok { shouldScan = false } errors := []string{} ds := &database.PostgresDatabaseSettings{} ds.Host, ok = os.LookupEnv("DATABASE_HOST") if !ok { errors = append(errors, "DATABASE_HOST") } ds.Name, ok = os.LookupEnv("DATABASE_NAME") if !ok { errors = append(errors, "DATABASE_NAME") } ds.User, ok = os.LookupEnv("DATABASE_USER") if !ok { errors = append(errors, "DATABASE_USER") } ds.Password, ok = os.LookupEnv("DATABASE_PASSWORD") if !ok { errors = append(errors, "DATABASE_PASSWORD") } if len(errors) > 0 { return nil, fmt.Errorf("Missing required environment variables: %s", strings.Join(errors, ", ")) } return &settings{ KubernetesConfig: config, DatabaseSettings: ds, ShouldScan: shouldScan, }, nil } func homeDir() string { if h := os.Getenv("HOME"); h != "" { return h } return os.Getenv("USERPROFILE") // windows } func getLocalConfig() (*rest.Config, error) { var kubeconfig *string if home := homeDir(); home != "" { kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") } else { kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file") } flag.Parse() config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) if err != nil { return nil, errors.Wrap(err, "failed building config") } return config, nil } func getClusterConfig() (*rest.Config, error) { config, err := rest.InClusterConfig() if err != nil { return nil, errors.Wrap(err, "failed getting in cluster conifg") } return config, nil }
package stack // stackOverflowError ... type stackOverflowError struct{} // Error ... func (s *stackOverflowError) Error() string { return "Error: stack overflow!" }
package cmd import ( "fmt" "log" "os" "path" "github.com/ncw/rclone/fs" "github.com/spf13/cobra" ) // Version is rhttpserve's current version number. const Version = "v0.0.1" var ( // Verbose tracks whether a verbose flag was passed into the command line. Verbose bool // version tracks whether a version flag was passed into the command line. version bool ) // Root is the main rhttpserve command var Root = &cobra.Command{ Use: "rhttpserve", Short: "Serves files out of an rclone store.", Long: ` Rhttpserve is a command line program to private serve files out of an rclone store. `, } // runRoot implements the main rclone command with no subcommands func runRoot(cmd *cobra.Command, args []string) { if version { ShowVersion() os.Exit(0) } else { _ = Root.Usage() fmt.Fprintf(os.Stderr, "Command not found.\n") os.Exit(1) } } func init() { Root.Run = runRoot Root.Flags().BoolVarP(&version, "version", "V", false, "Print the version number") Root.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "Verbose output") cobra.OnInitialize(initConfig) } // NewFsSrc creates a new src fs from the arguments func NewFsSrc(args []string) fs.Fs { fsrc := newFsSrc(args[0]) fs.CalculateModifyWindow(fsrc) return fsrc } // CheckArgs checks there are enough arguments and prints a message if not func CheckArgs(MinArgs, MaxArgs int, cmd *cobra.Command, args []string) { if len(args) < MinArgs { _ = cmd.Usage() fmt.Fprintf(os.Stderr, "Command %s needs %d arguments mininum\n", cmd.Name(), MinArgs) os.Exit(1) } else if len(args) > MaxArgs { _ = cmd.Usage() fmt.Fprintf(os.Stderr, "Command %s needs %d arguments maximum\n", cmd.Name(), MaxArgs) os.Exit(1) } } // ShowVersion prints the version to stdout func ShowVersion() { fmt.Printf("rclone %s\n", Version) } // initConfig is run by cobra after initialising the flags func initConfig() { // Load the rest of the config now we have started the logger fs.LoadConfig() } // newFsSrc creates a src Fs from a name // // This can point to a file func newFsSrc(remote string) fs.Fs { fsInfo, configName, fsPath, err := fs.ParseRemote(remote) if err != nil { fs.Stats.Error() log.Fatalf("Failed to create file system for %q: %v", remote, err) } f, err := fsInfo.NewFs(configName, fsPath) if err == fs.ErrorIsFile { if !fs.Config.Filter.InActive() { fs.Stats.Error() log.Fatalf("Can't limit to single files when using filters: %v", remote) } // Limit transfers to this file err = fs.Config.Filter.AddFile(path.Base(fsPath)) // Set --no-traverse as only one file fs.Config.NoTraverse = true } if err != nil { fs.Stats.Error() log.Fatalf("Failed to create file system for %q: %v", remote, err) } return f }
package log import ( "fmt" "log" ) type Entity struct { message string Data interface{} Err interface{} } func Newf(format string, args ...interface{}) *Entity { e := &Entity{} e.message = fmt.Sprintf(format, args...) return e } func New(args ...interface{}) *Entity { e := &Entity{} e.message = fmt.Sprint(args...) return e } func (e *Entity) WithData(v interface{}) *Entity { e.Data = v return e } func (e *Entity) WithError(v interface{}) *Entity { e.Err = v return e } func (e *Entity) Error() { log.Println(e.message) } func (e *Entity) Info() { log.Println(e.message) } func (e *Entity) Debug() { log.Println(e.message) }
package game import ( "fmt" "testing" "time" ) func TestCreateCard(t *testing.T) { var cards []int var n1 = 9 for i := 0; i < 10; i++ { time.Sleep(time.Millisecond*100) result := createCard(cards, n1) v := result[3]%13 + 1 + result[4]%13 + 1 if v != n1 { t.Error("错误") return } var tResult []int for i := 0; i < 5; i++ { tResult = append(tResult,result[i]%13 + 1) } fmt.Println(result,tResult, v) } }
package main import ( "crypto/tls" "crypto/x509" "fmt" "io/ioutil" "log" "net/http" "strings" ) func main() { roots := x509.NewCertPool() pem, err := ioutil.ReadFile("./conf/server.pem") if err != nil { log.Printf("read crt file error:%v\n", err) } ok := roots.AppendCertsFromPEM(pem) if !ok { panic("failed to parse root certificate") } tr := &http.Transport{ TLSClientConfig: &tls.Config{ RootCAs: roots, }, } client := &http.Client{Transport: tr} resp, err := client.Get("https://localhost:8012/hello") if err != nil { panic("failed to connect: " + err.Error()) } content, _ := ioutil.ReadAll(resp.Body) s := strings.TrimSpace(string(content)) fmt.Println(s) }
package test import ( db "bareksa-test/database" md "bareksa-test/model" r "bareksa-test/repository" st "bareksa-test/struck" "context" "github.com/stretchr/testify/suite" ) type NewsRepositorySuite struct { suite.Suite newsRepository md.NewsRepository } func (suite *NewsRepositorySuite) SetupSuite() { repository := r.InitiateNewsRepository(db.Databases) suite.newsRepository = repository } func (suite *NewsRepositorySuite) TestAdd() { // var var logs []st.Log ctx := context.Background() input := md.News{ Name: "Testing News - Unit Test", TopicID: "TO2", } _, err := suite.newsRepository.Add(ctx, input, &logs) suite.NoError(err, "no error") }
package worker import ( "context" "fmt" "github.com/rs/zerolog" "github.com/tomarrell/lbadd/internal/executor" ) // Worker is a database worker node. // // w := worker.New(log, exec) // err := w.Connect(ctx, ":34213") type Worker struct { log zerolog.Logger exec executor.Executor } // New creates a new worker with the given logger, that will replicate master // commands with the given executor. func New(log zerolog.Logger, exec executor.Executor) *Worker { return &Worker{ log: log, exec: exec, } } // Connect connects the worker to a running and available master node. Use the // given context to close the connection and terminate the worker node. // Canceling the context will cause the worker to attempt a graceful shutdown. func (w *Worker) Connect(ctx context.Context, addr string) error { w.log.Info(). Str("addr", addr). Msg("connect") return fmt.Errorf("unimplemented") }
// +build gotask package gotasks import ( "archive/zip" "encoding/xml" "fmt" "io" "log" "net/http" "os" "path" "path/filepath" "regexp" "strings" "text/template" "github.com/huin/goutil/codegen" "github.com/jingweno/gotask/tasking" "gx/ipfs/QmVwfv63beSAAirq3tiLY6fkNqvjThLnCofL7363YkaScy/goupnp" "gx/ipfs/QmVwfv63beSAAirq3tiLY6fkNqvjThLnCofL7363YkaScy/goupnp/scpd" ) var ( deviceURNPrefix = "urn:schemas-upnp-org:device:" serviceURNPrefix = "urn:schemas-upnp-org:service:" ) // DCP contains extra metadata to use when generating DCP source files. type DCPMetadata struct { Name string // What to name the Go DCP package. OfficialName string // Official name for the DCP. DocURL string // Optional - URL for further documentation about the DCP. XMLSpecURL string // Where to download the XML spec from. // Any special-case functions to run against the DCP before writing it out. Hacks []DCPHackFn } var dcpMetadata = []DCPMetadata{ { Name: "internetgateway1", OfficialName: "Internet Gateway Device v1", DocURL: "http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf", XMLSpecURL: "http://upnp.org/specs/gw/UPnP-gw-IGD-TestFiles-20010921.zip", Hacks: []DCPHackFn{totalBytesHack}, }, { Name: "internetgateway2", OfficialName: "Internet Gateway Device v2", DocURL: "http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v2-Device.pdf", XMLSpecURL: "http://upnp.org/specs/gw/UPnP-gw-IGD-Testfiles-20110224.zip", Hacks: []DCPHackFn{ func(dcp *DCP) error { missingURN := "urn:schemas-upnp-org:service:WANIPv6FirewallControl:1" if _, ok := dcp.ServiceTypes[missingURN]; ok { return nil } urnParts, err := extractURNParts(missingURN, serviceURNPrefix) if err != nil { return err } dcp.ServiceTypes[missingURN] = urnParts return nil }, totalBytesHack, }, }, { Name: "av1", OfficialName: "MediaServer v1 and MediaRenderer v1", DocURL: "http://upnp.org/specs/av/av1/", XMLSpecURL: "http://upnp.org/specs/av/UPnP-av-TestFiles-20070927.zip", }, } func totalBytesHack(dcp *DCP) error { for _, service := range dcp.Services { if service.URN == "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" { variables := service.SCPD.StateVariables for key, variable := range variables { varName := variable.Name if varName == "TotalBytesSent" || varName == "TotalBytesReceived" { // Fix size of total bytes which is by default ui4 or maximum 4 GiB. variable.DataType.Name = "ui8" variables[key] = variable } } break } } return nil } type DCPHackFn func(*DCP) error // NAME // specgen - generates Go code from the UPnP specification files. // // DESCRIPTION // The specification is available for download from: // // OPTIONS // -s, --specs_dir=<spec directory> // Path to the specification storage directory. This is used to find (and download if not present) the specification ZIP files. Defaults to 'specs' // -o, --out_dir=<output directory> // Path to the output directory. This is is where the DCP source files will be placed. Should normally correspond to the directory for github.com/huin/goupnp/dcps. Defaults to '../dcps' // --nogofmt // Disable passing the output through gofmt. Do this if debugging code output problems and needing to see the generated code prior to being passed through gofmt. func TaskSpecgen(t *tasking.T) { specsDir := fallbackStrValue("specs", t.Flags.String("specs_dir"), t.Flags.String("s")) if err := os.MkdirAll(specsDir, os.ModePerm); err != nil { t.Fatalf("Could not create specs-dir %q: %v\n", specsDir, err) } outDir := fallbackStrValue("../dcps", t.Flags.String("out_dir"), t.Flags.String("o")) useGofmt := !t.Flags.Bool("nogofmt") NEXT_DCP: for _, d := range dcpMetadata { specFilename := filepath.Join(specsDir, d.Name+".zip") err := acquireFile(specFilename, d.XMLSpecURL) if err != nil { t.Logf("Could not acquire spec for %s, skipping: %v\n", d.Name, err) continue NEXT_DCP } dcp := newDCP(d) if err := dcp.processZipFile(specFilename); err != nil { log.Printf("Error processing spec for %s in file %q: %v", d.Name, specFilename, err) continue NEXT_DCP } for i, hack := range d.Hacks { if err := hack(dcp); err != nil { log.Printf("Error with Hack[%d] for %s: %v", i, d.Name, err) continue NEXT_DCP } } dcp.writePackage(outDir, useGofmt) if err := dcp.writePackage(outDir, useGofmt); err != nil { log.Printf("Error writing package %q: %v", dcp.Metadata.Name, err) continue NEXT_DCP } } } func fallbackStrValue(defaultValue string, values ...string) string { for _, v := range values { if v != "" { return v } } return defaultValue } func acquireFile(specFilename string, xmlSpecURL string) error { if f, err := os.Open(specFilename); err != nil { if !os.IsNotExist(err) { return err } } else { f.Close() return nil } resp, err := http.Get(xmlSpecURL) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("could not download spec %q from %q: ", specFilename, xmlSpecURL, resp.Status) } tmpFilename := specFilename + ".download" w, err := os.Create(tmpFilename) if err != nil { return err } defer w.Close() _, err = io.Copy(w, resp.Body) if err != nil { return err } return os.Rename(tmpFilename, specFilename) } // DCP collects together information about a UPnP Device Control Protocol. type DCP struct { Metadata DCPMetadata DeviceTypes map[string]*URNParts ServiceTypes map[string]*URNParts Services []SCPDWithURN } func newDCP(metadata DCPMetadata) *DCP { return &DCP{ Metadata: metadata, DeviceTypes: make(map[string]*URNParts), ServiceTypes: make(map[string]*URNParts), } } func (dcp *DCP) processZipFile(filename string) error { archive, err := zip.OpenReader(filename) if err != nil { return fmt.Errorf("error reading zip file %q: %v", filename, err) } defer archive.Close() for _, deviceFile := range globFiles("*/device/*.xml", archive) { if err := dcp.processDeviceFile(deviceFile); err != nil { return err } } for _, scpdFile := range globFiles("*/service/*.xml", archive) { if err := dcp.processSCPDFile(scpdFile); err != nil { return err } } return nil } func (dcp *DCP) processDeviceFile(file *zip.File) error { var device goupnp.Device if err := unmarshalXmlFile(file, &device); err != nil { return fmt.Errorf("error decoding device XML from file %q: %v", file.Name, err) } var mainErr error device.VisitDevices(func(d *goupnp.Device) { t := strings.TrimSpace(d.DeviceType) if t != "" { u, err := extractURNParts(t, deviceURNPrefix) if err != nil { mainErr = err } dcp.DeviceTypes[t] = u } }) device.VisitServices(func(s *goupnp.Service) { u, err := extractURNParts(s.ServiceType, serviceURNPrefix) if err != nil { mainErr = err } dcp.ServiceTypes[s.ServiceType] = u }) return mainErr } func (dcp *DCP) writePackage(outDir string, useGofmt bool) error { packageDirname := filepath.Join(outDir, dcp.Metadata.Name) err := os.MkdirAll(packageDirname, os.ModePerm) if err != nil && !os.IsExist(err) { return err } packageFilename := filepath.Join(packageDirname, dcp.Metadata.Name+".go") packageFile, err := os.Create(packageFilename) if err != nil { return err } var output io.WriteCloser = packageFile if useGofmt { if output, err = codegen.NewGofmtWriteCloser(output); err != nil { packageFile.Close() return err } } if err = packageTmpl.Execute(output, dcp); err != nil { output.Close() return err } return output.Close() } func (dcp *DCP) processSCPDFile(file *zip.File) error { scpd := new(scpd.SCPD) if err := unmarshalXmlFile(file, scpd); err != nil { return fmt.Errorf("error decoding SCPD XML from file %q: %v", file.Name, err) } scpd.Clean() urnParts, err := urnPartsFromSCPDFilename(file.Name) if err != nil { return fmt.Errorf("could not recognize SCPD filename %q: %v", file.Name, err) } dcp.Services = append(dcp.Services, SCPDWithURN{ URNParts: urnParts, SCPD: scpd, }) return nil } type SCPDWithURN struct { *URNParts SCPD *scpd.SCPD } func (s *SCPDWithURN) WrapArguments(args []*scpd.Argument) (argumentWrapperList, error) { wrappedArgs := make(argumentWrapperList, len(args)) for i, arg := range args { wa, err := s.wrapArgument(arg) if err != nil { return nil, err } wrappedArgs[i] = wa } return wrappedArgs, nil } func (s *SCPDWithURN) wrapArgument(arg *scpd.Argument) (*argumentWrapper, error) { relVar := s.SCPD.GetStateVariable(arg.RelatedStateVariable) if relVar == nil { return nil, fmt.Errorf("no such state variable: %q, for argument %q", arg.RelatedStateVariable, arg.Name) } cnv, ok := typeConvs[relVar.DataType.Name] if !ok { return nil, fmt.Errorf("unknown data type: %q, for state variable %q, for argument %q", relVar.DataType.Type, arg.RelatedStateVariable, arg.Name) } return &argumentWrapper{ Argument: *arg, relVar: relVar, conv: cnv, }, nil } type argumentWrapper struct { scpd.Argument relVar *scpd.StateVariable conv conv } func (arg *argumentWrapper) AsParameter() string { return fmt.Sprintf("%s %s", arg.Name, arg.conv.ExtType) } func (arg *argumentWrapper) HasDoc() bool { rng := arg.relVar.AllowedValueRange return ((rng != nil && (rng.Minimum != "" || rng.Maximum != "" || rng.Step != "")) || len(arg.relVar.AllowedValues) > 0) } func (arg *argumentWrapper) Document() string { relVar := arg.relVar if rng := relVar.AllowedValueRange; rng != nil { var parts []string if rng.Minimum != "" { parts = append(parts, fmt.Sprintf("minimum=%s", rng.Minimum)) } if rng.Maximum != "" { parts = append(parts, fmt.Sprintf("maximum=%s", rng.Maximum)) } if rng.Step != "" { parts = append(parts, fmt.Sprintf("step=%s", rng.Step)) } return "allowed value range: " + strings.Join(parts, ", ") } if len(relVar.AllowedValues) != 0 { return "allowed values: " + strings.Join(relVar.AllowedValues, ", ") } return "" } func (arg *argumentWrapper) Marshal() string { return fmt.Sprintf("soap.Marshal%s(%s)", arg.conv.FuncSuffix, arg.Name) } func (arg *argumentWrapper) Unmarshal(objVar string) string { return fmt.Sprintf("soap.Unmarshal%s(%s.%s)", arg.conv.FuncSuffix, objVar, arg.Name) } type argumentWrapperList []*argumentWrapper func (args argumentWrapperList) HasDoc() bool { for _, arg := range args { if arg.HasDoc() { return true } } return false } type conv struct { FuncSuffix string ExtType string } // typeConvs maps from a SOAP type (e.g "fixed.14.4") to the function name // suffix inside the soap module (e.g "Fixed14_4") and the Go type. var typeConvs = map[string]conv{ "ui1": conv{"Ui1", "uint8"}, "ui2": conv{"Ui2", "uint16"}, "ui4": conv{"Ui4", "uint32"}, "ui8": conv{"Ui8", "uint64"}, "i1": conv{"I1", "int8"}, "i2": conv{"I2", "int16"}, "i4": conv{"I4", "int32"}, "int": conv{"Int", "int64"}, "r4": conv{"R4", "float32"}, "r8": conv{"R8", "float64"}, "number": conv{"R8", "float64"}, // Alias for r8. "fixed.14.4": conv{"Fixed14_4", "float64"}, "float": conv{"R8", "float64"}, "char": conv{"Char", "rune"}, "string": conv{"String", "string"}, "date": conv{"Date", "time.Time"}, "dateTime": conv{"DateTime", "time.Time"}, "dateTime.tz": conv{"DateTimeTz", "time.Time"}, "time": conv{"TimeOfDay", "soap.TimeOfDay"}, "time.tz": conv{"TimeOfDayTz", "soap.TimeOfDay"}, "boolean": conv{"Boolean", "bool"}, "bin.base64": conv{"BinBase64", "[]byte"}, "bin.hex": conv{"BinHex", "[]byte"}, "uri": conv{"URI", "*url.URL"}, } func globFiles(pattern string, archive *zip.ReadCloser) []*zip.File { var files []*zip.File for _, f := range archive.File { if matched, err := path.Match(pattern, f.Name); err != nil { // This shouldn't happen - all patterns are hard-coded, errors in them // are a programming error. panic(err) } else if matched { files = append(files, f) } } return files } func unmarshalXmlFile(file *zip.File, data interface{}) error { r, err := file.Open() if err != nil { return err } decoder := xml.NewDecoder(r) defer r.Close() return decoder.Decode(data) } type URNParts struct { URN string Name string Version string } func (u *URNParts) Const() string { return fmt.Sprintf("URN_%s_%s", u.Name, u.Version) } // extractURNParts extracts the name and version from a URN string. func extractURNParts(urn, expectedPrefix string) (*URNParts, error) { if !strings.HasPrefix(urn, expectedPrefix) { return nil, fmt.Errorf("%q does not have expected prefix %q", urn, expectedPrefix) } parts := strings.SplitN(strings.TrimPrefix(urn, expectedPrefix), ":", 2) if len(parts) != 2 { return nil, fmt.Errorf("%q does not have a name and version", urn) } name, version := parts[0], parts[1] return &URNParts{urn, name, version}, nil } var scpdFilenameRe = regexp.MustCompile( `.*/([a-zA-Z0-9]+)([0-9]+)\.xml`) func urnPartsFromSCPDFilename(filename string) (*URNParts, error) { parts := scpdFilenameRe.FindStringSubmatch(filename) if len(parts) != 3 { return nil, fmt.Errorf("SCPD filename %q does not have expected number of parts", filename) } name, version := parts[1], parts[2] return &URNParts{ URN: serviceURNPrefix + name + ":" + version, Name: name, Version: version, }, nil } var packageTmpl = template.Must(template.New("package").Parse(`{{$name := .Metadata.Name}} // Client for UPnP Device Control Protocol {{.Metadata.OfficialName}}. // {{if .Metadata.DocURL}} // This DCP is documented in detail at: {{.Metadata.DocURL}}{{end}} // // Typically, use one of the New* functions to create clients for services. package {{$name}} // *********************************************************** // GENERATED FILE - DO NOT EDIT BY HAND. See README.md // *********************************************************** import ( "net/url" "time" "github.com/huin/goupnp" "github.com/huin/goupnp/soap" ) // Hack to avoid Go complaining if time isn't used. var _ time.Time // Device URNs: const ({{range .DeviceTypes}} {{.Const}} = "{{.URN}}"{{end}} ) // Service URNs: const ({{range .ServiceTypes}} {{.Const}} = "{{.URN}}"{{end}} ) {{range .Services}} {{$srv := .}} {{$srvIdent := printf "%s%s" .Name .Version}} // {{$srvIdent}} is a client for UPnP SOAP service with URN "{{.URN}}". See // goupnp.ServiceClient, which contains RootDevice and Service attributes which // are provided for informational value. type {{$srvIdent}} struct { goupnp.ServiceClient } // New{{$srvIdent}}Clients discovers instances of the service on the network, // and returns clients to any that are found. errors will contain an error for // any devices that replied but which could not be queried, and err will be set // if the discovery process failed outright. // // This is a typical entry calling point into this package. func New{{$srvIdent}}Clients() (clients []*{{$srvIdent}}, errors []error, err error) { var genericClients []goupnp.ServiceClient if genericClients, errors, err = goupnp.NewServiceClients({{$srv.Const}}); err != nil { return } clients = new{{$srvIdent}}ClientsFromGenericClients(genericClients) return } // New{{$srvIdent}}ClientsByURL discovers instances of the service at the given // URL, and returns clients to any that are found. An error is returned if // there was an error probing the service. // // This is a typical entry calling point into this package when reusing an // previously discovered service URL. func New{{$srvIdent}}ClientsByURL(loc *url.URL) ([]*{{$srvIdent}}, error) { genericClients, err := goupnp.NewServiceClientsByURL(loc, {{$srv.Const}}) if err != nil { return nil, err } return new{{$srvIdent}}ClientsFromGenericClients(genericClients), nil } // New{{$srvIdent}}ClientsFromRootDevice discovers instances of the service in // a given root device, and returns clients to any that are found. An error is // returned if there was not at least one instance of the service within the // device. The location parameter is simply assigned to the Location attribute // of the wrapped ServiceClient(s). // // This is a typical entry calling point into this package when reusing an // previously discovered root device. func New{{$srvIdent}}ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*{{$srvIdent}}, error) { genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, {{$srv.Const}}) if err != nil { return nil, err } return new{{$srvIdent}}ClientsFromGenericClients(genericClients), nil } func new{{$srvIdent}}ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*{{$srvIdent}} { clients := make([]*{{$srvIdent}}, len(genericClients)) for i := range genericClients { clients[i] = &{{$srvIdent}}{genericClients[i]} } return clients } {{range .SCPD.Actions}}{{/* loops over *SCPDWithURN values */}} {{$winargs := $srv.WrapArguments .InputArguments}} {{$woutargs := $srv.WrapArguments .OutputArguments}} {{if $winargs.HasDoc}} // // Arguments:{{range $winargs}}{{if .HasDoc}} // // * {{.Name}}: {{.Document}}{{end}}{{end}}{{end}} {{if $woutargs.HasDoc}} // // Return values:{{range $woutargs}}{{if .HasDoc}} // // * {{.Name}}: {{.Document}}{{end}}{{end}}{{end}} func (client *{{$srvIdent}}) {{.Name}}({{range $winargs -}} {{.AsParameter}}, {{end -}} ) ({{range $woutargs -}} {{.AsParameter}}, {{end}} err error) { // Request structure. request := {{if $winargs}}&{{template "argstruct" $winargs}}{{"{}"}}{{else}}{{"interface{}(nil)"}}{{end}} // BEGIN Marshal arguments into request. {{range $winargs}} if request.{{.Name}}, err = {{.Marshal}}; err != nil { return }{{end}} // END Marshal arguments into request. // Response structure. response := {{if $woutargs}}&{{template "argstruct" $woutargs}}{{"{}"}}{{else}}{{"interface{}(nil)"}}{{end}} // Perform the SOAP call. if err = client.SOAPClient.PerformAction({{$srv.URNParts.Const}}, "{{.Name}}", request, response); err != nil { return } // BEGIN Unmarshal arguments from response. {{range $woutargs}} if {{.Name}}, err = {{.Unmarshal "response"}}; err != nil { return }{{end}} // END Unmarshal arguments from response. return } {{end}} {{end}} {{define "argstruct"}}struct {{"{"}} {{range .}}{{.Name}} string {{end}}{{"}"}}{{end}} `))
package watcher import ( "context" "encoding/json" "fmt" "io/ioutil" "net/http" api "nighthawkapi/api/core" "nighthawkapi/api/handlers/config" "github.com/gorilla/mux" elastic "gopkg.in/olivere/elastic.v5" yaml "gopkg.in/yaml.v2" ) func GetWatcherResults(w http.ResponseWriter, r *http.Request) { r.Header.Set("Content-Type", "application/json; charset=UTF-8") var ( method string wr api.WatcherResults _wr []api.WatcherResults query elastic.Query ret string conf *config.ConfigVars err error client *elastic.Client alerts *elastic.SearchResult ) conf, err = config.ReadConfFile() if err != nil { api.LogError(api.DEBUG, err) } if conf.Elastic.Elastic_ssl { method = api.HTTPS } else { method = api.HTTP } client, err = elastic.NewClient(elastic.SetURL(fmt.Sprintf("%s%s:%d", method, conf.Elastic.Elastic_server, conf.Elastic.Elastic_port))) if err != nil { api.LogError(api.DEBUG, err) } query = elastic.NewTermQuery("alert_sent", true) alerts, err = client.Search(). Index("elastalert_status"). Query(query). Size(1000). Do(context.Background()) if err != nil { api.LogError(api.DEBUG, err) ret := api.HttpFailureMessage(err.Error()) fmt.Fprint(w, string(ret)) return } for _, hit := range alerts.Hits.Hits { json.Unmarshal(*hit.Source, &wr) _wr = append(_wr, wr) } ret = api.HttpSuccessMessage("200", &_wr, alerts.TotalHits()) api.LogDebug(api.DEBUG, "[+] GET /watcher/results HTTP 200, returned watcher results") fmt.Fprintln(w, string(ret)) } func GetWatcherResultById(w http.ResponseWriter, r *http.Request) { r.Header.Set("Content-Type", "application/json; charset=UTF-8") var ( method, ret string vars = mux.Vars(r) vars_id = vars["id"] query elastic.Query conf *config.ConfigVars err error client *elastic.Client res *elastic.SearchResult ) conf, err = config.ReadConfFile() if err != nil { api.LogError(api.DEBUG, err) } if conf.Elastic.Elastic_ssl { method = api.HTTPS } else { method = api.HTTP } client, err = elastic.NewClient(elastic.SetURL(fmt.Sprintf("%s%s:%d", method, conf.Elastic.Elastic_server, conf.Elastic.Elastic_port))) if err != nil { api.LogError(api.DEBUG, err) } query = elastic.NewTermQuery("_id", vars_id) res, err = client.Search(). Index(conf.Elastic.Elastic_index). Query(query). Size(1). Do(context.Background()) ret = api.HttpSuccessMessage("200", &res.Hits.Hits[0], res.TotalHits()) api.LogDebug(api.DEBUG, "[+] GET /watcher/results/id HTTP 200, returned watcher result id doc") fmt.Fprintln(w, ret) } func GenerateWatcherRule(w http.ResponseWriter, r *http.Request) { var ( rb api.RB rd api.RuleDefaults ) r.Header.Set("Content-Type", "application/json; charset=UTF-8") body, err := ioutil.ReadAll(r.Body) if err != nil { api.LogError(api.DEBUG, err) } if err := r.Body.Close(); err != nil { api.LogError(api.DEBUG, err) } json.Unmarshal(body, &rb) conf, err := config.ReadConfFile() if err != nil { api.LogError(api.DEBUG, err) } // Setup RuleDefaults m := make(map[interface{}]interface{}) // map is needed to avoid struct names as becoming yaml rd.ESHost = conf.Elastic.Elastic_server rd.ESPort = conf.Elastic.Elastic_port rd.Index = conf.Elastic.Elastic_index rd.Timestampfield = "Record.TlnTime" switch rb.RealertTimelen { case "minutes": m["realert"] = struct { Minutes int }{ rb.RealertDuration, } break case "hours": m["realert"] = struct { Hours int }{ rb.RealertDuration, } break case "days": m["realert"] = struct { Days int }{ rb.RealertDuration, } } // make the rule m["es_host"] = rd.ESHost m["es_port"] = rd.ESPort m["index"] = rd.Index m["timestamp_field"] = rd.Timestampfield m["name"] = rb.Name m["type"] = rb.Type m["compare_key"] = rb.RuleMeta.CompareKey switch rb.Type { case "blacklist": m["blacklist"] = rb.RuleMeta.ListTerms break case "whitelist": m["whitelist"] = rb.RuleMeta.ListTerms break } data, err := yaml.Marshal(&m) if err != nil { fmt.Println(err.Error()) } fmt.Println(string(data)) }
package chars import ( "bytes" "fmt" "testing" "github.com/lioneagle/goutil/src/test" ) func TestUnescape(t *testing.T) { testdata := []struct { escaped string unescaped string }{ {"a%42c", "aBc"}, {"a%3B", "a;"}, {"a%3b%42", "a;B"}, {"ac%3", "ac%3"}, {"ac%P3", "ac%P3"}, {"ac%", "ac%"}, } for i, v := range testdata { v := v t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { t.Parallel() u := PercentUnescape([]byte(v.escaped)) test.EXPECT_EQ(t, string(u), v.unescaped, "") }) } } func TestEscape(t *testing.T) { testdata := []struct { name string isInCharset func(ch byte) bool }{ {"IsDigit", IsDigit}, {"IsAlpha", IsAlpha}, {"IsLower", IsLower}, {"IsUpper", IsUpper}, {"IsAlphanum", IsAlphanum}, {"IsLowerHexAlpha", IsLowerHexAlpha}, {"IsUpperHexAlpha", IsUpperHexAlpha}, {"IsLowerHex", IsLowerHex}, {"IsUpperHex", IsUpperHex}, {"IsHex", IsHex}, {"IsCrlfChar", IsCrlfChar}, {"IsWspChar", IsWspChar}, {"IsLwsChar", IsLwsChar}, {"IsAscii", IsAscii}, {"IsUtf8N1", IsUtf8N1}, {"IsUtf8N2", IsUtf8N2}, {"IsUtf8N3", IsUtf8N3}, {"IsUtf8N4", IsUtf8N4}, {"IsUtf8N5", IsUtf8N5}, {"IsUtf8N6", IsUtf8N6}, {"IsUtf8Cont", IsUtf8Cont}, {"IsUtf8Char", IsUtf8Char}, {"IsUriUnreserved", IsUriUnreserved}, {"IsUriReserved", IsUriReserved}, {"IsUriUric", IsUriUric}, {"IsUriUricNoSlash", IsUriUricNoSlash}, {"IsUriPchar", IsUriPchar}, {"IsUriScheme", IsUriScheme}, {"IsUriRegName", IsUriRegName}, } chars := makeFullCharset() for i, v := range testdata { v := v t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { t.Parallel() u := PercentEscape(chars, v.isInCharset) test.EXPECT_TRUE(t, bytes.Equal(PercentUnescape(u), chars), "") }) } } func makeFullCharset() (ret []byte) { for i := 0; i < 256; i++ { ret = append(ret, byte(i)) } return ret } func BenchmarkEscape(b *testing.B) { b.StopTimer() src := []byte("1234567abc") b.ReportAllocs() b.SetBytes(2) b.StartTimer() for i := 0; i < b.N; i++ { PercentEscape(src, IsDigit) } } func BenchmarkEscapeEx(b *testing.B) { b.StopTimer() src := []byte("1234567abc") b.ReportAllocs() b.SetBytes(2) b.StartTimer() for i := 0; i < b.N; i++ { PercentEscapeEx(src, &Charsets0, MASK_DIGIT) } } func BenchmarkUnescape(b *testing.B) { b.StopTimer() src := []byte("1234567%31%32%33") b.ReportAllocs() b.SetBytes(2) b.StartTimer() for i := 0; i < b.N; i++ { PercentUnescape(src) } }
package jsonv const ( // messages for bad destination types ERROR_BAD_INT_DEST = "Cannot assign integer to variable of type %v, path %v" ERROR_BAD_FLOAT_DEST = "Cannot assign float to variable of type %v, path %v" ERROR_BAD_STRING_DEST = "Cannot assign string to variable of type %v, path %v" ERROR_BAD_DATE_DEST = "Cannot assign date to variable of type %v, path %v" ERROR_BAD_DATE_TIME_DEST = "Cannot assign datetime to variable of type %v, path %v" ERROR_BAD_BYTE_DEST = "Cannot assign []byte to variable of type %v, path %v" ERROR_BAD_BOOL_DEST = "Cannot assign boolean to variable of type %v, path %v" ERROR_BAD_UNMARSHAL_DEST = "Cannot unmashal into variable of type %v, path %v" ERROR_BAD_OBJ_DEST = "Must be a non-nil ptr to a struct, not %v" ERROR_BAD_SLICE_DEST = "Must be a non-nil ptr to a slice, not %v" ERROR_INVALID_STRING = "Expected a string, go %v" ERROR_INVALID_DATE = "Expected a string in the format yyyy-mm-dd." ERROR_INVALID_DATE_TIME = "Expected a string in the format yyyy-mm-ddTHH:MM:SS.000Z." ERROR_INVALID_INT = "Expected an integer, got %v" ERROR_PARSE_INT = "Error parsing integer, %v" ERROR_INVALID_BOOL = "Expected a boolean, got %v" ERROR_PARSE_BOOL = "Error parsing bool, %v" ERROR_PROP_REQUIRED = "Required" ERROR_MIN_LEN_STR = "Must be at least %d characters long" ERROR_MAX_LEN_STR = "Must be no more than %d characters long" ERROR_PATTERN_MATCH = "Must match regex pattern %v" ERROR_MIN_LEN_ARR = "Please provide at least %d items" ERROR_MAX_LEN_ARR = "Please provide no more than %d items" // general number validation errors ERROR_MAX_EX = "Must be less than %v" ERROR_MAX = "Must be less than or equal to %v" ERROR_MIN_EX = "Must be greater than %v" ERROR_MIN = "Must be greater than or equal to %v" ERROR_MULOF = "Must be a multiple of %v" ERROR_NIL_DEFAULT = `Default for "%v" cannot be nil. Use a ptr field with no default instead.` ERROR_WRONG_TYPE_DEFAULT = "Default value must be the same type as field. Got %v, want %v" )
package model import "github.com/jschweizer78/fusion-ng/pkg/service/model/question" // User of the application type User struct { Email string `json:"email" storm:"id"` Customers map[string]*UserCustomer `json:"customers"` } // UserQuestion meta data type UserQuestion struct { Email *question.Textbox `json:"email"` Customers *question.DropDown `json:"customers"` } // NewUserQuestions user metadata func NewUserQuestions() *UserQuestion { eBase := question.NewBase("email", "Email", "text", 0, true) email := question.NewTextBox(eBase, "email") cBase := question.NewBase("customers", "Customers", "dropdown", 1, false) cOptions := make([]*question.SelectOptions, 0, 10) cOptions = append(cOptions, &question.SelectOptions{ Key: "new", Value: "New", }) customers := question.NewDropDown(cBase, cOptions) return &UserQuestion{email, customers} } // UserCustomer used to link an admin to a customer type UserCustomer struct { CustomerID string `json:"customerID"` AuthToken string `json:"authToken"` } // UserCustomerQuestion meta data type UserCustomerQuestion struct { CustomerID *question.Textbox `json:"customerID"` AuthToken *question.Textbox `json:"authToken"` }
package utils /*Contains ...*/ func Contains(source []string, item string) bool { for _, v := range source { if v == item { return true } } return false } /*RemoveFirst ...*/ func RemoveFirst(source []string, item string) (bool, []string) { found, index := FindIndex(source, item) if !found { return false, nil } return true, append(source[:index], source[index+1:]...) } /*FindIndex ...*/ func FindIndex(source []string, item string) (bool, int) { for index, v := range source { if v == item { return true, index } } return false, -1 }
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00600102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.006.001.02 Document"` Message *RedemptionMultipleOrderConfirmationV02 `xml:"setr.006.001.02"` } func (d *Document00600102) AddMessage() *RedemptionMultipleOrderConfirmationV02 { d.Message = new(RedemptionMultipleOrderConfirmationV02) return d.Message } // Scope // The RedemptionMultipleOrderConfirmation message is sent by an exacting party, eg, a transfer agent, to an instructing party, eg, an investment manager or its authorised representative. There may be one or more intermediary parties between the executing party and the instructing party. The intermediary party is, for example, an intermediary or a concentrator. // This message is used to confirm the details of the execution of a RedemptionMultipleOrder message. // Usage // The RedemptionMultipleOrderConfirmation message is sent, after the price has been determined, to confirm the execution of all individual orders. // A RedemptionMultipleOrder may be responded to by more than one RedemptionMultipleOrderConfirmation, as the valuation cycle of the financial instruments in each individual order may be different. // When the executing party sends several confirmations, there is no specific indication in the message that it is an incomplete confirmation. Reconciliation must be based on the references. // A RedemptionMultipleOrder must in all cases be responded to by a RedemptionMultipleOrderConfirmation message/s and in no circumstances by a RedemptionBulkOrderConfirmation message/s. // If the executing party needs to confirm a RedemptionBulkOrder message, then a RedemptionBulkOrderConfirmation message must be used. type RedemptionMultipleOrderConfirmationV02 struct { // Reference assigned to a set of orders or trades in order to link them together. MasterReference *iso20022.AdditionalReference3 `xml:"MstrRef,omitempty"` // Collective reference identifying a set of messages. PoolReference *iso20022.AdditionalReference3 `xml:"PoolRef,omitempty"` // Reference to a linked message that was previously sent. PreviousReference []*iso20022.AdditionalReference3 `xml:"PrvsRef,omitempty"` // Reference to a linked message that was previously received. RelatedReference *iso20022.AdditionalReference3 `xml:"RltdRef"` // General information related to the execution of investment fund orders. MultipleExecutionDetails *iso20022.RedemptionMultipleExecution2 `xml:"MltplExctnDtls"` // Information related to an intermediary. IntermediaryDetails []*iso20022.Intermediary4 `xml:"IntrmyDtls,omitempty"` // Information provided when the message is a copy of a previous message. CopyDetails *iso20022.CopyInformation1 `xml:"CpyDtls,omitempty"` // Additional information that cannot be captured in the structured elements and/or any other specific block. Extension []*iso20022.Extension1 `xml:"Xtnsn,omitempty"` } func (r *RedemptionMultipleOrderConfirmationV02) AddMasterReference() *iso20022.AdditionalReference3 { r.MasterReference = new(iso20022.AdditionalReference3) return r.MasterReference } func (r *RedemptionMultipleOrderConfirmationV02) AddPoolReference() *iso20022.AdditionalReference3 { r.PoolReference = new(iso20022.AdditionalReference3) return r.PoolReference } func (r *RedemptionMultipleOrderConfirmationV02) AddPreviousReference() *iso20022.AdditionalReference3 { newValue := new(iso20022.AdditionalReference3) r.PreviousReference = append(r.PreviousReference, newValue) return newValue } func (r *RedemptionMultipleOrderConfirmationV02) AddRelatedReference() *iso20022.AdditionalReference3 { r.RelatedReference = new(iso20022.AdditionalReference3) return r.RelatedReference } func (r *RedemptionMultipleOrderConfirmationV02) AddMultipleExecutionDetails() *iso20022.RedemptionMultipleExecution2 { r.MultipleExecutionDetails = new(iso20022.RedemptionMultipleExecution2) return r.MultipleExecutionDetails } func (r *RedemptionMultipleOrderConfirmationV02) AddIntermediaryDetails() *iso20022.Intermediary4 { newValue := new(iso20022.Intermediary4) r.IntermediaryDetails = append(r.IntermediaryDetails, newValue) return newValue } func (r *RedemptionMultipleOrderConfirmationV02) AddCopyDetails() *iso20022.CopyInformation1 { r.CopyDetails = new(iso20022.CopyInformation1) return r.CopyDetails } func (r *RedemptionMultipleOrderConfirmationV02) AddExtension() *iso20022.Extension1 { newValue := new(iso20022.Extension1) r.Extension = append(r.Extension, newValue) return newValue }
/* WARNING This piece of code will attempt to break the CXE liveagent go routine server and the meralco main chatbot server. Please use this code with CAUTION. */ package main import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "os" "strconv" "sync" "time" "github.com/cheggaaa/pb/v3" ) type Config struct { AveResponseTime time.Time SuccessTotal int FailTotal int UserID string `json:"userID"` CoreURL string `json:"coreURL"` LoadCapacity int `json:"loadCapacity"` LoadReps int `json:"loadReps"` MsgLoad string `json:"msgLoad"` DFUsername string `json:"dfUsername"` DFPassword string `json:"dfPassword"` } // Send payload to meralco main core func sendPayload(id string, config *Config) { basicAuth := config.DFUsername + ":" + config.DFPassword basicAuth = base64.StdEncoding.EncodeToString([]byte(basicAuth)) URL := config.CoreURL headers := map[string]string{ "Content-Type": "application/json", "Authorizaiton": "Basic " + basicAuth, } payload := map[string]interface{}{ "queryResult": map[string]interface{}{ "intent": map[string]interface{}{ "displayName": "Default Fallback Intent", }, }, "originalDetectIntentRequest": map[string]interface{}{ "source": "facebook", "payload": map[string]interface{}{ "data": map[string]interface{}{ "sender": map[string]interface{}{ "id": config.UserID, }, "recipient": map[string]interface{}{ "id": "2288306637923993", }, "message": map[string]interface{}{ "text": "yo", }, }, "source": "facebook", }, }, } resp, err := post(URL, payload, headers) if err != nil { //log.Println("[ID " + id + "] Result: " + err.Error()) config.FailTotal++ return } defer resp.Body.Close() if resp.StatusCode == 200 { config.SuccessTotal++ //log.Println("[ID " + id + "] Result: Success " + strconv.Itoa(config.SuccessTotal) + "| Fail " + strconv.Itoa(config.FailTotal)) } else { log.Println(resp.StatusCode) } } func post(URL string, payload map[string]interface{}, headers map[string]string) (*http.Response, error) { client := &http.Client{} jsonPayload, _ := json.Marshal(payload) req, _ := http.NewRequest("POST", URL, bytes.NewBuffer(jsonPayload)) if headers != nil { for key, value := range headers { req.Header.Add(key, value) } } resp, err := client.Do(req) if err != nil { return resp, err } return resp, nil } // Synchronous load test func botCoreLoadTest(config *Config, bar *pb.ProgressBar) { var waitGroup sync.WaitGroup waitGroup.Add(config.LoadCapacity) log.Print("Load Capacity: " + strconv.Itoa(config.LoadCapacity)) for i := 0; i < config.LoadCapacity; i++ { go func() { defer waitGroup.Done() for j := 0; j < config.LoadReps; j++ { max := 10 min := 5 requestDelay := rand.Intn(max-min) + min time.Sleep(time.Duration(requestDelay) * time.Second) sendPayload("test", config) bar.Increment() } }() } waitGroup.Wait() } // Load test configuration func loadConfig() *Config { log.Print("Loading configuration..") var config Config jsonFile, err := os.Open("config.json") if err != nil { fmt.Println(err) } defer jsonFile.Close() byteValue, err := ioutil.ReadAll(jsonFile) if err != nil { fmt.Println(err) } json.Unmarshal([]byte(byteValue), &config) return &config } func main() { config := loadConfig() bar := pb.StartNew(config.LoadCapacity * config.LoadReps) log.Print("Starting load testing with host url: " + config.CoreURL) botCoreLoadTest(config, bar) bar.Finish() log.Println("Result: Success " + strconv.Itoa(config.SuccessTotal) + "| Fail " + strconv.Itoa(config.FailTotal)) }
package manager import ( "github.com/rancher/longhorn-manager/types" "time" ) type event struct{} func TimeEvent() types.Event { return &event{} } type Ticker interface { Start() Ticker Stop() Ticker NewTick() types.Event } type tickerImpl struct { ch chan types.Event interval time.Duration timer *time.Timer } func NewTicker(interval time.Duration, ch chan types.Event) Ticker { return &tickerImpl{interval: interval, ch: ch} } func (t *tickerImpl) Start() Ticker { if t.timer == nil { t.timer = time.NewTimer(t.interval) go t.tick() } else { t.timer.Reset(t.interval) } return t } func (t *tickerImpl) tick() { <-t.timer.C if Send(t.ch, t.NewTick()) { t.timer.Reset(t.interval) go t.tick() } } func (t *tickerImpl) NewTick() types.Event { return TimeEvent() } func (t *tickerImpl) Stop() Ticker { if t.timer != nil { t.timer.Stop() } return t } func Send(c chan<- types.Event, e types.Event) bool { if c == nil { return false } defer func() { recover() // otherwise, c <- e will panic if c is closed }() c <- e return true }