text
stringlengths 11
4.05M
|
|---|
package main
import (
"errors"
// "fmt"
termbox "github.com/nsf/termbox-go"
// "gopkg.in/mattn/go-runewidth.v0"
)
type av struct {
tag string /* Tag tools*/
cols []*col
// w, h int
}
type col struct {
tag string
wins []*win
x, w int
}
type win struct {
tag string
// body string
rows []*row
y, h int
}
type row struct {
body string
}
/*** win functions ***/
func (w *win) resize() {
w.h = w.h / 2
}
func (w *win) makeRow() {
w.rows = append(w.rows, &row{string("")})
}
/*** col functions ***/
func (c *col) resize() {
c.w = c.w / 2
}
func (c *col) makeWin() error {
winLen := len(c.wins)
_, h := termbox.Size()
var emptyRow []*row
if winLen == 0 {
debug(1, 55, "Here")
w := &win{ wintool, emptyRow, 2, h}
c.wins = append(c.wins, w)
} else {
lastWin := c.wins[winLen - 1]
if lastWin.y == h - 1 {
errors.New("Now place for new windows")
}
lastWin.resize()
w := &win{ wintool, emptyRow, lastWin.y + lastWin.h, lastWin.h }
c.wins = append(c.wins, w)
}
return nil
}
/*** av functions ***/
func (e *av) init() {
e.tag = maintool
e.cols = []*col{}
// e.w, e.h = termbox.Size()
}
/*
* USER will deal with this function
*/
func (e *av) makeCol() error {
colLen := len(e.cols)
w, _ := termbox.Size()
// debug(3,100, fmt.Sprintf("w = %d", w))
if colLen == 0 {
c := &col{ coltool, []*win{}, 0, w }
e.cols = append(e.cols, c)
} else {
lastCol := e.cols[colLen - 1]
// chech if there is a place for new colume
// at least one empty colume should be there
if lastCol.x == w - 1 {
errors.New("Now Place for new colume")
}
lastCol.resize()
c := &col{ coltool, []*win{}, lastCol.x + lastCol.w, lastCol.w }
// TODO: lastCo.w should be checked to bee true in previous line
e.cols = append(e.cols, c)
// FIXME Debugging print extra '2' digit in c.w or its actully **buggy**
// debug(2,100, fmt.Sprintf("c.x %d | c.w %d", c.x, c.w))
// debug(1,100, fmt.Sprintf("last.x = %d, last.w = %d", lastCol.x, lastCol.w))
// termbox.Flush()
}
return nil
}
/*** Main function and loop ***/
func main() {
err := termbox.Init()
if err != nil {
panic(err)
}
defer termbox.Close()
av := av{}
av.init()
if e := av.makeCol(); e != nil {
panic("No space for basic colume")
}
av.cols[0].makeWin()
av.cols[0].wins[0].makeRow()
av.cols[0].wins[0].rows[0].body = "Hello World, مرحبا, this is sooooooooooo long"
av.cols[0].wins[0].makeRow()
av.cols[0].wins[0].rows[1].body = "\tTHis is the second line of bla bla bla" //TODO: enalbe formatting
av.draw()
mainloop:
for {
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
switch ev.Key {
case termbox.KeyEsc:
break mainloop
case termbox.KeyCtrlC:
av.makeCol()
av.draw()
case termbox.KeyCtrlW:
av.cols[0].makeWin()
av.draw()
case termbox.KeyCtrlE:
av.cols[1].makeWin()
av.draw()
}
case termbox.EventResize:
// av.resizeAll(); TODO: implementation
av.draw()
}
}
}
|
package main
import (
"fmt"
"net"
"flag"
"strings"
"strconv"
"os"
"bufio"
"bytes"
"encoding/binary"
"github.com/golang/protobuf/proto"
identity "./proto_files"
)
func main(){
flag.Parse()
if flag.NArg() != 1{
fmt.Fprintln(os.Stderr, "missing subcommand 'mode': individual or enterprise")
os.Exit(1)
}
if flag.Arg(0) == "individual" || flag.Arg(0) == "enterprise"{
startClient(flag.Arg(0))
}else{
fmt.Fprintln(os.Stderr, "wrong subcommand" )
os.Exit(1)
}
}
func startClient(mode string){
conn, err := net.Dial("tcp", ":2000")
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't connect to server: %v\n", err)
os.Exit(1)
}
fmt.Println("Connected to the server")
rd := bufio.NewReader(os.Stdin)
buf := new(bytes.Buffer)
len_arr := make([]byte, 8)
if mode == "individual"{
for {
buf.Reset()
person := &identity.Individual{}
fmt.Print("Enter person ID number: ")
if _, err := fmt.Fscanf(rd, "%d\n", &person.Id); err != nil {
fmt.Fprintf(os.Stderr, "couldn't parse id: %v\n", err)
}
fmt.Print("Enter name: ")
name, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse name: %v\n", err)
}
person.Name = strings.TrimSpace(name)
fmt.Print("Enter ph number: ")
ph, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse ph number: %v\n", err)
}
person.Ph, _ = strconv.ParseInt(strings.TrimSpace(ph), 10, 64)
fmt.Print("Enter house number for address info (or leave blank): ")
house_no, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse house number: %v\n", err)
}
if strings.TrimSpace(house_no) != ""{
add := &identity.Individual_Address{}
add.Housenum, _ = strconv.ParseInt(strings.TrimSpace(house_no), 10, 64)
fmt.Print("Enter street name for address info: ")
street, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse street name: %v\n", err)
}
add.Street = strings.TrimSpace(street)
fmt.Print("Enter city for address info: ")
city, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse city: %v\n", err)
}
add.City = strings.TrimSpace(city)
person.Add = add
}
msg, err := proto.Marshal(person)
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't marshal person struct: %v\n", err)
}
binary.PutVarint(len_arr, int64(len(msg)+1)) // buffer type from protobuf/proto package could be used for encoding int and marhsaling protobufs msgs
_, err = conn.Write(len_arr)
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't write length to the connection: %v\nclosing connection..\n", err)
conn.Close()
os.Exit(1)
}
binary.Write(buf, binary.LittleEndian, int8(1))
binary.Write(buf, binary.LittleEndian, msg)
_, err = conn.Write(buf.Bytes())
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't write msg to the connection: %v\nclosing connection..\n", err)
conn.Close()
os.Exit(1)
}
fmt.Print("like to add another individual[Y/N]: ")
repeat, _ := rd.ReadString('\n')
if strings.ToLower(strings.TrimSpace(repeat)) == "n"{
break
}
}
}else{
for {
buf.Reset()
company := &identity.Enterprise{}
ceo := &identity.Individual{}
fmt.Print("Enter company name: ")
if _, err := fmt.Fscanf(rd, "%s\n", &company.Name); err != nil {
fmt.Fprintf(os.Stderr, "couldn't parse company name: %v\n", err)
}
fmt.Print("Enter ceo name: ")
name, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse ceo name: %v\n", err)
}
ceo.Name = strings.TrimSpace(name)
fmt.Print("Enter ceo id: ")
id, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse ceo id: %v\n", err)
}
id_64, _ := strconv.ParseInt(strings.TrimSpace(id), 10, 64)
ceo.Id = int32(id_64)
company.Ceo = ceo
fmt.Print("Enter Company Address/House number (or leave blank): ")
house_no, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse house number: %v\n", err)
}
if strings.TrimSpace(house_no) != ""{
add := &identity.Individual_Address{}
add.Housenum, _ = strconv.ParseInt(strings.TrimSpace(house_no), 10, 64)
fmt.Print("Enter street name for address info: ")
street, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse street name: %v\n", err)
}
add.Street = strings.TrimSpace(street)
fmt.Print("Enter city for address info: ")
city, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse city: %v\n", err)
}
add.City = strings.TrimSpace(city)
company.Add = add
}
fmt.Print("Enter Company's work domain (tech/security/services): ")
domain, err := rd.ReadString('\n')
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't parse domain: %v\n", err)
}
switch strings.TrimSpace(domain){
case "tech":
company.D = identity.Enterprise_TECH
case "security":
company.D = identity.Enterprise_SECURITY
case "services":
company.D = identity.Enterprise_SERVICES
default:
fmt.Println("Unknown company domain, choosing TECH as default country domain")
}
msg, err := proto.Marshal(company)
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't marshal company struct: %v\n", err)
}
binary.PutVarint(len_arr, int64(len(msg)+1))
_, err = conn.Write(len_arr)
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't write length to the connection: %v\nclosing connection..\n", err)
conn.Close()
os.Exit(1)
}
binary.Write(buf, binary.LittleEndian, int8(2))
binary.Write(buf, binary.LittleEndian, msg)
_, err = conn.Write(buf.Bytes())
if err != nil{
fmt.Fprintf(os.Stderr, "couldn't write msg to the connection: %v\nclosing connection..\n", err)
conn.Close()
os.Exit(1)
}
fmt.Print("like to add another company[Y/N]: ")
repeat, _ := rd.ReadString('\n')
if strings.ToLower(strings.TrimSpace(repeat)) == "n"{
break
}
}
}
}
|
// Copyright © 2020. All rights reserved.
// Author: Ilya Stroy.
// Contacts: qioalice@gmail.com, https://github.com/qioalice
// License: https://opensource.org/licenses/MIT
package privet
import (
"sync/atomic"
"unsafe"
)
//goland:noinspection GoSnakeCaseUsage
const (
/*
TODO: comment
*/
_LLS_STANDBY uint32 = 0
_LLS_SOURCE_PENDING uint32 = 1
_LLS_LOAD_PENDING uint32 = 2
_LLS_READY uint32 = 10
)
var (
/*
*/
defaultClient Client
)
/*
TODO: comment
*/
func (c *Client) isValid() bool {
return c != nil
}
/*
TODO: comment
*/
func (c *Client) changeState(from, to uint32) bool {
return atomic.CompareAndSwapUint32(&c.state, from, to)
}
/*
TODO: comment
*/
func (c *Client) changeStateForce(to uint32) {
atomic.StoreUint32(&c.state, to)
}
/*
TODO: comment
*/
func (c *Client) getState() uint32 {
return atomic.LoadUint32(&c.state)
}
/*
TODO: comment
*/
func strState(v uint32) string {
switch v {
case _LLS_STANDBY:
return "<standby mode>"
case _LLS_SOURCE_PENDING:
return "<analyzing locale sources>"
case _LLS_LOAD_PENDING:
return "<loading locales>"
case _LLS_READY:
return "<locales loaded, ready to use>"
default:
return "<unknown>"
}
}
/*
getDefaultLocale returns a Locale object that was marked as default locale.
If either no one Locale object was marked as default
or no one locale was loaded yet, nil is returned.
*/
func (c *Client) getDefaultLocale() *Locale {
if c.getState() != _LLS_READY {
return nil
}
return (*Locale)(atomic.LoadPointer(&c.defaultLocale))
}
/*
setDefaultLocale marks loc as a default locale saving it to the defaultLocale
atomically.
*/
func (c *Client) setDefaultLocale(loc *Locale) {
atomic.StorePointer(&c.defaultLocale, unsafe.Pointer(loc))
}
/*
getLocale returns a Locale object for the requested locale's name.
E.g: It returns English locale's entry point if you passed "en_US" and you did load
locale with that name.
If either Locale with the requested name is not exist,
or no one locale was loaded yet nil is returned.
*/
func (c *Client) getLocale(name string) *Locale {
if c.getState() != _LLS_READY {
return nil
}
return c.storage[name]
}
/*
makeLocale is Locale constructor and initializer.
The caller MUST to add it to either Client.storage or Client.storageTmp
depends on requirements.
*/
func (c *Client) makeLocale(name string) *Locale {
loc := &Locale{
owner: c,
name: name,
}
loc.root = loc.makeSubNode()
return loc
}
|
package benchmark
// 基准测试源文件名称也必须以_test结尾
import (
"fmt"
"strconv"
"testing"
)
// 基准测试函数名必须以Benchmark开头,函数没有返回值
/**
int转字符串操作的基准测试,测试了三个函数,具体见一下三个基准测试方法
输出:
goos: windows
goarch: amd64
BenchmarkSprintf-4 5000000 367 ns/op
BenchmarkFormat-4 100000000 18.1 ns/op
BenchmarkItoa-4 100000000 18.9 ns/op
上面的输出 ^ 4表示运行时对应的GOMAXPROCS的值,后面的数字表示执行的循环次数,18.9 ns/op 表示每次循环花费的时间
想让测试运行的时间更长,可以通过-benchtime指定,比如3秒 go test -bench=. -benchtime=3s
1 ns = 10^-9 s
-test.benchmem 参数可以提供每次操作分配内存的次数:
BenchmarkSprintf-4 3000000 357 ns/op 16 B/op 2 allocs/op
BenchmarkFormat-4 100000000 16.7 ns/op 0 B/op 0 allocs/op
BenchmarkItoa-4 100000000 19.7 ns/op 0 B/op 0 allocs/op
增加的两列输出表示:每次操作会分配多少内存,每次操作会进行几次内存分配。
*/
func BenchmarkSprintf(b *testing.B) {
number := 10
b.ResetTimer()
for i := 0; i < b.N; i++ {
fmt.Sprintf("%d", number)
}
}
func BenchmarkFormat(b *testing.B) {
number := int64(10)
b.ResetTimer()
for i := 0; i < b.N; i++ {
strconv.FormatInt(number, 10)
}
}
func BenchmarkItoa(b *testing.B) {
number := 10
b.ResetTimer()
for i := 0; i < b.N; i ++ {
strconv.Itoa(number)
}
}
|
package main
import (
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/sanguohot/medichain/chain"
"github.com/sanguohot/medichain/etc"
"log"
)
func main() {
name := etc.ContractAuth
if err, hash := chain.SetAddressToCns(name, common.HexToAddress("0x6313917545787e96c22520da87ec0a4bbdc442ad")); err != nil {
log.Fatal(err)
}else {
fmt.Printf("tx sent: %s\n", hash.Hex()) // tx sent: 0x8d490e535678e9a24360e955d75b27ad307bdfb97a1dca51d0f3035dcee3e870
}
if err, address := chain.GetAddressFromCns(name); err != nil {
log.Fatal(err)
}else {
fmt.Printf("%s ===> %s\n", name, address.Hex())
}
}
|
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"gopkg.in/yaml.v3"
"git.scc.kit.edu/sdm/lsdf-checksum/scaleadpt"
"git.scc.kit.edu/sdm/lsdf-checksum/scaleadpt/filelist"
"git.scc.kit.edu/sdm/lsdf-checksum/scaleadpt/options"
)
type Spec struct {
Filesystems map[string]SpecFilesystem `yaml:"filesystems"`
}
type SpecFilesystem struct {
Name string `yaml:"name"`
MountRoot string `yaml:"mount_root"`
Version string `yaml:"version"`
SnapshotDirsInfo SpecSnapshotDirsInfo `yaml:"snapshot_dirs_info"`
CreateGetDeleteSnapshot string `yaml:"create_get_delete_snapshot"`
ListPolicy SpecListPolicy `yaml:"list_policy"`
}
type SpecSnapshotDirsInfo struct {
Global string `yaml:"global"`
GlobalsInFileset bool `yaml:"globals_in_fileset"`
Fileset string `yaml:"fileset"`
AllDirectories bool `yaml:"all_directories"`
}
type SpecListPolicy struct {
Subpath string `yaml:"subpath"`
Files []SpecListPolicyFile `yaml:"files"`
FilesComplete bool `yaml:"files_complete"`
ExcludePathPatterns []string `yaml:"exclude_path_patterns"`
}
type SpecListPolicyFile struct {
Path string `yaml:"path"`
Size int64 `yaml:"size"`
}
type MismatchError struct {
Name string
Observed interface{}
Specced interface{}
}
func (m *MismatchError) Error() string {
return fmt.Sprintf(
"Mismatch for \"%s\" between observed value \"%v\" and specced value \"%v\"",
m.Name, m.Observed, m.Specced,
)
}
func ShouldEqualString(obsVal, specVal string, name string) error {
if obsVal != specVal {
return &MismatchError{
Observed: obsVal,
Specced: specVal,
Name: name,
}
}
return nil
}
func ShouldEqualInt(obsVal, specVal int, name string) error {
if obsVal != specVal {
return &MismatchError{
Observed: obsVal,
Specced: specVal,
Name: name,
}
}
return nil
}
func ShouldEqualBool(obsVal, specVal bool, name string) error {
if obsVal != specVal {
return &MismatchError{
Observed: obsVal,
Specced: specVal,
Name: name,
}
}
return nil
}
func ShouldApproxEqualTime(obsVal, specVal time.Time, intv time.Duration, name string) error {
windowStart := specVal.Add(-intv)
windowEnd := specVal.Add(intv)
if obsVal.Before(windowStart) || obsVal.After(windowEnd) {
return &MismatchError{
Observed: obsVal,
Specced: specVal,
Name: name,
}
}
return nil
}
type Reporter struct {
modules map[string]*reporterModule
}
type reporterModule struct {
skipped bool
runtime []error
mismatch []error
}
func (r *Reporter) ensureAndGetModule(module string) *reporterModule {
if r.modules == nil {
r.modules = make(map[string]*reporterModule)
}
if m, ok := r.modules[module]; ok {
return m
}
m := &reporterModule{}
r.modules[module] = m
return m
}
func (r *Reporter) PrintSummary() {
fmt.Println("Summary")
names := make([]string, 0, len(r.modules))
for name, m := range r.modules {
if len(m.runtime)+len(m.mismatch) == 0 && !m.skipped {
names = append(names, name)
}
}
if len(names) > 0 {
fmt.Printf(" SUCCEEDED %d modules: %s\n", len(names), strings.Join(names, ", "))
}
names = names[:0]
for name, m := range r.modules {
if len(m.runtime)+len(m.mismatch) == 0 && m.skipped {
names = append(names, name)
}
}
if len(names) > 0 {
fmt.Printf(" SKIPPED %d modules: %s\n", len(names), strings.Join(names, ", "))
}
names = names[:0]
for name, m := range r.modules {
if len(m.runtime)+len(m.mismatch) > 0 {
names = append(names, name)
}
}
if len(names) > 0 {
fmt.Printf(" FAILED %d modules: %s\n", len(names), strings.Join(names, ", "))
}
}
func (r *Reporter) IsSuccessful() bool {
for _, m := range r.modules {
if len(m.runtime)+len(m.mismatch) > 0 {
return false
}
}
return true
}
func (r *Reporter) StartModule(module string) ReporterModuleCtx {
fmt.Printf("module %s starts\n", module)
m := r.ensureAndGetModule(module)
return ReporterModuleCtx{
name: module,
data: m,
}
}
type ReporterModuleCtx struct {
name string
data *reporterModule
}
func (r ReporterModuleCtx) AddRuntimeErr(errs ...error) {
for _, err := range errs {
if err == nil {
continue
}
fmt.Printf("runtime error in module %s: %v\n", r.name, err)
r.data.runtime = append(r.data.runtime, err)
}
}
func (r ReporterModuleCtx) AddMismatchErr(errs ...error) {
for _, err := range errs {
if err == nil {
continue
}
fmt.Printf("mismatch error in module %s: %v\n", r.name, err)
r.data.mismatch = append(r.data.mismatch, err)
}
}
func (r ReporterModuleCtx) ReportSkipped() {
fmt.Printf("module %s is skipped and does not perform its checks (skipped) \n", r.name)
r.data.skipped = true
}
func (r ReporterModuleCtx) Finish() {
if len(r.data.runtime)+len(r.data.mismatch) > 0 {
fmt.Printf("module %s finished with errors\n", r.name)
} else if r.data.skipped {
fmt.Printf("module %s finished (skipped)\n", r.name)
} else {
fmt.Printf("module %s finished\n", r.name)
}
}
type Checker struct {
fs *scaleadpt.FileSystem
spec *SpecFilesystem
reporter *Reporter
}
func CheckFS(spec *SpecFilesystem) bool {
c := Checker{
fs: scaleadpt.OpenFileSystem(spec.Name),
spec: spec,
reporter: &Reporter{},
}
c.checkMountRoot()
c.checkVersion()
c.checkSnapshotDirsInfo()
c.checkCreateGetDeleteSnapshot()
c.checkListPolicy()
c.reporter.PrintSummary()
return c.reporter.IsSuccessful()
}
func (c *Checker) checkMountRoot() {
f := c.reporter.StartModule("mount_root")
defer f.Finish()
if c.spec.MountRoot == "" {
f.ReportSkipped()
return
}
mountRoot, err := c.fs.GetMountRoot()
if err != nil {
f.AddRuntimeErr(err)
return
}
f.AddMismatchErr(
ShouldEqualString(mountRoot, c.spec.MountRoot, "mount_root"),
)
}
func (c *Checker) checkVersion() {
f := c.reporter.StartModule("version")
defer f.Finish()
if c.spec.Version == "" {
f.ReportSkipped()
return
}
version, err := c.fs.GetVersion()
if err != nil {
f.AddRuntimeErr(err)
return
}
f.AddMismatchErr(
ShouldEqualString(version, c.spec.Version, "version"),
)
}
func (c *Checker) checkSnapshotDirsInfo() {
f := c.reporter.StartModule("snapshot_dirs_info")
defer f.Finish()
if c.spec.SnapshotDirsInfo.Global == "" || c.spec.SnapshotDirsInfo.Fileset == "" {
f.ReportSkipped()
return
}
info, err := c.fs.GetSnapshotDirsInfo()
if err != nil {
f.AddRuntimeErr(err)
return
}
f.AddMismatchErr(
ShouldEqualString(info.Global, c.spec.SnapshotDirsInfo.Global, "global"),
ShouldEqualBool(info.GlobalsInFileset, c.spec.SnapshotDirsInfo.GlobalsInFileset, "globals_in_fileset"),
ShouldEqualString(info.Fileset, c.spec.SnapshotDirsInfo.Fileset, "fileset"),
ShouldEqualBool(info.AllDirectories, c.spec.SnapshotDirsInfo.AllDirectories, "all_directories"),
)
}
func (c *Checker) checkCreateGetDeleteSnapshot() {
f := c.reporter.StartModule("create_get_delete_snapshot")
defer f.Finish()
if c.spec.CreateGetDeleteSnapshot == "" {
f.ReportSkipped()
return
}
start := time.Now()
sCreate, err := c.fs.CreateSnapshot(c.spec.CreateGetDeleteSnapshot)
if err != nil {
f.AddRuntimeErr(err)
return
}
end := time.Now()
dur := end.Sub(start)
mid := start.Add(dur / 2)
intv := dur/2 + 10*time.Second
f.AddMismatchErr(
ShouldEqualString(sCreate.Name, c.spec.CreateGetDeleteSnapshot, "snapshot name"),
ShouldEqualString(sCreate.Status, "Valid", "snapshot valid (dynamic)"),
ShouldApproxEqualTime(sCreate.CreatedAt, mid, intv, "snapshot created_at (dynamic)"),
)
sGet, err := c.fs.GetSnapshot(sCreate.Name)
if err != nil {
f.AddRuntimeErr(err)
_ = c.fs.DeleteSnapshot(sCreate.Name)
return
}
f.AddMismatchErr(
ShouldEqualInt(sGet.ID, sCreate.ID, "snapshot ID (dynamic)"),
ShouldEqualString(sGet.Name, sCreate.Name, "snapshot name"),
ShouldEqualString(sGet.Status, "Valid", "snapshot valid (dynamic)"),
ShouldApproxEqualTime(sGet.CreatedAt, sCreate.CreatedAt, 10*time.Second, "snapshot created_at (dynamic)"),
ShouldEqualString(sGet.Fileset, sCreate.Fileset, "snapshot fileset (dynamic)"),
)
err = c.fs.DeleteSnapshot(sCreate.Name)
if err != nil {
f.AddRuntimeErr(err)
return
}
_, err = c.fs.GetSnapshot(sCreate.Name)
if err == nil {
f.AddRuntimeErr(fmt.Errorf("Snapshot \"%s\" still exists after deleting", sCreate.Name))
return
} else if err == scaleadpt.ErrSnapshotDoesNotExist {
} else {
f.AddRuntimeErr(err)
return
}
}
func (c *Checker) checkListPolicy() {
f := c.reporter.StartModule("list_policy")
defer f.Finish()
if c.spec.ListPolicy.Subpath == "" {
f.ReportSkipped()
return
}
mountRoot, err := c.fs.GetMountRoot()
if err != nil {
f.AddRuntimeErr(err)
return
}
basePath, err := filepath.Abs(filepath.Join(mountRoot, c.spec.ListPolicy.Subpath))
if err != nil {
f.AddRuntimeErr(err)
return
}
specFiles := make(map[string]*SpecListPolicyFile)
for i := range c.spec.ListPolicy.Files {
file := &c.spec.ListPolicy.Files[i]
specFiles[file.Path] = file
}
options := []options.FilelistPolicyOptioner{
filelist.Opt.PolicyOpts(scaleadpt.PolicyOpt.Subpath(c.spec.ListPolicy.Subpath)),
}
if len(c.spec.ListPolicy.ExcludePathPatterns) > 0 {
options = append(options,
filelist.Opt.ExcludePathPatterns(c.spec.ListPolicy.ExcludePathPatterns),
)
}
parser, err := filelist.ApplyPolicy(c.fs, options...)
if err != nil {
f.AddRuntimeErr(err)
return
}
defer parser.Close()
for {
var fileData filelist.FileData
err := parser.ParseLine(&fileData)
if err == io.EOF {
break
} else if err != nil {
f.AddRuntimeErr(err)
return
}
relPath, err := filepath.Rel(basePath, fileData.Path)
if err != nil {
f.AddRuntimeErr(err)
return
}
if specFile, ok := specFiles[relPath]; ok {
if specFile == nil {
f.AddRuntimeErr(
fmt.Errorf("Encountered file %s a second time in file list", relPath),
)
continue
}
f.AddMismatchErr(
ShouldEqualInt(int(fileData.FileSize), int(specFile.Size), "file size"),
)
specFiles[relPath] = nil
} else if c.spec.ListPolicy.FilesComplete {
f.AddMismatchErr(
fmt.Errorf("Encountered file %s in file list which is not in spec", relPath),
)
}
}
for _, specFile := range specFiles {
if specFile != nil {
f.AddMismatchErr(
fmt.Errorf("File %s from spec not encountered in file list", specFile.Path),
)
}
}
}
func CheckAll(spec *Spec) bool {
successful := true
for name, fsSpec := range spec.Filesystems {
if fsSpec.Name == "" {
fsSpec.Name = name
}
if !CheckFS(&fsSpec) {
successful = false
}
}
return successful
}
func readSpec(path string) (*Spec, error) {
specFile, err := os.Open(path)
if err != nil {
panic(err)
}
defer specFile.Close()
spec := &Spec{}
dec := yaml.NewDecoder(specFile)
err = dec.Decode(spec)
if err != nil {
return nil, err
}
return spec, nil
}
func main() {
spec, err := readSpec(os.Args[1])
if err != nil {
panic(err)
}
if !CheckAll(spec) {
os.Exit(1)
}
}
|
package fcm
type response struct {
StatusCode int
Err string `json:"error,omitempty"`
Success int `json:"success"`
MultiCastId int64 `json:"multicast_id"`
CanonicalIds int `json:"canonical_ids"`
Failure int `json:"failure"`
Results []result `json:"results,omitempty"`
MsgId int64 `json:"message_id,omitempty"`
RetryAfter string `json:"retry_after"`
copyRegistrationIds []string
}
type result struct {
MessageID string `json:"message_id"`
RegistrationID string `json:"registration_id"`
Error string `json:"error"`
}
// GetInvalidTokens return list with tokens wrongs
func (r *response) GetInvalidTokens() map[string]string {
tr := make(map[string]string)
for index, val := range r.Results {
if val.Error != "" {
tr[r.copyRegistrationIds[index]] = val.Error
}
}
return tr
}
|
package client
import (
"context"
"encoding/json"
"os"
"os/signal"
"syscall"
"time"
"github.com/asppj/cnbs/net-bridge/auth"
"github.com/asppj/cnbs/net-bridge/options"
"github.com/asppj/cnbs/log"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/net/gtcp"
)
// Client 客户端
type Client struct {
running chan os.Signal
host string
remoteHTTPConn *gtcp.Conn
remoteTCPConn *gtcp.Conn
remoteUDPConn *gtcp.Conn
localHTTPPort int
localTCPPort int
localUDPPort int
ctx context.Context
cancel context.CancelFunc
Name string
heartTicker *time.Ticker // 心跳
}
// NewClient 客户端
// host ip:port
func NewClient() *Client {
ctx, cancel := context.WithCancel(context.Background())
// 读取配置
g.Cfg().SetFileName("config.client.toml")
localHTTPPort := g.Cfg().GetInt("client.httpPort")
localTCPConn := g.Cfg().GetInt("client.tcpPort")
localUDPConn := g.Cfg().GetInt("client.udpPort")
ip := g.Cfg().GetString("ip")
port := g.Cfg().GetString("port")
serviceName := g.Cfg().GetString("serviceName")
return &Client{
Name: serviceName,
running: make(chan os.Signal),
host: ip + ":" + port,
localHTTPPort: localHTTPPort,
localTCPPort: localTCPConn,
localUDPPort: localUDPConn,
ctx: ctx,
cancel: cancel,
heartTicker: options.NewTickerHeart(),
}
}
// Run 开始
func (c *Client) Run() error {
conn, err := gtcp.NewConn(c.host, options.DeadLine)
if err != nil {
return err
}
c.remoteHTTPConn = conn
// todo 临时写在这
if err = login(c.ctx, conn); err != nil {
log.Error("login失败:", err)
return err
}
monitorHTTPTunnel(c.ctx, conn)
c.Wait()
return nil
}
// Stop 停止
func (c *Client) Stop() {
c.cancel()
if c.remoteHTTPConn != nil {
if err := c.remoteHTTPConn.Close(); err != nil {
log.ErrorF("关闭隧道端口:%d失败", c.localHTTPPort)
} else {
log.InfoF("关闭隧道端口:%d成功", c.localHTTPPort)
}
}
if c.remoteTCPConn != nil {
if err := c.remoteTCPConn.Close(); err != nil {
log.ErrorF("关闭代理端口%d失败", c.localTCPPort)
} else {
log.InfoF("关闭代理端口%d成功", c.localTCPPort)
}
}
if c.remoteUDPConn != nil {
if err := c.remoteUDPConn.Close(); err != nil {
log.ErrorF("关闭代理端口%d失败", c.localUDPPort)
} else {
log.InfoF("关闭代理端口%d成功", c.localUDPPort)
}
}
// 关闭心跳
c.heartTicker.Stop()
}
// Wait 阻塞等待关闭
func (c *Client) Wait() {
log.Info("服务运行中...")
signal.Notify(c.running, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
pTick := time.NewTicker(120 * time.Second)
defer pTick.Stop()
loop:
for {
select {
case r := <-c.running:
log.InfoF("正在服务关闭...:%+v。", r)
break loop
case <-pTick.C:
c.PrintInfo()
}
}
c.Stop()
}
// PrintInfo 打印信息
func (c *Client) PrintInfo() {
log.InfoF("Server Host:%s\n\t httpPort:%d\n\ttcpPort:%d\n\t udpPort:%d",
c.host, c.localHTTPPort, c.localTCPPort, c.localUDPPort)
}
func login(ctx context.Context, conn *gtcp.Conn) error {
buf, err := json.Marshal(auth.NewIdentity())
if err != nil {
return err
}
resp, err := conn.SendRecvPkg(buf)
if err != nil {
log.Error(err)
return err
}
log.Info(string(resp))
return nil
}
|
package parser_test
import (
"fmt"
"syscall"
"testing"
"github.com/m-lab/etl/parser"
)
func TestParseIPFamily(t *testing.T) {
if parser.ParseIPFamily("1.2.3.4") != syscall.AF_INET {
t.Fatalf("IPv4 address not parsed correctly.")
}
if parser.ParseIPFamily("2001:db8:0:1:1:1:1:1") != syscall.AF_INET6 {
t.Fatalf("IPv6 address not parsed correctly.")
}
}
func TestValidateIP(t *testing.T) {
if parser.ValidateIP("1.2.3.4") != nil {
fmt.Println(parser.ValidateIP("1.2.3.4"))
t.Fatalf("Valid IPv4 was identified as invalid.")
}
if parser.ValidateIP("2620:0:1000:2304:8053:fe91:6e2e:b4f1") != nil {
t.Fatalf("Valid IPv6 was identified as invalid.")
}
if parser.ValidateIP("::") == nil || parser.ValidateIP("0.0.0.0") == nil ||
parser.ValidateIP("abc.0.0.0") == nil || parser.ValidateIP("1.0.0.256") == nil {
t.Fatalf("Invalid IP was identified as valid.")
}
if parser.ValidateIP("172.16.0.1") == nil {
t.Fatalf("Private IP was not identified as invalid IP.")
}
if parser.ValidateIP("127.0.0.1") == nil || parser.ValidateIP("::ffff:127.0.0.1") == nil {
t.Fatalf("Nonroutable IP was not identified as invalid IP.")
}
}
// To run benchmark...
// go test -bench=. ./parser/...
func BenchmarkValidateIPv4(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = parser.ValidateIP("1.2.3.4")
}
}
|
/*
Package tracing provides tracing integration to the project
OpenTracing implements a general purpose interface that microservices can
program against, and which adapts to all major distributed tracing systems.
*/
package tracing
|
package effects
import "github.com/faiface/beep"
// Doppler simulates a "sound at a distance". If the sound starts at a far distance,
// it'll take some time to reach the ears of the listener.
//
// The distance of the sound can change dynamically. Doppler adjusts the density of
// the sound (affecting its speed) to remain consistent with the distance. This is called
// the Doppler effect.
//
// The arguments are:
//
// quality: the quality of the underlying resampler (1 or 2 is usually okay)
// samplesPerMeter: sample rate / speed of sound
// s: the source streamer
// distance: a function to calculate the current distance; takes number of
// samples Doppler wants to stream at the moment
//
// This function is experimental and may change any time!
func Doppler(quality int, samplesPerMeter float64, s beep.Streamer, distance func(delta int) float64) beep.Streamer {
return &doppler{
r: beep.ResampleRatio(quality, 1, s),
distance: distance,
space: make([][2]float64, int(distance(0)*samplesPerMeter)),
samplesPerMeter: samplesPerMeter,
}
}
type doppler struct {
r *beep.Resampler
distance func(delta int) float64
space [][2]float64
samplesPerMeter float64
}
func (d *doppler) Stream(samples [][2]float64) (n int, ok bool) {
distance := d.distance(len(samples))
currentSpaceLen := int(distance * d.samplesPerMeter)
difference := currentSpaceLen - len(d.space)
d.r.SetRatio(float64(len(samples)) / float64(len(samples)+difference))
d.space = append(d.space, make([][2]float64, len(samples)+difference)...)
rn, _ := d.r.Stream(d.space[len(d.space)-len(samples)-difference:])
d.space = d.space[:len(d.space)-len(samples)-difference+rn]
for i := len(d.space) - rn; i < len(d.space); i++ {
d.space[i][0] /= distance * distance
d.space[i][1] /= distance * distance
}
if len(d.space) == 0 {
return 0, false
}
n = copy(samples, d.space)
d.space = d.space[n:]
return n, true
}
func (d *doppler) Err() error {
return d.r.Err()
}
|
package main
import (
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"api/handlers"
"controller"
)
func main() {
e := echo.New()
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"http://localhost:8080","http://localhost:8081","http://localhost:63342","http://52.78.172.184:8080","http://52.78.172.184:8081"},
AllowHeaders: []string{echo.HeaderOrigin,echo.HeaderContentType,echo.HeaderAccept,"Authorization"},
}))
e.GET("/",controller.MainPage)
e.GET("/profits/:id",handlers.GetData)
e.Start(":8080")
}
|
package middleware
import (
"bytes"
"net/http"
"testing"
"github.com/gorilla/mux"
"github.com/stretchr/testify/require"
"github.com/root-gg/plik/server/common"
"github.com/root-gg/plik/server/context"
)
func TestFileNoUpload(t *testing.T) {
ctx := newTestingContext(common.NewConfiguration())
req, err := http.NewRequest("GET", "", &bytes.Buffer{})
require.NoError(t, err, "unable to create new request")
rr := ctx.NewRecorder(req)
File(ctx, common.DummyHandler).ServeHTTP(rr, req)
context.TestInternalServerError(t, rr, "missing upload from context")
}
func TestFileNoFileID(t *testing.T) {
ctx := newTestingContext(common.NewConfiguration())
ctx.SetUpload(&common.Upload{})
req, err := http.NewRequest("GET", "", &bytes.Buffer{})
require.NoError(t, err, "unable to create new request")
rr := ctx.NewRecorder(req)
File(ctx, common.DummyHandler).ServeHTTP(rr, req)
context.TestMissingParameter(t, rr, "file ID")
}
func TestFileNoFileName(t *testing.T) {
ctx := newTestingContext(common.NewConfiguration())
ctx.SetUpload(&common.Upload{})
req, err := http.NewRequest("GET", "", &bytes.Buffer{})
require.NoError(t, err, "unable to create new request")
// Fake gorilla/mux vars
vars := map[string]string{
"fileID": "fileID",
}
req = mux.SetURLVars(req, vars)
rr := ctx.NewRecorder(req)
File(ctx, common.DummyHandler).ServeHTTP(rr, req)
context.TestMissingParameter(t, rr, "file name")
}
func TestFileNotFound(t *testing.T) {
ctx := newTestingContext(common.NewConfiguration())
ctx.SetUpload(&common.Upload{})
req, err := http.NewRequest("GET", "", &bytes.Buffer{})
require.NoError(t, err, "unable to create new request")
// Fake gorilla/mux vars
vars := map[string]string{
"fileID": "fileID",
"filename": "filename",
}
req = mux.SetURLVars(req, vars)
rr := ctx.NewRecorder(req)
File(ctx, common.DummyHandler).ServeHTTP(rr, req)
context.TestNotFound(t, rr, "file fileID not found")
}
func TestFileInvalidFileName(t *testing.T) {
ctx := newTestingContext(common.NewConfiguration())
upload := &common.Upload{}
file := upload.NewFile()
file.Name = "filename"
ctx.SetUpload(upload)
upload.InitializeForTests()
err := ctx.GetMetadataBackend().CreateUpload(upload)
require.NoError(t, err, "create upload error")
req, err := http.NewRequest("GET", "", &bytes.Buffer{})
require.NoError(t, err, "unable to create new request")
// Fake gorilla/mux vars
vars := map[string]string{
"fileID": file.ID,
"filename": "invalid_file_name",
}
req = mux.SetURLVars(req, vars)
rr := ctx.NewRecorder(req)
File(ctx, common.DummyHandler).ServeHTTP(rr, req)
context.TestInvalidParameter(t, rr, "file name")
}
func TestFile(t *testing.T) {
ctx := newTestingContext(common.NewConfiguration())
upload := &common.Upload{}
file := upload.NewFile()
file.Name = "filename"
ctx.SetUpload(upload)
upload.InitializeForTests()
err := ctx.GetMetadataBackend().CreateUpload(upload)
require.NoError(t, err, "create upload error")
req, err := http.NewRequest("GET", "", &bytes.Buffer{})
require.NoError(t, err, "unable to create new request")
// Fake gorilla/mux vars
vars := map[string]string{
"fileID": file.ID,
"filename": file.Name,
}
req = mux.SetURLVars(req, vars)
rr := ctx.NewRecorder(req)
File(ctx, common.DummyHandler).ServeHTTP(rr, req)
require.Equal(t, http.StatusOK, rr.Code, "invalid handler response status code")
f := ctx.GetFile()
require.NotNil(t, f, "missing file from context")
require.Equal(t, file.ID, f.ID, "invalid file from context")
}
func TestFileMetadataBackendError(t *testing.T) {
ctx := newTestingContext(common.NewConfiguration())
upload := &common.Upload{}
file := upload.NewFile()
file.Name = "filename"
ctx.SetUpload(upload)
upload.InitializeForTests()
err := ctx.GetMetadataBackend().CreateUpload(upload)
require.NoError(t, err, "create upload error")
req, err := http.NewRequest("GET", "", &bytes.Buffer{})
require.NoError(t, err, "unable to create new request")
// Fake gorilla/mux vars
vars := map[string]string{
"fileID": file.ID,
"filename": file.Name,
}
req = mux.SetURLVars(req, vars)
err = ctx.GetMetadataBackend().Shutdown()
require.NoError(t, err, "unable to shutdown metadata backend")
rr := ctx.NewRecorder(req)
File(ctx, common.DummyHandler).ServeHTTP(rr, req)
context.TestInternalServerError(t, rr, "database is closed")
}
|
package main
import (
"fmt"
"os"
"github.com/takatoh/fft"
"github.com/takatoh/infr"
"github.com/takatoh/seismicwave"
)
func main() {
csvfile := os.Args[1]
w, e := seismicwave.LoadCSV(csvfile)
if e != nil {
fmt.Println(e)
os.Exit(1)
}
acc := w[0].Data
dt := w[0].Dt
n := len(acc)
v0 := acc[0] * dt
nn := 2
for nn < n {
nn *= 2
}
c := make([]complex128, nn)
for i := 0; i < n; i++ {
c[i] = complex(acc[i], 0.0)
}
for i := n; i < nn; i++ {
c[i] = complex(0.0, 0.0)
}
cf := fft.FFT(c, nn)
cf = infr.Integrate(cf, nn, dt, v0)
c = fft.IFFT(cf, nn)
vel := make([]float64, n)
for i := 0; i < n; i++ {
vel[i] = real(c[i])
}
cf = fft.FFT(c, nn)
cf = infr.Integrate(cf, nn, dt, 0.0)
c = fft.IFFT(cf, nn)
dis := make([]float64, n)
for i := 0; i < n; i++ {
dis[i] = real(c[i])
}
for i := 0; i < n; i++ {
fmt.Printf("%f,%f\n", vel[i], dis[i])
}
}
|
package stack
import "testing"
func TestIsValid(t *testing.T) {
s := "[](){}"
t.Log(isValid(s))
s = "[()]{}"
t.Log(isValid(s))
s = "("
t.Log(isValid(s))
s = "(][]()"
t.Log(isValid(s))
s = "]"
t.Log(isValid(s))
}
|
package add
/*
import (
"io/ioutil"
"os"
"testing"
"github.com/devspace-cloud/devspace/cmd/flags"
"github.com/devspace-cloud/devspace/pkg/devspace/config/loader"
"github.com/devspace-cloud/devspace/pkg/devspace/config/constants"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/config"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/v1beta3"
"github.com/devspace-cloud/devspace/pkg/util/fsutil"
"github.com/devspace-cloud/devspace/pkg/util/log"
"github.com/devspace-cloud/devspace/pkg/util/ptr"
"github.com/devspace-cloud/devspace/pkg/util/survey"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"
"gotest.tools/assert"
)
type addDeploymentTestCase struct {
name string
fakeConfig config.Config
args []string
answers []string
cmd *deploymentCmd
expectedErr string
expectedConfig latest.Config
}
func TestRunAddDeployment(t *testing.T) {
testCases := []addDeploymentTestCase{
addDeploymentTestCase{
name: "Add already existing deployment",
args: []string{"exists"},
fakeConfig: &latest.Config{
Version: latest.Version,
Deployments: []*latest.DeploymentConfig{
&latest.DeploymentConfig{
Name: "exists",
Kubectl: &latest.KubectlConfig{
Manifests: []string{""},
},
},
},
},
expectedErr: "Deployment exists already exists",
expectedConfig: latest.Config{
Version: latest.Version,
Deployments: []*latest.DeploymentConfig{
&latest.DeploymentConfig{
Name: "exists",
Kubectl: &latest.KubectlConfig{
Manifests: []string{""},
},
},
},
Dev: &latest.DevConfig{},
},
},
addDeploymentTestCase{
name: "Valid kubectl deployment",
args: []string{"newKubectlDeployment"},
fakeConfig: &latest.Config{
Version: "v1beta3",
},
cmd: &deploymentCmd{
Manifests: "these, are, manifests",
GlobalFlags: &flags.GlobalFlags{
Namespace: "kubectlNamespace",
},
},
expectedConfig: latest.Config{
Version: latest.Version,
Deployments: []*latest.DeploymentConfig{
&latest.DeploymentConfig{
Name: "newKubectlDeployment",
Namespace: "kubectlNamespace",
Kubectl: &latest.KubectlConfig{
Manifests: []string{"these", "are", "manifests"},
},
},
},
Dev: &latest.DevConfig{},
},
},
addDeploymentTestCase{
name: "Valid helm deployment",
args: []string{"newHelmDeployment"},
fakeConfig: &latest.Config{
Version: "v1beta3",
},
cmd: &deploymentCmd{
Chart: "myChart",
ChartRepo: "myChartRepo",
ChartVersion: "myChartVersion",
},
expectedConfig: latest.Config{
Version: latest.Version,
Deployments: []*latest.DeploymentConfig{
&latest.DeploymentConfig{
Name: "newHelmDeployment",
Helm: &latest.HelmConfig{
Chart: &latest.ChartConfig{
Name: "myChart",
RepoURL: "myChartRepo",
Version: "myChartVersion",
},
},
},
},
Dev: &latest.DevConfig{},
},
},
addDeploymentTestCase{
name: "Valid dockerfile deployment",
args: []string{"newDockerfileDeployment"},
answers: []string{"1234"},
fakeConfig: &latest.Config{
Version: "v1beta3",
},
cmd: &deploymentCmd{
Dockerfile: "myDockerfile",
Image: "myImage",
Context: "myContext",
},
expectedConfig: latest.Config{
Version: latest.Version,
Deployments: []*latest.DeploymentConfig{
&latest.DeploymentConfig{
Name: "newDockerfileDeployment",
Helm: &latest.HelmConfig{
ComponentChart: ptr.Bool(true),
Values: map[interface{}]interface{}{
"containers": []latest.ImageConfig{
latest.ImageConfig{
Image: "myImage",
},
},
"service": latest.ServiceConfig{
Ports: []*latest.ServicePortConfig{
&latest.ServicePortConfig{
Port: ptr.Int(1234),
},
},
},
},
},
},
},
Images: map[string]*latest.ImageConfig{
"newDockerfileDeployment": &latest.ImageConfig{
Image: "myImage",
Dockerfile: "myDockerfile",
Context: "myContext",
CreatePullSecret: ptr.Bool(true),
},
},
Dev: &latest.DevConfig{},
},
},
addDeploymentTestCase{
name: "Valid image deployment",
args: []string{"newImageDeployment"},
answers: []string{"1234"},
fakeConfig: &v1beta3.Config{
Version: "v1beta3",
Images: map[string]*v1beta3.ImageConfig{
"someImage": &v1beta3.ImageConfig{
Image: "someImage",
},
},
},
cmd: &deploymentCmd{
Image: "myImage",
Context: "myContext",
},
expectedConfig: latest.Config{
Version: latest.Version,
Deployments: []*latest.DeploymentConfig{
&latest.DeploymentConfig{
Name: "newImageDeployment",
Helm: &latest.HelmConfig{
ComponentChart: ptr.Bool(true),
Values: map[interface{}]interface{}{
"containers": []latest.ImageConfig{
latest.ImageConfig{
Image: "myImage",
},
},
"service": latest.ServiceConfig{
Ports: []*latest.ServicePortConfig{
&latest.ServicePortConfig{
Port: ptr.Int(1234),
},
},
},
},
},
},
},
Images: map[string]*latest.ImageConfig{
"someImage": &latest.ImageConfig{
Image: "someImage",
},
"newImageDeployment": &latest.ImageConfig{
Image: "myImage",
Tag: "latest",
CreatePullSecret: ptr.Bool(true),
Build: &latest.BuildConfig{
Disabled: ptr.Bool(true),
},
},
},
Dev: &latest.DevConfig{},
},
},
}
log.SetInstance(&log.DiscardLogger{PanicOnExit: true})
for _, testCase := range testCases {
testRunAddDeployment(t, testCase)
}
}
func testRunAddDeployment(t *testing.T, testCase addDeploymentTestCase) {
dir, err := ioutil.TempDir("", "test")
if err != nil {
t.Fatalf("Error creating temporary directory: %v", err)
}
wdBackup, err := os.Getwd()
if err != nil {
t.Fatalf("Error getting current working directory: %v", err)
}
err = os.Chdir(dir)
if err != nil {
t.Fatalf("Error changing working directory: %v", err)
}
for _, answer := range testCase.answers {
survey.SetNextAnswer(answer)
}
if testCase.fakeConfig != nil {
fakeConfigAsYaml, err := yaml.Marshal(testCase.fakeConfig)
assert.NilError(t, err, "Error parsing fakeConfig into yaml in testCase %s", testCase.name)
fsutil.WriteToFile(fakeConfigAsYaml, constants.DefaultConfigPath)
}
loader.ResetConfig()
defer func() {
//Delete temp folder
err = os.Chdir(wdBackup)
if err != nil {
t.Fatalf("Error changing dir back: %v", err)
}
err = os.RemoveAll(dir)
if err != nil {
t.Fatalf("Error removing dir: %v", err)
}
}()
if testCase.cmd == nil {
testCase.cmd = &deploymentCmd{}
}
if testCase.cmd.GlobalFlags == nil {
testCase.cmd.GlobalFlags = &flags.GlobalFlags{}
}
err = (testCase.cmd).RunAddDeployment(nil, testCase.args)
if testCase.expectedErr == "" {
assert.NilError(t, err, "Unexpected error in testCase %s.", testCase.name)
} else {
assert.Error(t, err, testCase.expectedErr, "Wrong or no error in testCase %s.", testCase.name)
}
config, err := loadConfigFromPath()
if err != nil {
configContent, _ := fsutil.ReadFile(constants.DefaultConfigPath, -1)
t.Fatalf("Error loading config after adding deployment in testCase %s: \n%v\n Content of %s:\n%s", testCase.name, err, constants.DefaultConfigPath, string(configContent))
}
configAsYaml, _ := yaml.Marshal(config)
expectedAsYaml, _ := yaml.Marshal(testCase.expectedConfig)
assert.Equal(t, string(configAsYaml), string(expectedAsYaml), "Unexpected config in testCase %s.\nExpected:\n%s\nActual config:\n%s", testCase.name, string(expectedAsYaml), string(configAsYaml))
}
func loadConfigFromPath() (*latest.Config, error) {
yamlFileContent, err := ioutil.ReadFile(constants.DefaultConfigPath)
if err != nil {
return nil, err
}
oldConfig := map[interface{}]interface{}{}
err = yaml.Unmarshal(yamlFileContent, oldConfig)
if err != nil {
return nil, err
}
newConfig, err := versions.Parse(oldConfig, nil, log.Discard)
if err != nil {
return nil, errors.Wrap(err, "parsing versions")
}
return newConfig, nil
}
*/
|
package inform
import (
// Standard library
"bytes"
"context"
"os/exec"
"strings"
"text/template"
// Third-party packages
"github.com/go-joe/joe"
"github.com/pkg/errors"
)
// The prefix used for all keys stored.
const keyPrefix = "org.deuill.informbot"
type Inform struct {
sessions map[string]*Session // A list of open sessions, against their authors.
bot *joe.Bot // The initialized bot to read commands from and send responses to.
config *Config // The configuration for the Inform bot.
}
func (n *Inform) SayTemplate(channel string, template *template.Template, data interface{}) error {
var buf bytes.Buffer
if err := template.Execute(&buf, data); err != nil || buf.Len() == 0 {
n.bot.Say(channel, messageUnknownError)
return err
}
n.bot.Say(channel, buf.String())
return nil
}
func (n *Inform) Handle(ctx context.Context, ev joe.ReceiveMessageEvent) error {
// Validate event data.
if ev.AuthorID == "" {
n.bot.Say(ev.Channel, messageUnknownError)
return nil
}
// Check for stored rule-set against author ID, and send welcome message if none was found.
var author, authorKey = &Author{}, keyPrefix + ".author." + ev.AuthorID
if ok, err := n.bot.Store.Get(authorKey, author); err != nil {
n.bot.Say(ev.Channel, messageUnknownError)
return err
} else if !ok {
if err := n.SayTemplate(ev.Channel, templateWelcome, nil); err != nil {
return errors.Wrap(err, "failed storing author information")
}
// Create and store new Author representation.
author = NewAuthor(ev.AuthorID)
if err := n.bot.Store.Set(authorKey, author); err != nil {
n.bot.Say(ev.Channel, messageUnknownError)
return err
}
}
// Check for open session, and handle command directly if not prefixed.
var cmd = ev.Text
if n.sessions[author.ID] != nil {
if !strings.HasPrefix(ev.Text, author.Options.Prefix) {
if err := n.sessions[author.ID].Run(cmd); err != nil {
n.bot.Say(ev.Channel, messageRunError, err)
return err
}
n.bot.Say(ev.Channel, n.sessions[author.ID].Output())
return nil
} else {
cmd = ev.Text[len(author.Options.Prefix):]
}
}
// Handle meta-commands.
var fields = strings.Fields(cmd)
if len(fields) == 0 {
return nil
} else if len(fields) == 1 {
cmd = fields[0]
} else if len(fields) >= 2 {
cmd = strings.Join(fields[:2], " ")
}
switch strings.ToLower(cmd) {
case "help", "h":
return n.SayTemplate(ev.Channel, templateHelp, nil)
case "story", "stories", "story list", "list stories", "s":
return n.SayTemplate(ev.Channel, templateStoryList, author)
case "story add", "stories add", "add stories":
if len(fields) < 4 {
n.bot.Say(ev.Channel, messageUnknownStory)
} else if story, err := author.AddStory(fields[2], fields[3]); err != nil {
n.bot.Say(ev.Channel, messageInvalidStory, err)
} else if err := story.Compile(ctx, n.config); err != nil {
n.bot.Say(ev.Channel, "TODO: Compilation error: "+err.Error())
return err
} else if err = n.bot.Store.Set(authorKey, author); err != nil {
n.bot.Say(ev.Channel, messageUnknownError)
return err
} else {
n.bot.Say(ev.Channel, messageAddedStory, fields[2])
}
return nil
case "story remove", "stories remove", "story rem", "stories rem":
// TODO: Check for active session.
if len(fields) < 3 {
n.bot.Say(ev.Channel, messageUnknownStory)
} else if err := author.RemoveStory(fields[2]); err != nil {
n.bot.Say(ev.Channel, messageInvalidStory, err)
} else if err = n.bot.Store.Set(authorKey, author); err != nil {
n.bot.Say(ev.Channel, messageUnknownError)
return err
} else {
n.bot.Say(ev.Channel, messageRemovedStory, fields[2])
}
return nil
case "story start", "stories start":
if len(fields) < 3 {
n.bot.Say(ev.Channel, messageUnknownStory)
} else if story, err := author.GetStory(fields[2]); err != nil {
n.bot.Say(ev.Channel, messageInvalidStory, err)
} else if _, ok := n.sessions[author.ID]; ok {
n.bot.Say(ev.Channel, "TODO: Stop session before starting")
} else if sess, err := NewSession(story); err != nil {
n.bot.Say(ev.Channel, messageInvalidSession, err)
return err
} else if err = sess.Start(ctx, n.config); err != nil {
n.bot.Say(ev.Channel, "TODO: Cannot start session: %s", err)
return err
} else {
n.bot.Say(ev.Channel, messageStartedSession, fields[2], author.Options.Prefix)
n.bot.Say(ev.Channel, sess.Output())
n.sessions[author.ID] = sess
}
return nil
case "story end", "stories end":
if n.sessions[author.ID] == nil {
n.bot.Say(ev.Channel, "TODO: No active session")
} else {
n.bot.Say(ev.Channel, "TODO: Stopped session")
delete(n.sessions, author.ID)
}
return nil
case "option", "options", "option list", "list options", "o":
return n.SayTemplate(ev.Channel, templateOptionList, author)
case "option set", "options set", "set option", "set options":
if len(fields) < 4 {
n.bot.Say(ev.Channel, messageUnknownOption)
} else if err := author.SetOption(fields[2], fields[3]); err != nil {
n.bot.Say(ev.Channel, messageInvalidOption, err)
} else if err = n.bot.Store.Set(authorKey, author); err != nil {
n.bot.Say(ev.Channel, messageUnknownError)
return err
} else {
n.bot.Say(ev.Channel, messageSetOption, fields[2], fields[3])
}
return nil
}
return n.SayTemplate(ev.Channel, templateUnknownCommand, cmd)
}
// Default executable names for required runtime dependencies.
const (
defaultInform7 = "/usr/libexec/ni"
defaultInform6 = "/usr/libexec/inform6"
defaultDumbFrotz = "/usr/bin/dfrotz"
)
type Config struct {
// Required attributes.
Bot *joe.Bot // The bot handler.
// Optional attributes.
Inform7 string // The path to the `ni` Inform 7 compiler.
Inform6 string // The path to the `inform6` Inform 6 compiler.
DumbFrotz string // The path to the `dumb-frotz` interpreter.
}
func New(conf Config) (*Inform, error) {
if conf.Bot == nil {
return nil, errors.New("bot given is nil")
} else if conf.Bot.Store == nil {
return nil, errors.New("storage module required")
}
// Set default paths for runtime dependencies, if needed.
if conf.Inform7 == "" {
conf.Inform7 = defaultInform7
}
if conf.Inform6 == "" {
conf.Inform6 = defaultInform6
}
if conf.DumbFrotz == "" {
conf.DumbFrotz = defaultDumbFrotz
}
// Verify and expand paths for runtime dependencies.
if i7, err := exec.LookPath(conf.Inform7); err != nil {
return nil, errors.Wrap(err, "Inform 7 compiler not found")
} else if i6, err := exec.LookPath(conf.Inform6); err != nil {
return nil, errors.Wrap(err, "Inform 6 compiler not found")
} else if frotz, err := exec.LookPath(conf.DumbFrotz); err != nil {
return nil, errors.Wrap(err, "Frotz interpreter not found")
} else {
conf.Inform7, conf.Inform6, conf.DumbFrotz = i7, i6, frotz
}
return &Inform{
bot: conf.Bot,
config: &conf,
sessions: make(map[string]*Session),
}, nil
}
|
package controller
import (
_ "bytes"
"database/sql"
"fmt"
//"newproject/gtoken"
"newproject/model"
"gitee.com/johng/gf/g/encoding/gjson"
"gitee.com/johng/gf/g/frame/gmvc"
"gitee.com/johng/gf/g/net/ghttp"
//"os"
"os/exec"
"strconv"
_ "strings"
"github.com/Unknwon/goconfig"
_ "golang.org/x/crypto/ssh"
)
//数据库配置
const (
DATABASE = ""
DBNET = "tcp"
DBSERVER = "localhost"
GRANT_USER = "user"
GRANT_PASS = "wanjianning!@#$123"
)
type ControllerMaster struct {
gmvc.Controller
}
// 初始化控制器对象,并绑定操作到Web Server
func init() {
ghttp.GetServer().BindController("/master", &ControllerMaster{})
}
//重写父类构造函数
func (master *ControllerMaster) Init(r *ghttp.Request) {
defer master.Controller.Init(r)
//身份验证层
//获取action
action := GetAction(r, "/master/")
fmt.Println("当前请求:master", action)
// if r.Session.Get("user") == nil {
// r.Response.RedirectTo("/user/login-index")
// r.Exit()
// }
}
//实例化表
func (master *ControllerMaster) M(tables string) *model.Models {
return model.NewDB(tables)
}
//配置master
/***
params:{jsoninfo:{ip:,dbuser:,dbpass:,dbport:,}}
***/
func (master *ControllerMaster) Exec() {
//重启数据库
master.restart()
//获取masterip
params, _ := GetParams(master).ToJson()
conf := new(Config)
gjson.DecodeTo(params, &conf)
//获取数据库句柄
DB, _ := master.getdb(conf)
fmt.Println(conf)
//修改为master入库
//修改配置文件
master.saveconfig("1")
master.restart()
fmt.Println("restart ok")
DB, _ = master.getdb(conf)
rows, _ := DB.Query("show databases")
var databases = make([]string, 10, 10)
var i int = 1
for rows.Next() {
var Database string
rows.Scan(&Database)
databases[i] = Database
i++
fmt.Println(Database)
}
fmt.Println("总共有" + strconv.Itoa(i) + "个数据库")
//查询主数据库的状态
master_status := master.showstatus(DB)
master.Response.WriteJson(&Response{Success: 0, Msg: master_status})
}
//获取master状态主要信息
func GetMasterStatus(masterip string) map[string]interface{} {
var resp map[string]interface{} = make(map[string]interface{})
var resp1 Response
conf := new(Config)
tb_master := model.NewDB("config")
condition, _ := gjson.Encode([]map[string]interface{}{{"name": "ip", "value": masterip, "op": "="}})
cond, _ := gjson.DecodeToJson(condition)
res := tb_master.Where(cond.ToArray()).Select()
for _, v := range res {
gjson.DecodeTo(v, &conf)
}
//获取数据库句柄
masterinfo, _ := gjson.Encode(conf)
params_b := ghttp.BuildParams(map[string]string{
"jsoninfo": string(masterinfo),
})
r, e := ghttp.NewClient().Post("http://"+masterip+":8888/master/get-master-status", params_b)
if e != nil {
return resp
}
gjson.DecodeTo(r.ReadAll(), &resp1)
if resp1.Success == 0 {
return resp1.Msg.(map[string]interface{})
}
return resp
}
/***
params:{jsoninfo:{ip:,dbuser:,dbpass:,dbport:,}}
***/
func (master *ControllerMaster) GetMasterStatus() {
//获取masterip
params, _ := GetParams(master).ToJson()
conf := new(Config)
gjson.DecodeTo(params, &conf)
//获取数据库句柄
DB, _ := master.getdb(conf)
//查询主数据库的状态
master_status := master.showstatus(DB)
msg := gjson.New(map[string]string{"file": master_status["File"], "pos": master_status["Position"]})
master.Response.WriteJson(&Response{Success: 0, Msg: msg.ToMap()})
}
func (master *ControllerMaster) showstatus(DB *sql.DB) map[string]string {
rows, err := DB.Query("show master status")
fmt.Println(rows, err)
//master status
var master_status = make(map[string]string)
for rows.Next() {
var File string
var Position string
var Binlog_Do_DB string
var Binlog_Ignore_DB string
var Executed_Gtid_Set string
err = rows.Scan(&File, &Position, &Binlog_Do_DB, &Binlog_Ignore_DB, &Executed_Gtid_Set)
master_status["File"] = File
master_status["Position"] = Position
master_status["Binlog_Do_DB"] = Binlog_Do_DB
master_status["Binlog_Ignore_DB"] = Binlog_Ignore_DB
master_status["Executed_Gtid_Set"] = Executed_Gtid_Set
}
return master_status
}
//修改配置文件
func (master *ControllerMaster) saveconfig(server_id string) {
var mysql_config string = "/etc/my.cnf"
if ok, err := IsExists(mysql_config); !ok {
fmt.Println("配置文件不存在", err)
}
//加载配置文件
cfg, err := goconfig.LoadConfigFile(mysql_config)
if err != nil {
fmt.Println("读取配置文件失败[/etc/my.cnf]")
return
}
cfg.SetValue("mysqld", "log-bin", "mysql-bin")
cfg.SetValue("mysqld", "server-id", server_id)
cfg.SetValue("mysqld", "binlog-ignore-db", "sys ")
cfg.SetValue("mysqld", "binlog-ignore-db", "mysql ")
goconfig.SaveConfigFile(cfg, mysql_config)
}
//重启数据库
func (master *ControllerMaster) restart() {
var c = "service mysqld restart"
cmd := exec.Command("sh", "-c", c)
_, err := cmd.Output()
//fmt.Println(cmd.ProcessState)
if err != nil {
master.Response.WriteJson(&Response{Success: 2, Msg: err.Error()})
return
} else {
fmt.Println("启动mysql成功")
}
}
//给master服务器添加授权用户
/***
params:{jsoninfo:{ip:,dbuser:,dbpass:,dbport:,slaveip:,}}
***/
func (master *ControllerMaster) GrantUser() {
conf := new(Config)
params := GetParams(master)
params_b, _ := params.ToJson()
gjson.DecodeTo(params_b, &conf)
DB, err := master.getdb(conf)
if err != nil {
master.Response.WriteJson(&Response{Success: 2, Msg: err.Error()})
return
}
//授权用户命令
_, errs := DB.Exec("grant replication slave on *.* to '" + GRANT_USER + "'@'" + params.GetString("slaveip") + "' identified by '" + GRANT_PASS + "' with grant option")
if errs != nil {
fmt.Println(errs)
master.Response.WriteJson(&Response{Success: 2, Msg: "授权失败!," + errs.Error()})
return
}
//刷新授权命令
if _, err := DB.Exec("flush privileges"); err != nil {
master.Response.WriteJson(&Response{Success: 2, Msg: "登录数据库失败," + err.Error()})
return
}
master.Response.WriteJson(&Response{Success: 0, Msg: "授权该服务器成功!"})
}
func (master *ControllerMaster) getdb(conf *Config) (DB *sql.DB, err error) {
dsn := fmt.Sprintf("%s:%s@%s(%s:%s)/%s", conf.Dbuser, conf.Dbpass, DBNET, DBSERVER, conf.Dbport, DATABASE)
DB, err = sql.Open("mysql", dsn)
if err != nil {
return nil, err
}
//登陆数据库
if err := DB.Ping(); err != nil {
return nil, err
} else {
fmt.Println("数据库登录成功!")
return DB, nil
}
}
|
package utils
import (
"bytes"
"fmt"
"path"
"strings"
"text/template"
)
func sub(left, right int) int {
return left - right
}
func addSuffix(host string, suffix string) string {
if !strings.HasSuffix(host, suffix) {
host += suffix
}
return host
}
// ParseTemp 解析templates
func ParseTemp(filePath string, data interface{}) (b *bytes.Buffer, err error) {
var (
t *template.Template
)
tempFuncMap := template.FuncMap{
"sub": sub,
"suffix": addSuffix,
}
t = template.New(path.Base(filePath)).Funcs(tempFuncMap)
if t, err = t.ParseFiles(filePath); err != nil {
err = fmt.Errorf("ERROR: Parse Template File [%s] Error. %v", filePath, err)
return
}
b = new(bytes.Buffer)
if err = t.Execute(b, data); err != nil {
err = fmt.Errorf("ERROR: Execute Template [%s] Error. %v", filePath, err)
return
}
return
}
|
package main
import (
"fmt"
kernel "mohammedmanssour-events/kernal"
"time"
)
type User struct {
name string
email string
}
func main() {
unsubscribe1 := kernel.Subscribe("UserRegistered", func(event kernel.EventInterface) {
User := event.(User)
fmt.Printf("User Registered with name %s and email %s\n", User.name, User.email)
})
unsubscribe2 := kernel.Subscribe("UserRegistered", func(event kernel.EventInterface) {
User := event.(User)
fmt.Printf("Simulate sending email to %s:%s\n", User.name, User.email)
})
defer unsubscribe1()
defer unsubscribe2()
err := kernel.TriggerEvent(
"UserRegistered",
User{
name: "Mohammed Manssour",
email: "manssour.mohammed@gmail.com",
},
)
if err != nil {
fmt.Printf("Can not trigger %s event", "UserRegistered")
return
}
time.Sleep(time.Second * 3)
}
|
package gcp
// MachinePool stores the configuration for a machine pool installed on GCP.
type MachinePool struct {
// Zones is list of availability zones that can be used.
//
// +optional
Zones []string `json:"zones,omitempty"`
// InstanceType defines the GCP instance type.
// eg. n1-standard-4
//
// +optional
InstanceType string `json:"type"`
// OSDisk defines the storage for instance.
//
// +optional
OSDisk `json:"osDisk"`
// OSImage defines a custom image for instance.
//
// +optional
OSImage *OSImage `json:"osImage,omitempty"`
// Tags defines a set of network tags which will be added to instances in the machineset
//
// +optional
Tags []string `json:"tags,omitempty"`
// SecureBoot Defines whether the instance should have secure boot enabled.
// secure boot Verify the digital signature of all boot components, and halt the boot process if signature verification fails.
// If omitted, the platform chooses a default, which is subject to change over time, currently that default is false.
// +kubebuilder:validation:Enum=Enabled;Disabled
// +optional
SecureBoot string `json:"secureBoot,omitempty"`
// OnHostMaintenance determines the behavior when a maintenance event occurs that might cause the instance to reboot.
// Allowed values are "Migrate" and "Terminate".
// If omitted, the platform chooses a default, which is subject to change over time, currently that default is "Migrate".
// +kubebuilder:validation:Enum=Migrate;Terminate;
// +optional
OnHostMaintenance string `json:"onHostMaintenance,omitempty"`
// ConfidentialCompute Defines whether the instance should have confidential compute enabled.
// If enabled OnHostMaintenance is required to be set to "Terminate".
// If omitted, the platform chooses a default, which is subject to change over time, currently that default is false.
// +kubebuilder:validation:Enum=Enabled;Disabled
// +optional
ConfidentialCompute string `json:"confidentialCompute,omitempty"`
// ServiceAccount is the email of a gcp service account to be used for shared
// vpc installations. The provided service account will be attached to control-plane nodes
// in order to provide the permissions required by the cloud provider in the host project.
// This field is only supported in the control-plane machinepool.
//
// +optional
ServiceAccount string `json:"serviceAccount,omitempty"`
}
// OSDisk defines the disk for machines on GCP.
type OSDisk struct {
// DiskType defines the type of disk.
// For control plane nodes, the valid value is pd-ssd.
// +optional
// +kubebuilder:validation:Enum=pd-balanced;pd-ssd;pd-standard
DiskType string `json:"diskType"`
// DiskSizeGB defines the size of disk in GB.
//
// +kubebuilder:validation:Minimum=16
// +kubebuilder:validation:Maximum=65536
DiskSizeGB int64 `json:"DiskSizeGB"`
// EncryptionKey defines the KMS key to be used to encrypt the disk.
//
// +optional
EncryptionKey *EncryptionKeyReference `json:"encryptionKey,omitempty"`
}
// OSImage defines the image to use for the OS.
type OSImage struct {
// Name defines the name of the image.
//
// +required
Name string `json:"name"`
// Project defines the name of the project containing the image.
//
// +required
Project string `json:"project"`
}
// Set sets the values from `required` to `a`.
func (a *MachinePool) Set(required *MachinePool) {
if required == nil || a == nil {
return
}
if len(required.Zones) > 0 {
a.Zones = required.Zones
}
if required.InstanceType != "" {
a.InstanceType = required.InstanceType
}
if required.Tags != nil {
a.Tags = required.Tags
}
if required.OSDisk.DiskSizeGB > 0 {
a.OSDisk.DiskSizeGB = required.OSDisk.DiskSizeGB
}
if required.OSDisk.DiskType != "" {
a.OSDisk.DiskType = required.OSDisk.DiskType
}
if required.OSImage != nil {
a.OSImage = required.OSImage
}
if required.EncryptionKey != nil {
if a.EncryptionKey == nil {
a.EncryptionKey = &EncryptionKeyReference{}
}
a.EncryptionKey.Set(required.EncryptionKey)
}
if required.SecureBoot != "" {
a.SecureBoot = required.SecureBoot
}
if required.OnHostMaintenance != "" {
a.OnHostMaintenance = required.OnHostMaintenance
}
if required.ConfidentialCompute != "" {
a.ConfidentialCompute = required.ConfidentialCompute
}
if required.ServiceAccount != "" {
a.ServiceAccount = required.ServiceAccount
}
}
// EncryptionKeyReference describes the encryptionKey to use for a disk's encryption.
type EncryptionKeyReference struct {
// KMSKey is a reference to a KMS Key to use for the encryption.
//
// +optional
KMSKey *KMSKeyReference `json:"kmsKey,omitempty"`
// KMSKeyServiceAccount is the service account being used for the
// encryption request for the given KMS key. If absent, the Compute
// Engine default service account is used.
// See https://cloud.google.com/compute/docs/access/service-accounts#compute_engine_service_account
// for details on the default service account.
//
// +optional
KMSKeyServiceAccount string `json:"kmsKeyServiceAccount,omitempty"`
}
// Set sets the values from `required` to `e`.
func (e *EncryptionKeyReference) Set(required *EncryptionKeyReference) {
if required == nil || e == nil {
return
}
if required.KMSKeyServiceAccount != "" {
e.KMSKeyServiceAccount = required.KMSKeyServiceAccount
}
if required.KMSKey != nil {
if e.KMSKey == nil {
e.KMSKey = &KMSKeyReference{}
}
e.KMSKey.Set(required.KMSKey)
}
}
// KMSKeyReference gathers required fields for looking up a GCP KMS Key
type KMSKeyReference struct {
// Name is the name of the customer managed encryption key to be used for the disk encryption.
Name string `json:"name"`
// KeyRing is the name of the KMS Key Ring which the KMS Key belongs to.
KeyRing string `json:"keyRing"`
// ProjectID is the ID of the Project in which the KMS Key Ring exists.
// Defaults to the VM ProjectID if not set.
//
// +optional
ProjectID string `json:"projectID,omitempty"`
// Location is the GCP location in which the Key Ring exists.
Location string `json:"location"`
}
// Set sets the values from `required` to `k`.
func (k *KMSKeyReference) Set(required *KMSKeyReference) {
if required == nil || k == nil {
return
}
if required.Name != "" {
k.Name = required.Name
}
if required.KeyRing != "" {
k.KeyRing = required.KeyRing
}
if required.ProjectID != "" {
k.ProjectID = required.ProjectID
}
if required.Location != "" {
k.Location = required.Location
}
}
|
package auth
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
"ions_zhiliao/models/auth"
"ions_zhiliao/utils"
"math"
"time"
)
type AuthController struct {
beego.Controller
}
func (a *AuthController) List() {
//每页显示的条数
o := orm.NewOrm()
qs := o.QueryTable("sys_auth")
var auths []auth.Auth
pageSize := 10
pageNo, err := a.GetInt("page")
if err != nil {
pageNo = 1
}
var count int64 = 0
offsetNum := pageSize * (pageNo-1)
kw := a.GetString("kw")
if kw != "" {
count, _ = qs.Filter("is_delete", 0).Filter("auth_name__contains", kw).Count()
_, _ = qs.Filter("is_delete",0).Filter("auth_name__contains",kw).Limit(pageSize).Offset(offsetNum).All(&auths)
}else {
count, _ = qs.Filter("is_delete", 0).Count()
_, _ = qs.Filter("is_delete",0).Limit(pageSize).Offset(offsetNum).All(&auths)
}
//总页数
countPage := int(math.Ceil(float64(count)/float64(pageSize)))
prePage := 1
if pageNo == 1 {
prePage = 1
}else if pageNo>1 {
prePage = pageNo - 1
}
nextPage := 1
if pageNo < countPage {
nextPage = pageNo + 1
}else if pageNo >= countPage {
nextPage = pageNo
}
page_map := utils.Paginator(pageNo,pageSize,count)
a.Data["auths"] = auths
a.Data["count"] = count
a.Data["pageNo"] = pageNo
a.Data["prePage"] = prePage
a.Data["nextPage"] = nextPage
a.Data["countPage"] = countPage
a.Data["page_map"] = page_map
a.Data["kw"] = kw
a.TplName = "auth/auth-list.html"
}
func (a *AuthController) ToAdd() {
var auths []auth.Auth
o:=orm.NewOrm()
qs := o.QueryTable("sys_auth")
_, err := qs.Filter("is_delete", 0).All(&auths)
if err != nil {
logs.Info("获取权限数据错误:",err)
}
a.Data["auths"] = auths
a.TplName = "auth/auth-add.html"
}
func (a *AuthController) DoAdd() {
pid, err := a.GetInt("pid")
if err != nil {
logs.Info("父级id获取失败:",err)
}
auth_name := a.GetString("auth_name")
url_for := a.GetString("url_for")
desc := a.GetString("desc")
is_active, err := a.GetInt("is_active")
if err != nil {
logs.Info("状态获取失败:",err)
}
weight, err := a.GetInt("weight")
if err != nil {
logs.Info("权重获取失败:",err)
}
fmt.Println("==========",pid,auth_name,url_for,desc,is_active,weight)
o := orm.NewOrm()
auth_data := auth.Auth{AuthName:auth_name,UrlFor:url_for,Pid:pid,Desc:desc,CreateTime:time.Now(),IsActive:is_active,Weight:weight}
ret_map := map[string]interface{}{}
id, err := o.Insert(&auth_data)
if err != nil {
fmt.Println(err)
ret_map["code"]=10001
ret_map["msg"]="添加失败,重新操作!"
a.Data["json"] = ret_map
}else {
fmt.Println(id)
ret_map["code"]=200
ret_map["msg"]="添加成功!"
a.Data["json"] = ret_map
}
a.ServeJSON()
}
|
package entrypoint
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/urfave/cli"
)
func TestStringFlagRequiredOnMissingFlag(t *testing.T) {
t.Parallel()
app := createSampleAppWithRequiredFlag()
app.Action = func(cliContext *cli.Context) error {
value, err := StringFlagRequiredE(cliContext, "the-answer-to-all-problems")
assert.NotNil(t, err)
assert.IsType(t, &RequiredArgsError{}, err)
assert.Equal(t, value, "")
return nil
}
args := []string{"app"}
app.Run(args)
}
func TestStringFlagRequiredOnSetFlag(t *testing.T) {
t.Parallel()
app := createSampleAppWithRequiredFlag()
app.Action = func(cliContext *cli.Context) error {
value, err := StringFlagRequiredE(cliContext, "the-answer-to-all-problems")
assert.Nil(t, err)
assert.Equal(t, value, "42")
return nil
}
args := []string{"app", "--the-answer-to-all-problems", "42"}
app.Run(args)
}
func TestEnvironmentVarRequiredOnMissingEnvVar(t *testing.T) {
value, err := EnvironmentVarRequiredE("THE_ANSWER_TO_ALL_PROBLEMS")
assert.NotNil(t, err)
assert.IsType(t, &RequiredArgsError{}, err)
assert.Equal(t, value, "")
}
func TestEnvironmentVarRequiredOnSetEnvVar(t *testing.T) {
os.Setenv("THE_ANSWER_TO_ALL_PROBLEMS", "42")
value, err := EnvironmentVarRequiredE("THE_ANSWER_TO_ALL_PROBLEMS")
assert.Nil(t, err)
assert.Equal(t, value, "42")
}
func createSampleAppWithRequiredFlag() *cli.App {
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "the-answer-to-all-problems",
},
}
return app
}
|
package main
import (
"encoding/binary"
"errors"
"github.com/g-xianhui/crypt"
"io"
"net"
)
var _ = io.EOF
const MAX_CLIENT_BUF = 1 << 16
func Readn(conn io.Reader, count int) ([]byte, int, error) {
data := make([]byte, count)
n := 0
for {
i, err := conn.Read(data[n:])
if i > 0 {
n += i
}
if n == count || err != nil {
return data, n, err
}
}
}
// read a package from conn, package is format like: | length(2) | data(lenght) |
func readPack(conn io.Reader) ([]byte, error) {
lenbuf, n, err := Readn(conn, 2)
if n < 2 {
if err == io.EOF && n == 0 {
return nil, err
} else {
log(ERROR, "Readn: %s\n", err)
return nil, errors.New("uncomplete head")
}
}
textLen := int(binary.BigEndian.Uint16(lenbuf))
data, n, err := Readn(conn, textLen)
if n < textLen {
log(ERROR, "Readn: %s\n", err)
return nil, errors.New("uncomplete content")
}
return data, nil
}
func readEncrypt(conn io.Reader, secret []byte) ([]byte, error) {
ciphertext, err := readPack(conn)
if err != nil {
return nil, err
}
data, err := crypt.AesDecrypt(ciphertext, secret)
if err != nil {
return nil, err
}
return data, nil
}
// send a package to conn
func writePack(conn io.Writer, data []byte) error {
l := len(data)
if l >= MAX_CLIENT_BUF {
return errors.New("msg is too big")
}
pack := make([]byte, l+2)
binary.BigEndian.PutUint16(pack[:2], uint16(l))
copy(pack[2:], data)
if _, err := conn.Write(pack); err != nil {
return err
}
return nil
}
func writeEncrypt(conn io.Writer, data []byte, secret []byte) error {
ciphertext, err := crypt.AesEncrypt(data, secret)
if err != nil {
return err
}
return writePack(conn, ciphertext)
}
func recv(conn net.Conn, secret []byte, dst chan<- Msg, quit <-chan struct{}, connecttime int64) {
DONE:
for {
select {
case <-quit:
break DONE
default:
pack, err := readEncrypt(conn, secret)
if pack != nil {
m := unpackMsg(pack)
if m == nil {
continue
}
// maybe session unequal
dst <- m
}
if err != nil {
if err != io.EOF {
log(ERROR, "read from client: %s\n", err)
} else {
m := &InnerMsg{cmd: "disconnect", ud: connecttime}
dst <- m
log(DEBUG, "client end\n")
}
break DONE
}
}
}
conn.Close()
}
func send(conn net.Conn, m *NetMsg, secret []byte) error {
return writeEncrypt(conn, packMsg(m), secret)
}
|
package main
import (
"log"
)
//node定义
type Node struct {
Data interface{} //数据域
next *Node //指针域
belong *SingelChain //Node归属链
}
type SingelChain struct {
root Node //存储头结点
length int //存储当前长度
}
func (l *SingelChain) Init() *SingelChain {
l.root.next = nil
l.length = 0
return l
}
//返回链表的长度
func (l *SingelChain) Len() int {
return l.length
}
//返回第一个节点
func (l *SingelChain) Front() *Node {
if l.length == 0 {
return nil
}
return l.root.next
}
//返回最后一个节点
func (l *SingelChain) Back() *Node {
if l.length == 0 {
return nil
}
n := l.root.next
for n.next != nil {
n = n.next
}
return n
}
//在at节点后面插入e,并返回e
func (l *SingelChain) insert(e, at *Node) *Node {
n := at.next
at.next = e
e.next = n
l.length++
e.belong = l
return e
}
func (l *SingelChain) Insert(e, at *Node) *Node {
return l.insert(e, at)
}
func (l *SingelChain) InsertValue(v interface{}, at *Node) *Node {
return l.insert(&Node{Data: v}, at)
}
//去除l中的e节点
func (l *SingelChain) remove(e *Node) interface{} {
n := e.next
temp := &l.root
for temp.next != e {
temp = temp.next
}
temp.next = n
l.length--
e.belong = nil
return e.Data
}
func (l *SingelChain) Remove(e *Node) interface{} {
//e.gelong == l: l must have been initialized when e was inserted
//and root.belong is nil.if e == nil
if e.belong == l {
return l.remove(e)
}
return nil
}
|
package userinterface
import (
"unicode"
"unicode/utf8"
ui "github.com/gizak/termui/v3"
"github.com/gizak/termui/v3/widgets"
)
var (
text string
)
func inputWidgetInit(width, height int) *widgets.Paragraph {
p := widgets.NewParagraph()
p.Text = prettyPrint("")
p.SetRect(0, 0, width, 3)
ui.Render(p)
return p
}
func handleClientEvent(l *look, e string,
clientEvents chan string, quit chan int) {
input_p := l.input_p
switch {
case e == "<C-c>":
quit <- 1
return
case isToPrint(e):
text += e
input_p.Text = prettyPrint(text)
ui.Render(input_p)
case e == "<Space>":
text += " "
input_p.Text = prettyPrint(text)
ui.Render(input_p)
case e == "<Backspace>":
if len(text) == 0 {
break
}
text = trimLastChar(text)
input_p.Text = prettyPrint(text)
ui.Render(input_p)
case e == "<Enter>":
if len(text) == 0 {
break
}
clientEvents <- text
text = ""
input_p.Text = prettyPrint(text)
ui.Render(input_p)
}
}
func isToPrint(s string) bool {
var (
i int
r rune
)
for i, r = range s {
if i > 0 {
return false
}
}
if unicode.IsPrint(r) {
return true
}
return false
}
func trimLastChar(s string) string {
r, size := utf8.DecodeLastRuneInString(s)
if r == utf8.RuneError && (size == 0 || size == 1) {
size = 0
}
return s[:len(s)-size]
}
func prettyPrint(s string) string {
return "-> " + s + "|"
}
|
package fmc
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/mattn/go-isatty"
)
// Base attributes
const (
reset attribute = iota
bold
faint
italic
underline
blinkSlow
blinkRapid
reverseVideo
concealed
crossedOut
)
// Foreground text colors
const (
fgBlack attribute = iota + 30
fgRed
fgGreen
fgYellow
fgBlue
fgMagenta
fgCyan
fgWhite
)
const escape = "\x1b"
type attribute int
type color struct {
params []attribute
nocolor *bool
}
func (c *color) add(value ...attribute) *color {
c.params = append(c.params, value...)
return c
}
func new(value ...attribute) *color {
c := &color{params: make([]attribute, 0)}
c.add(value...)
return c
}
func (c *color) sequence() string {
format := make([]string, len(c.params))
for i, v := range c.params {
format[i] = strconv.Itoa(int(v))
}
return strings.Join(format, ";")
}
func (c *color) isNocolorSet() bool {
// check first if we have user setted action
if c.nocolor != nil {
return *c.nocolor
}
// if not return the global option, which is disabled by default
return nocolor
}
func (c *color) wrap(s string) string {
if c.isNocolorSet() {
return s
}
return c.format() + s + c.unformat()
}
func (c *color) sprintfFunc() func(format string, a ...interface{}) string {
return func(format string, a ...interface{}) string {
return c.wrap(fmt.Sprintf(format, a...))
}
}
func (c *color) sprintfFuncS() func(format string) string {
return func(format string) string {
color := fmt.Sprintf("%s[%sm", escape, c.sequence())
//d:=
return color + format + fmt.Sprintf("%s[%s", escape, c.unformat())
//return c.wrap(fmt.Sprintf(format, a...))
}
//return func(format string) string {
//}
}
func (c *color) format() string {
return fmt.Sprintf("%s[%sm", escape, c.sequence())
}
func (c *color) unformat() string {
return fmt.Sprintf("%s[%dm", escape, reset)
}
func checkSharp(format string) bool {
if strings.Contains(format, "#") == true {
return true
}
return false
}
func setcolor(item string) string {
color := ""
mess := ""
itemLen := len(item)
// fmt.Printf("item:%s, itemLen: '%d'\n", item, itemLen)
if 3 < itemLen {
// fmt.Printf("item[3]: '%s'\n", string(item[3]))
color = item[0:3]
if 4 <= itemLen {
if string(item[3]) == " " {
// fmt.Println("item[3]")
if 4 < len(item) {
mess = item[4:]
} else {
mess = item[3:]
}
} else {
// fmt.Println("!item[3]")
mess = item[3:]
}
} else {
mess = item[3:]
}
} else {
color = ""
mess = ""
}
// fmt.Printf("color: %s\n", color)
// fmt.Printf("mess: %s\n", mess)
world := " "
switch color {
case "yst":
world = yst(mess)
case "ybt":
world = ybt(mess)
case "rst":
world = rst(mess)
case "rbt":
world = rbt(mess)
case "gst":
world = gst(mess)
case "gbt":
world = gbt(mess)
case "bst":
world = bst(mess)
case "bbt":
world = bbt(mess)
case "wst":
world = wst(mess)
case "wbt":
world = wbt(mess)
default:
world = mess
}
//fmt.Printf("wordset:%s\n", world)
return world
}
var (
yst = new(fgYellow).sprintfFuncS()
ybt = new(fgYellow, bold).sprintfFuncS()
rst = new(fgRed).sprintfFuncS()
rbt = new(fgRed, bold).sprintfFuncS()
gst = new(fgGreen).sprintfFuncS()
gbt = new(fgGreen, bold).sprintfFuncS()
bst = new(fgBlue).sprintfFuncS()
bbt = new(fgBlue, bold).sprintfFuncS()
wst = new(fgWhite).sprintfFuncS()
wbt = new(fgWhite, bold).sprintfFuncS()
nocolor = os.Getenv("TERM") == "dumb" ||
(!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()))
)
//Print interface
func Print(form string) {
fmt.Print(Sprint(form))
}
//Println string
func Println(form string) {
fmt.Print(Sprint(form))
fmt.Printf("\n")
}
//Printf interface
func Printf(format string, a ...interface{}) {
pr := Sprint(format)
t := fmt.Sprintf(pr, a...)
fmt.Printf(t)
}
//Printfln +and line
func Printfln(format string, a ...interface{}) {
pr := Sprint(format)
t := fmt.Sprintf(pr, a...)
fmt.Printf(t)
fmt.Printf("\n")
}
//Sprint prepare string to print or fmt.Sprintf(format, a...)
func Sprint(form string) string {
items := strings.Split(form, "#")
ilen := len(items)
msg := ""
for i := 0; i < ilen; i++ {
item := items[i]
if i == 0 {
msg = msg + item
} else {
if 0 < len(items[i-1]) {
lastSymbol := string((items[i-1])[len(items[i-1])-1])
if lastSymbol != "!" {
rt := setcolor(item)
msg = msg + rt
} else {
msg = msg + item
}
//fmt.Println("last:", lastSymbol)
} else {
rt := setcolor(item)
msg = msg + rt
}
}
}
//fmt.Printf("msg: %s\n", msg)
return msg
}
//PrintfT interface
func printfT(format string, a ...interface{}) {
if checkSharp(format) != true {
fmt.Print(format)
for _, v := range a {
//fmt.Println(fmt.Sprintf("%s[%sm fff", escape, d.sequence()))
fmt.Print(v)
}
return
}
// sep := strings.Split(format, "#")
d := new(fgRed, bold)
frmt := fmt.Sprintf("%s[%sm%s", escape, d.sequence(), format)
//for _, v := range a {
alen := len(a)
per := strings.Split(frmt, "%")
perc := len(per) - 1
if perc < alen {
fmt.Printf("%s %s\n", rbt("[error] Not enough separators in format string:"), format)
return
}
fmt.Printf("a:%d | perc: %d\n", alen, perc)
//letter := fmt.Sprintf(frmt)
//mstring:=
for i := 0; i < len(per); i++ {
typeW := ""
if i == 0 {
typeW = "N"
} else {
typeW = string((per[i])[0])
}
fmt.Printf("per:%s, type:%s \n", per[i], typeW)
}
//fmt.Print(letter)
//}
}
|
package utils
import (
"os"
"testing"
"github.com/stretchr/testify/require"
)
func TestNewAuthorizer(t *testing.T) {
t.Cleanup(func() {
os.RemoveAll("testDir")
})
require.NoError(t, os.MkdirAll("testDir", os.ModePerm))
acct, err := NewKeyFile("testDir", "password123")
require.NoError(t, err)
_, err = NewAuthorizer(acct.URL.Path, "password123")
require.NoError(t, err)
}
|
package main
import "fmt"
var x, y int = 12, 13
var (
xa int = 12
xb string = "ok"
)
func main() {
var a string = "Runoob"
fmt.Println(a)
var b, c int = 1, 2
fmt.Println(b, c)
fmt.Println(x, y)
fmt.Println(xa, xb)
zeroVariable()
multiDefine()
valueAdnReference()
}
func zeroVariable() {
var a string = "Runoob"
fmt.Println(a)
var b int
fmt.Println(b)
var i int
var f float64
var bo bool
var s string
fmt.Printf("%v %v %v %q\n", i, f, bo, s)
var d = true
fmt.Println(d)
varS := "Runoob"
fmt.Println(varS)
}
func multiDefine() {
var vname1, vname2, vname3 int
fmt.Println(vname1, vname2, vname3)
vname11, vname12, vname13 := 3, "3", true
fmt.Println(vname11, vname12, vname13)
}
func valueAdnReference() {
var i int
i = 7
var p *int
p = &i
a := 50
fmt.Println(i, p, a)
}
|
/*
* @lc app=leetcode.cn id=11 lang=golang
*
* [11] 盛最多水的容器
*/
package main
import "fmt"
// @lc code=start
func min(a, b int) int {
if a < b {
return a
} else {
return b
}
}
func maxArea(height []int) int {
heightLen := len(height)
res := 0
area := 0
for i, j := 0, heightLen-1; i != j; {
left, right := height[i], height[j]
area = (j - i) * min(left, right)
if left < right {
i++
} else {
j--
}
if area > res {
res = area
}
}
return res
}
// @lc code=end
func main() {
fmt.Println(maxArea([]int{1, 3, 2, 5, 25, 24, 5}))
}
|
package main
import (
"fmt"
"strings"
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/handlers"
)
type Media struct {
Audio string `json:"audio"`
Wave string `json:"wave"`
Duration string `json:"duration"`
}
func main() {
fmt.Println("Listening on port 8080")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
router := mux.NewRouter()
router.HandleFunc("/waveform/text/{tts_string}", SubmitText).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", handlers.CORS(originsOk, headersOk, methodsOk)(router)))
}
func SubmitText(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
fmt.Println("Getting audio for " + vars["tts_string"])
audio_filename := get_audio(vars["tts_string"])
wave_filename := generate_waveform(audio_filename)
duration := get_duration(audio_filename)
audio_uri := getAbsoluteUrl(audio_filename)
wave_uri := getAbsoluteUrl(wave_filename)
media := Media{audio_uri, wave_uri, duration}
json.NewEncoder(w).Encode(media)
}
func getAbsoluteUrl(path string) (string) {
relative_url := strings.Replace(path, "/var/www/", "", -1)
absolute_url := "http://68.183.30.161/" + relative_url;
return absolute_url
}
|
package resolvers
import (
"context"
"github.com/syncromatics/kafmesh/internal/graph/generated"
)
//go:generate mockgen -source=./resolver.go -destination=./resolver_mock_test.go -package=resolvers_test
// DataLoaders provides data loaders for models from the context
type DataLoaders interface {
ComponentLoader(context.Context) ComponentLoader
PodLoader(context.Context) PodLoader
ProcessorLoader(context.Context) ProcessorLoader
ProcessorInputLoader(context.Context) ProcessorInputLoader
ProcessorJoinLoader(context.Context) ProcessorJoinLoader
ProcessorLookupLoader(context.Context) ProcessorLookupLoader
ProcessorOutputLoader(context.Context) ProcessorOutputLoader
QueryLoader(context.Context) QueryLoader
ServiceLoader(context.Context) ServiceLoader
SinkLoader(context.Context) SinkLoader
SourceLoader(context.Context) SourceLoader
TopicLoader(context.Context) TopicLoader
ViewLoader(context.Context) ViewLoader
ViewSinkLoader(context.Context) ViewSinkLoader
ViewSourceLoader(context.Context) ViewSourceLoader
}
// Subscribers provides subcription handlers
type Subscribers interface {
Processor() ProcessorWatcher
}
var _ generated.ResolverRoot = &Resolver{}
// Resolver resolvers models
type Resolver struct {
DataLoaders DataLoaders
Subscribers Subscribers
}
// NewResolver creates a new resolver
func NewResolver(loaders DataLoaders, subscribers Subscribers) *Resolver {
return &Resolver{
DataLoaders: loaders,
Subscribers: subscribers,
}
}
// Query returns the query resolver
func (r *Resolver) Query() generated.QueryResolver {
return &QueryResolver{r}
}
// Service returns the Service resolver
func (r *Resolver) Service() generated.ServiceResolver {
return &ServiceResolver{r}
}
// Component returns the component resolver
func (r *Resolver) Component() generated.ComponentResolver {
return &ComponentResolver{r}
}
// Pod returns the pod resolver
func (r *Resolver) Pod() generated.PodResolver {
return &PodResolver{r}
}
// Processor returns the processor resolver
func (r *Resolver) Processor() generated.ProcessorResolver {
return &ProcessorResolver{r}
}
// ProcessorInput returns the processor input resolver
func (r *Resolver) ProcessorInput() generated.ProcessorInputResolver {
return &ProcessorInputResolver{r}
}
// ProcessorJoin returns the processor join resolver
func (r *Resolver) ProcessorJoin() generated.ProcessorJoinResolver {
return &ProcessorJoinResolver{r}
}
// ProcessorLookup returns the processor lookupu resolver
func (r *Resolver) ProcessorLookup() generated.ProcessorLookupResolver {
return &ProcessorLookupResolver{r}
}
// ProcessorOutput returns the processor output resolver
func (r *Resolver) ProcessorOutput() generated.ProcessorOutputResolver {
return &ProcessorOutputResolver{r}
}
// Sink returns the sink resolver
func (r *Resolver) Sink() generated.SinkResolver {
return &SinkResolver{r}
}
// Source returns the source resolver
func (r *Resolver) Source() generated.SourceResolver {
return &SourceResolver{r}
}
// Topic returns the topic resolver
func (r *Resolver) Topic() generated.TopicResolver {
return &TopicResolver{r}
}
// View returns the view resolver
func (r *Resolver) View() generated.ViewResolver {
return &ViewResolver{r}
}
// ViewSink returns the view sink resolver
func (r *Resolver) ViewSink() generated.ViewSinkResolver {
return &ViewSinkResolver{r}
}
// ViewSource returns the view source resolver
func (r *Resolver) ViewSource() generated.ViewSourceResolver {
return &ViewSourceResolver{r}
}
// Subscription returns the subscription resolver
func (r *Resolver) Subscription() generated.SubscriptionResolver {
return &Subscription{r}
}
|
package timer
import (
"fmt"
"time"
"github.com/sirupsen/logrus"
)
// Timer is the struct that keeps track of each of the sections.
type Timer struct {
listOfStages []string
stageTimes map[string]time.Duration
startTimes map[string]time.Time
}
const (
// TotalTimeElapsed is a constant string value to denote total time elapsed.
TotalTimeElapsed = "Total"
)
var timer = NewTimer()
// StartTimer initiailzes the timer object with the current timestamp information.
func StartTimer(key string) {
timer.StartTimer(key)
}
// StopTimer records the duration for the current stage sent as the key parameter and stores the information.
func StopTimer(key string) {
timer.StopTimer(key)
}
// LogSummary prints the summary of all the times collected so far into the INFO section.
func LogSummary() {
timer.LogSummary(logrus.StandardLogger())
}
// NewTimer returns a new timer that can be used to track sections and
func NewTimer() Timer {
return Timer{
listOfStages: []string{},
stageTimes: make(map[string]time.Duration),
startTimes: make(map[string]time.Time),
}
}
// StartTimer initializes the timer object with the current timestamp information.
func (t *Timer) StartTimer(key string) {
t.listOfStages = append(t.listOfStages, key)
t.startTimes[key] = time.Now().Round(time.Second)
}
// StopTimer records the duration for the current stage sent as the key parameter and stores the information.
func (t *Timer) StopTimer(key string) time.Duration {
if item, found := t.startTimes[key]; found {
duration := time.Since(item).Round(time.Second)
t.stageTimes[key] = duration
}
return time.Since(time.Now())
}
// LogSummary prints the summary of all the times collected so far into the INFO section.
// The format of printing will be the following:
// If there are no stages except the total time stage, then it only prints the following
// Time elapsed: <x>m<yy>s
// If there are multiple stages, it prints the following:
// Time elapsed for each section
// Stage1: <x>m<yy>s
// Stage2: <x>m<yy>s
// .
// .
// .
// StageN: <x>m<yy>s
// Time elapsed: <x>m<yy>s
// All durations printed are rounded up to the next second value and printed in the format mentioned above.
func (t *Timer) LogSummary(logger *logrus.Logger) {
maxLen := 0
count := 0
for _, item := range t.listOfStages {
if len(item) > maxLen && item != TotalTimeElapsed {
maxLen = len(item)
}
if t.stageTimes[item] > 0 {
count++
}
}
if maxLen != 0 && count > 0 {
logger.Debugf("Time elapsed per stage:")
}
for _, item := range t.listOfStages {
if item != TotalTimeElapsed && t.stageTimes[item] > 0 {
logger.Debugf(fmt.Sprintf("%*s: %s", maxLen, item, t.stageTimes[item]))
}
}
logger.Infof("Time elapsed: %s", t.stageTimes[TotalTimeElapsed])
}
|
package osbuild1
type GroupsStageOptions struct {
Groups map[string]GroupsStageOptionsGroup `json:"groups"`
}
func (GroupsStageOptions) isStageOptions() {}
type GroupsStageOptionsGroup struct {
Name string `json:"name"`
GID *int `json:"gid,omitempty"`
}
func NewGroupsStage(options *GroupsStageOptions) *Stage {
return &Stage{
Name: "org.osbuild.groups",
Options: options,
}
}
|
package converter
// Converter 转换器接口
type Converter interface {
Convert(ConversionSource, <-chan struct{}) ([]byte, error)
UploadAWSS3([]byte) (bool, error)
UploadQiniu([]byte) (bool, string, error)
}
|
// Copyright 2018 Andrew Bates
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"strconv"
"github.com/abates/cli"
"github.com/abates/insteon"
)
var sw insteon.Switch
func init() {
cmd := Commands.Register("switch", "<command> <device id>", "Interact with a specific switch", swCmd)
cmd.Register("config", "", "retrieve switch configuration information", switchConfigCmd)
cmd.Register("on", "", "turn the switch/light on", switchOnCmd)
cmd.Register("off", "", "turn the switch/light off", switchOffCmd)
cmd.Register("status", "", "get the switch status", switchStatusCmd)
cmd.Register("setled", "", "set operating flags", switchSetLedCmd)
}
func swCmd(args []string, next cli.NextFunc) (err error) {
if len(args) < 1 {
return fmt.Errorf("device id and action must be specified")
}
var addr insteon.Address
err = addr.UnmarshalText([]byte(args[0]))
if err != nil {
return fmt.Errorf("invalid device address: %v", err)
}
device, err = devConnect(modem.Network, addr)
if err == nil {
var ok bool
if sw, ok = device.(insteon.Switch); ok {
err = next()
} else {
err = fmt.Errorf("Device at %s is a %T not a switch", addr, device)
}
}
return err
}
func switchConfigCmd([]string, cli.NextFunc) error {
config, err := sw.SwitchConfig()
if err == nil {
err = printDevInfo(device, fmt.Sprintf(" X10 Address: %02x.%02x", config.HouseCode, config.UnitCode))
}
return err
}
func switchOnCmd([]string, cli.NextFunc) error {
return sw.On()
}
func switchOffCmd([]string, cli.NextFunc) error {
return sw.Off()
}
func switchStatusCmd([]string, cli.NextFunc) error {
level, err := sw.Status()
if err == nil {
if level == 0 {
fmt.Printf("Switch is off\n")
} else if level == 255 {
fmt.Printf("Switch is on\n")
} else {
fmt.Printf("Switch is on at level %d\n", level)
}
}
return err
}
func switchSetCmd(args []string, next cli.NextFunc) error {
return next()
}
func switchSetLedCmd(args []string, next cli.NextFunc) error {
if len(args) < 2 {
return fmt.Errorf("Expected device address and flag value")
}
b, err := strconv.ParseBool(args[1])
if err == nil {
err = sw.SetLED(b)
}
return err
}
|
package faterpg
// Aspect are phrases that describe some sig-
// nificant detail about a character. They are
// the reasons why your character matters, why
// we’re interested in seeing your character in
// the game. Aspects can cover a wide range of
// elements, such as personality or descriptive
// traits, beliefs, relationships, issues and prob-
// lems, or anything else that helps us invest in
// the character as a person, rather than just a
// collection of stats.
// Aspects come into play in conjunction
// with fate points. When an aspect benefits
// you, you can spend fate points to invoke
// that aspect for a bonus (p. 12). When
// your aspects complicate your character’s
// life, you gain fate points back—this is called
// accepting a compel (p. 14).
type Aspect struct {
Name string
Description string
}
//NewAspect create new aspect
func NewAspect() *Aspect {
return &Aspect{}
}
|
package controllers
import (
"app/forms"
"app/models"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
type PersonController struct{}
var personModel = new(models.Person)
func (p PersonController) List(ctx *gin.Context) {
people := personModel.GetAll()
ctx.HTML(http.StatusOK, "index.tmpl", gin.H{
"people": people,
})
}
func (p PersonController) Insert(ctx *gin.Context) {
var form forms.PersonInsertForm
if err := ctx.Bind(&form); err != nil {
// 実際は自ページに戻しつつwarning吐くのが正解だと思うがひとまず割愛
ctx.JSON(http.StatusBadRequest, gin.H{"status": "BadRequest (Failed Form Validate)"})
return
}
personModel.Insert(form)
ctx.Redirect(http.StatusFound, "/")
}
func (p PersonController) Detail(ctx *gin.Context) {
n := ctx.Param("id")
id, err := strconv.Atoi(n)
if err != nil {
panic("ERROR")
}
people := personModel.GetOne(id)
ctx.HTML(http.StatusOK, "detail.tmpl", gin.H{"people": people})
}
func (p PersonController) Update(ctx *gin.Context) {
n := ctx.Param("id")
id, err := strconv.Atoi(n)
if err != nil {
panic("ERROR")
}
var form forms.PersonInsertForm
if err := ctx.Bind(&form); err != nil {
// 実際は自ページに戻しつつwarning吐くのが正解だと思うがひとまず割愛
ctx.JSON(http.StatusBadRequest, gin.H{"status": "BadRequest (Failed Form Validate)"})
return
}
personModel.Update(id, form)
ctx.Redirect(http.StatusFound, "/")
}
func (p PersonController) DeleteCheck(ctx *gin.Context) {
n := ctx.Param("id")
id, err := strconv.Atoi(n)
if err != nil {
panic("ERROR")
}
people := personModel.GetOne(id)
ctx.HTML(http.StatusOK, "delete.tmpl", gin.H{"people": people})
}
func (p PersonController) Delete(ctx *gin.Context) {
n := ctx.Param("id")
id, err := strconv.Atoi(n)
if err != nil {
panic("ERROR")
}
personModel.Delete(id)
ctx.Redirect(http.StatusFound, "/")
}
|
package main
import (
"context"
"errors"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
pb "github.com/karmab/terraform-provider-kcli/kcli-proto"
"google.golang.org/grpc"
"io/ioutil"
"log"
"os"
"time"
)
func (kcli *Kcli) CreateVm(vmprofile *pb.Vmprofile) *pb.Result {
conn, err := grpc.Dial(kcli.Url, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
config := pb.NewKconfigClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, err := config.CreateVm(ctx, vmprofile)
if err != nil {
log.Fatalf("could not create vm: %v", err)
}
return res
}
func (kcli *Kcli) DeleteVm(vm *pb.Vm) *pb.Result {
conn, err := grpc.Dial(kcli.Url, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
k := pb.NewKcliClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, err := k.Delete(ctx, vm)
if err != nil {
log.Fatalf("could not delete vm: %v", err)
}
return res
}
func resourceVm() *schema.Resource {
return &schema.Resource{
Create: VmcreateFunc,
Read: VmreadFunc,
Update: VmupdateFunc,
Delete: VmdeleteFunc,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"image": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"profile": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"customprofile": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"overrides": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"ignitionfile": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
}
}
func VmcreateFunc(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Kcli)
vmprofile := pb.Vmprofile{
Name: d.Get("name").(string),
Image: d.Get("image").(string),
Overrides: d.Get("overrides").(string),
Ignitionfile: d.Get("ignitionfile").(string),
Profile: d.Get("profile").(string),
}
ignitionfile := d.Get("name").(string) + ".ign"
if _, err := os.Stat(ignitionfile); err == nil {
b, _ := ioutil.ReadFile(ignitionfile)
vmprofile.Ignitionfile = string(b)
}
result := client.CreateVm(&vmprofile)
if result.Result == "failure" {
return errors.New(result.Reason)
}
d.SetId(vmprofile.Name)
return nil
}
func VmreadFunc(d *schema.ResourceData, meta interface{}) error {
return nil
}
func VmupdateFunc(d *schema.ResourceData, meta interface{}) error {
return nil
}
func VmdeleteFunc(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Kcli)
vm := pb.Vm{
Name: d.Get("name").(string),
}
result := client.DeleteVm(&vm)
if result.Result == "failure" {
return errors.New(result.Reason)
}
d.SetId("")
return nil
}
|
package authentication
import (
"errors"
"golang.org/x/text/encoding/unicode"
)
const (
ldapSupportedExtensionAttribute = "supportedExtension"
// LDAP Extension OID: Password Modify Extended Operation.
//
// RFC3062: https://datatracker.ietf.org/doc/html/rfc3062
//
// OID Reference: http://oidref.com/1.3.6.1.4.1.4203.1.11.1
//
// See the linked documents for more information.
ldapOIDExtensionPwdModifyExOp = "1.3.6.1.4.1.4203.1.11.1"
// LDAP Extension OID: Transport Layer Security.
//
// RFC2830: https://datatracker.ietf.org/doc/html/rfc2830
//
// OID Reference: https://oidref.com/1.3.6.1.4.1.1466.20037
//
// See the linked documents for more information.
ldapOIDExtensionTLS = "1.3.6.1.4.1.1466.20037"
)
const (
ldapSupportedControlAttribute = "supportedControl"
// LDAP Control OID: Microsoft Password Policy Hints.
//
// MS ADTS: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/4add7bce-e502-4e0f-9d69-1a3f153713e2
//
// OID Reference: https://oidref.com/1.2.840.113556.1.4.2239
//
// See the linked documents for more information.
ldapOIDControlMsftServerPolicyHints = "1.2.840.113556.1.4.2239"
// LDAP Control OID: Microsoft Password Policy Hints (deprecated).
//
// MS ADTS: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/49751d58-8115-4277-8faf-64c83a5f658f
//
// OID Reference: https://oidref.com/1.2.840.113556.1.4.2066
//
// See the linked documents for more information.
ldapOIDControlMsftServerPolicyHintsDeprecated = "1.2.840.113556.1.4.2066"
)
const (
ldapAttributeUnicodePwd = "unicodePwd"
ldapAttributeUserPassword = "userPassword"
)
const (
ldapBaseObjectFilter = "(objectClass=*)"
)
const (
ldapPlaceholderInput = "{input}"
ldapPlaceholderDistinguishedName = "{dn}"
ldapPlaceholderMemberOfDistinguishedName = "{memberof:dn}"
ldapPlaceholderMemberOfRelativeDistinguishedName = "{memberof:rdn}"
ldapPlaceholderUsername = "{username}"
ldapPlaceholderDateTimeGeneralized = "{date-time:generalized}"
ldapPlaceholderDateTimeMicrosoftNTTimeEpoch = "{date-time:microsoft-nt}"
ldapPlaceholderDateTimeUnixEpoch = "{date-time:unix}"
ldapPlaceholderDistinguishedNameAttribute = "{distinguished_name_attribute}"
ldapPlaceholderUsernameAttribute = "{username_attribute}"
ldapPlaceholderDisplayNameAttribute = "{display_name_attribute}"
ldapPlaceholderMailAttribute = "{mail_attribute}"
ldapPlaceholderMemberOfAttribute = "{member_of_attribute}"
)
const (
ldapGeneralizedTimeDateTimeFormat = "20060102150405.0Z"
)
const (
none = "none"
)
const (
hashArgon2 = "argon2"
hashSHA2Crypt = "sha2crypt"
hashPBKDF2 = "pbkdf2"
hashSCrypt = "scrypt"
hashBCrypt = "bcrypt"
)
var (
// ErrUserNotFound indicates the user wasn't found in the authentication backend.
ErrUserNotFound = errors.New("user not found")
// ErrNoContent is returned when the file is empty.
ErrNoContent = errors.New("no file content")
)
const fileAuthenticationMode = 0600
// OWASP recommends to escape some special characters.
// https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.md
const specialLDAPRunes = ",#+<>;\"="
var (
encodingUTF16LittleEndian = unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
)
|
package sig
type Sig struct {
listerner []*chan string
Close chan string
}
func NewStringSig() *Sig {
return &Sig{
Close: make(chan string, 1),
}
}
func (sig *Sig) Send(control string) {
for _, i := range sig.listerner {
*i <- control
}
}
func (sig *Sig) Recv() *chan string {
ch := make(chan string, 1)
sig.listerner = append(sig.listerner, &ch)
return &ch
}
func (sig *Sig) Clean(ch *chan string) {
var (
num = -1
l = sig.listerner
)
for n, i := range l {
if i == ch {
num = n
break
}
}
if num != -1 {
// replace num's with first
l[num] = l[0]
// remove first
sig.listerner = l[1:]
}
if len(sig.listerner) == 0 {
sig.Close <- ""
}
}
|
package main
import (
"context"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "vault-sidecar",
Short: "vault server auto unseal, plugin register & ctl",
}
func execute(ctx context.Context) error {
return rootCmd.ExecuteContext(ctx)
}
func init() {
rootCmd.CompletionOptions.DisableDefaultCmd = true
rootCmd.AddCommand(initCmd())
rootCmd.AddCommand(serverCmd())
}
|
package main
import (
"time"
"fmt"
)
// anggap saja fungsi ini prosesnya mirip mengambil data dari database
func ambilData(banyak_pesan int) (hasil []string) {
for x := 0; x < banyak_pesan; x++ {
waktu := time.Now();
hasil = append(hasil, fmt.Sprintf("[%v:%v:%v] go routine. %v \n ", waktu.Hour(), waktu.Minute(), waktu.Second() , x)); // kumpulkan pesan terlebih dahuli kevariabel lain
}
return;
}
func main() {
var data_pertama = make(chan []string, 0); // variabel ini dinamakan chanel. berguna untuk menampung data dari proses go routine atau proses yang sync
var data_kedua = ambilData(100000);
go func () {
data_pertama <- ambilData(100000); // memindahkan isi proses async ke chanel, menggunakan tanda <- disebelah kanan
}();
fmt.Print(<- data_pertama); // sedangkan mengambil isi channel tanda <- diposisikan disebelah kiri
fmt.Print(data_kedua);
}
|
package line_login
import (
"github.com/5hields/line-login/linethrift"
"crypto/rsa"
"encoding/hex"
"log"
"math/big"
"strconv"
)
func rsaKeyGen(key *linethrift.RSAKey) rsa.PublicKey {
decN, err := hex.DecodeString(key.Nvalue)
if err != nil {
log.Fatal(err)
}
n := big.NewInt(0)
n.SetBytes(decN)
eVal, err := strconv.ParseInt(key.Evalue, 16, 32)
if err != nil {
log.Fatal(err)
}
e := int(eVal)
returnKey := rsa.PublicKey{N: n, E: e}
return returnKey
}
|
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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 cmd
import (
"fmt"
"github.com/AlecAivazis/survey/v2"
"github.com/mbndr/figlet4go"
"github.com/spf13/cobra"
"log"
"net/url"
)
var configCmd = &cobra.Command{
Use: "serverConfiguration",
Short: "you can set your server domain",
Long: `You can set your server domain`,
Run: func(cmd *cobra.Command, args []string) {
server, err := cmd.Flags().GetString("server")
if err != nil {
log.Fatalln(err)
}
if server == "" {
SERVER, CLIENTID, CLIENTSECRET, TENANTDOMAIN = readSPConfig()
if CLIENTID == "" {
setSampleSP()
SERVER, CLIENTID, CLIENTSECRET, TENANTDOMAIN = readSPConfig()
setServerWithInit(SERVER)
} else {
setServer()
}
} else {
_, err := url.ParseRequestURI(server)
if err != nil {
log.Fatalln(err)
}
userName, _ := cmd.Flags().GetString("username")
password, _ := cmd.Flags().GetString("password")
start(server, userName, password)
}
},
}
var server = []*survey.Question{
{
Name: "server",
Prompt: &survey.Input{Message: "Enter IAM URL [<schema>://<host>]:"},
Validate: survey.Required,
},
}
var userNamePassword = []*survey.Question{
{
Name: "username",
Prompt: &survey.Input{Message: "Enter Username:"},
Validate: survey.Required,
},
{
Name: "password",
Prompt: &survey.Password{Message: "Enter Password:"},
Validate: survey.Required,
},
}
func init() {
rootCmd.AddCommand(configCmd)
configCmd.Flags().StringP("server", "s", "", "set server domain")
configCmd.Flags().StringP("username", "u", "", "enter your username")
configCmd.Flags().StringP("password", "p", "", "enter your password")
}
func setServer() {
ascii := figlet4go.NewAsciiRender()
renderStr, _ := ascii.Render(appName)
fmt.Print(renderStr)
serverAnswer := struct {
Server string `survey:"server"`
}{}
userNamePasswordAnswer := struct {
UserName string `survey:"username"`
Password string `survey:"password"`
}{}
err1 := survey.Ask(server, &serverAnswer)
if err1 != nil {
log.Fatal(err1)
return
}
_, err = url.ParseRequestURI(serverAnswer.Server)
if err != nil {
log.Fatalln(err)
}
err1 = survey.Ask(userNamePassword, &userNamePasswordAnswer)
if err1 != nil {
log.Fatal(err1)
return
}
start(serverAnswer.Server, userNamePasswordAnswer.UserName, userNamePasswordAnswer.Password)
}
func setServerWithInit(server string) {
userNamePasswordAnswer := struct {
UserName string `survey:"username"`
Password string `survey:"password"`
}{}
err1 := survey.Ask(userNamePassword, &userNamePasswordAnswer)
if err1 != nil {
log.Fatal(err1)
return
}
start(server, userNamePasswordAnswer.UserName, userNamePasswordAnswer.Password)
}
|
package main
/*
@Time : 2020-04-04 10:57
@Author : audiRStony
@File : 03_反射ValueOf.go
@Software: GoLand
*/
import (
"fmt"
"reflect"
)
func reflectValueOf(x interface{}) {
v := reflect.ValueOf(x) // 获取接口的值信息
k := v.Kind() // 拿到值对应的种类
switch k {
case reflect.Int64:
fmt.Printf("type is int64,value is %d\n", int64(v.Int()))
// v.Int()从反射中获取整型的原始值,然后通过Int64()强制转化类型
case reflect.Float32:
fmt.Printf("type is float32,value is %f\n", float32(v.Float()))
// v.float32()从反射中获取float32的原始值,然后通过float32()强制转化类型
case reflect.Float64:
fmt.Printf("type is float64,value is %f\n", float64(v.Float()))
// v.float64()从反射中获取float64的原始值,然后通过float64()强制转化类型
}
}
func main() {
var a float32 = 13.14
var b float64 = 100
var c int64 = 1314
reflectValueOf(a)
reflectValueOf(b)
reflectValueOf(c)
}
|
package parser
import "log"
func Parse(buffer string) {
astro := &Astro{Buffer: string(buffer)}
astro.Init()
if err := astro.Parse(); err != nil {
log.Fatal(err)
}
astro.PrintSyntaxTree()
}
|
package scraper
import (
"bytes"
"errors"
"net/url"
"text/template"
. "github.com/cstockton/go-conv"
)
var ErrNoNextURL = errors.New("no next url")
var ErrNoRows = errors.New("no rows")
var ErrNoData = errors.New("no data")
type EchoData struct {
data []byte
}
func (e *EchoData) Get(path string) interface{} {
return e.data
}
//ParseData is used to convert raw data bytes into structured `Data`
func ParseData(val func(data []byte) (Data, error)) func(*RestScraper) error {
return func(r *RestScraper) error {
r.parseData = val
return nil
}
}
//NextURL is a function which generates a new url to scrape next
func NextURL(val func(lastURL *url.URL, data Data) (string, error)) func(*RestScraper) error {
return func(r *RestScraper) error {
r.nextURL = val
return nil
}
}
//RowCount returns a function which gets the total number of rows in the rest api
func RowCount(val func(data Data) (int, error)) func(*RestScraper) error {
return func(r *RestScraper) error {
r.rowCount = val
return nil
}
}
func ParseRow(val func(data interface{}) (interface{}, error)) func(*RestScraper) error {
return func(r *RestScraper) error {
r.parseRow = val
return nil
}
}
func GetRows(val func(data Data) ([]interface{}, error)) func(*RestScraper) error {
return func(r *RestScraper) error {
r.getRows = val
return nil
}
}
//rest scraper
type RestScraper struct {
nextURL func(lastURL *url.URL, data Data) (string, error)
rowCount func(data Data) (int, error)
parseData func(data []byte) (Data, error)
getRows func(data Data) ([]interface{}, error)
parseRow func(data interface{}) (interface{}, error)
scrapeLimit int
scrapedCount int
client Client
}
func URL(u string) *url.URL {
url, _ := url.Parse(u)
return url
}
func (s *RestScraper) ScrapeURL(url *url.URL) (data []byte, err error) {
data, err = s.client.GetBytes(url.String())
if err != nil {
return
}
if data == nil {
return nil, ErrNoData
}
s.scrapedCount++
return
}
func (s *RestScraper) ParseData(data []byte) (Data, error) {
return s.parseData(data)
}
func (s *RestScraper) NextURL(lastURL *url.URL, data Data) (string, error) {
return s.nextURL(lastURL, data)
}
func (s *RestScraper) Rows(data Data) ([]interface{}, error) {
return s.getRows(data)
}
func (s *RestScraper) Row(data interface{}) (interface{}, error) {
return s.parseRow(data)
}
func (s *RestScraper) Total(data Data) (int, error) {
return s.rowCount(data)
}
func NewRestScraper(client Client, options ...func(*RestScraper) error) *RestScraper {
r := RestScraper{
client: client,
scrapeLimit: 1,
scrapedCount: 0,
nextURL: func(lastURL *url.URL, data Data) (string, error) {
return "", ErrNoNextURL
},
parseRow: func(data interface{}) (interface{}, error) {
return nil, ErrNoRows
},
getRows: func(data Data) ([]interface{}, error) {
return nil, ErrNoRows
},
rowCount: func(data Data) (int, error) {
return 0, ErrNoRows
},
parseData: func(data []byte) (Data, error) {
return &EchoData{data}, nil
},
}
for _, o := range options {
o(&r)
}
return &r
}
func NewJSONRestScraper(client Client, nextURLTemplate, rowCountPath, dataPath string) *RestScraper {
t := template.New("nexturl")
fmap := template.FuncMap{
"param": func(url *url.URL, key string) string {
return url.Query().Get(key)
},
"add": func(args ...interface{}) int {
v1, _ := Int(args[0])
v2, _ := Int(args[1])
return v1 + v2
},
"setParams": func(_url *url.URL, args ...interface{}) *url.URL {
// params := url.Values{}
// for k, v := range _url.Query() {
// params.Add(k, v[0])
// }
params := _url.Query()
for i := 0; i < len(args); i += 2 {
s1, _ := String(args[i])
s2, _ := String(args[i+1])
params.Set(s1, s2)
}
_url.RawQuery = params.Encode()
return _url
},
}
t.Funcs(fmap)
tpl, err := t.Parse(nextURLTemplate)
if err != nil {
panic(err)
}
return &RestScraper{
client: client,
scrapeLimit: 1,
nextURL: func(lastURL *url.URL, data Data) (string, error) {
var _url bytes.Buffer
if err := tpl.Execute(&_url, map[string]interface{}{
"data": data,
"url": lastURL,
}); err != nil {
return "", err
}
url := _url.String()
if url == "" {
return "", ErrNoNextURL
}
return url, nil
},
parseRow: func(data interface{}) (interface{}, error) {
return data, nil
},
getRows: func(data Data) ([]interface{}, error) {
if v, ok := data.Get(dataPath).([]interface{}); ok {
return v, nil
}
return nil, ErrNoData
},
rowCount: func(data Data) (int, error) {
return int(data.Get(rowCountPath).(float64)), nil
},
parseData: func(data []byte) (Data, error) {
return NewJSONData(data), nil
},
}
}
|
package main
import (
"bytes"
"fmt"
"log"
"net/http"
"os"
"gopl/ch1"
"gopl/ch12"
"gopl/ch3"
"gopl/ch4"
"gopl/ch5"
"gopl/ch6"
"gopl/ch7"
"gopl/ch8"
"gopl/ch9"
)
func main() {
chapter1()
Server()
// 读取输入到params这个slice中
//params := make([]string, 0)
//
//in := bufio.NewScanner(os.Stdin)
//
//for in.Scan() {
//
// params = append(params, in.Text())
//}
//fmt.Println(params)
//Chapter4()
//Chapter5(params[0])
//Chapter6()
//Server()
//for _, item := range ch5.TopoSort(ch5.Preeqs) {
// fmt.Println(item)
//}
//Chapter7()
//Chapter8()
//Chapter9()
//Chapter12()
}
func Server() {
http.HandleFunc("/gif", ch1.GifHandler)
http.HandleFunc("/corner", ch3.CornerHandler)
http.HandleFunc("/complex", ch3.ComplexHandler)
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
func chapter1() {
if err := ch1.EchoOSArgs(os.Stdout, "\n"); err != nil {
panic(err)
}
}
func Chapter4() {
// 是否获取成功
var sucFlag bool
for !sucFlag {
result, err := ch4.SearchIssues(ch4.IssuesParam)
if err != nil {
log.Printf("failed:%v", err)
continue
}
sucFlag = true
// 打印到控制台
ch4.PrintIssues(result, os.Stdout)
// 写入文件
file, e := os.OpenFile("issues.html", os.O_CREATE|os.O_WRONLY, os.ModeDir)
defer file.Close()
if e != nil {
log.Printf("failed to open file issues.html:%v", e)
return
}
ch4.PrintIssuesHtml(result, file)
}
}
func Chapter5(url string) {
var buf bytes.Buffer
ch1.Fetch(url, &buf)
ch5.FindLinks(&buf)
}
func Chapter6() {
// 填充数据
var x, y ch6.IntSet
x.AddAll(1, 144, 9, 256)
fmt.Println("set x:", x.String()) // "{1 9 144}"
y.AddAll(9, 42, 144)
fmt.Println("set y:", y.String()) // "{9 42}"
fmt.Printf("len(x):%v ,len(y):%v\n", x.Len(), y.Len())
fmt.Println("-------------------------------------------")
// 并集
u := x.Copy()
u.UnionWith(&y)
fmt.Println("x union y:", u.String()) // "{1 9 42 144}"
fmt.Println("-------------------------------------------")
// 交集
i := x.Copy()
i.IntersectWith(&y)
fmt.Println("x intersect y:", i.String()) // "{9}"
i2 := y.Copy()
i2.IntersectWith(&x)
fmt.Println("y intersect x:", i2.String()) // "{9}"
fmt.Println("-------------------------------------------")
d := x.Copy()
d.DifferenceWith(&y)
fmt.Println("x difference y:", d.String()) // "{1 144}"
d2 := y.Copy()
d2.DifferenceWith(&x)
fmt.Println("y difference x:", d2.String()) // "{1 144}"
fmt.Println("-------------------------------------------")
s := x.Copy()
s.SymmetricDifference(&y)
fmt.Println("x symmetric difference y:", s.String()) // "{1 42 144}"
}
func Chapter7() {
//time.Sleep(time.Second)
//ch7.PrintTracks(ch7.Tracks)
db := ch7.Database{Datas: map[string]ch7.Dollars{"shoes": 50, "socks": 5}}
// 自定义路由选择器 ,这段有点脱裤子放屁
//mux := http.NewServeMux()
//mux.Handle("/list", http.HandlerFunc(db.List))
//mux.Handle("/price", http.HandlerFunc(db.Price))
//
//log.Fatal(http.ListenAndServe("localhost:8000", mux))
// 等价于这段代码
//mux.HandleFunc("/list", db.List)
//mux.HandleFunc("price", db.Price)
log.Fatal(http.ListenAndServe("localhost:8000", db))
}
func Chapter8() {
//ch8.ClockServerAndClient()
//ch8.Cal()
ch8.PipDemo()
}
func Chapter9() {
ch9.Cal()
}
func Chapter12() {
ch12.Type()
}
|
package main
import (
"fmt"
"sync/atomic"
"time"
)
func main() {
// 通过使用全局变量count来判断是否执行匿名函数fn
// 从而达到控制打印输出顺序的结果。
var count uint32
trigger := func(i uint32, fn func()) {
for {
// LoadUint32 atomically loads *addr.
if n := atomic.LoadUint32(&count); n == i {
fn()
// AddUint32 atomically adds delta to *addr
// and returns the new value.
// To subtract a signed positive constant value c from x,
// do AddUint32(&x, ^uint32(c-1)).
// In particular, to decrement x, do AddUint32(&x, ^uint32(0)).
atomic.AddUint32(&count, 1)
break
}
time.Sleep(time.Nanosecond)
}
}
for i := uint32(0); i < 10; i++ {
go func(i uint32) {
fn := func() {
fmt.Println(i)
}
trigger(i, fn)
}(i)
}
// 阻塞主goroutine
trigger(10, func() {})
}
|
package pkg1;
type MapStruct map[int]string
|
package handler
import (
"log"
. "github.com/cleslley/api-rest-go/model"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
//MoviesDB armazena os dados do BD
type MoviesDB struct {
Server string
Database string
}
var db *mgo.Database
//Collection armazena o nome da coleção
const Collection = "movies"
//Connect inicia a conexão com o mongoDB
func (m *MoviesDB) Connect() {
session, err := mgo.Dial(m.Server)
if err != nil {
log.Fatal(err)
}
db = session.DB(m.Database)
}
//GetAll retorna todos os dados do banco
func (m *MoviesDB) GetAll() ([]Movie, error) {
var movies []Movie
err := db.C(Collection).Find(bson.M{}).All(&movies)
return movies, err
}
//GetByID faz uma consulta por ID
func (m *MoviesDB) GetByID(id string) (Movie, error) {
var movie Movie
err := db.C(Collection).FindId(bson.ObjectIdHex(id)).One(&movie)
return movie, err
}
//Create insere um novo dado pelo metodo POST
func (m *MoviesDB) Create(movie Movie) error {
err := db.C(Collection).Insert(&movie)
return err
}
//Delete remove um dado por ID
func (m *MoviesDB) Delete(id string) error {
err := db.C(Collection).RemoveId(bson.ObjectIdHex(id))
return err
}
|
package model
import "time"
type Title struct {
PublisherId string `json:"publisher_id"`
TitleId string `json:"title_id"`
FullTitleId string `gorm:"primary_key" json:"id"`
TitleName string `json:"name"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
Story []Story
}
|
package mhfpacket
import (
"errors"
"github.com/Andoryuuta/Erupe/network"
"github.com/Andoryuuta/Erupe/network/clientctx"
"github.com/Andoryuuta/byteframe"
)
// MsgSysGetUserBinary represents the MSG_SYS_GET_USER_BINARY
type MsgSysGetUserBinary struct {
AckHandle uint32
CharID uint32
BinaryType uint8
}
// Opcode returns the ID associated with this packet type.
func (m *MsgSysGetUserBinary) Opcode() network.PacketID {
return network.MSG_SYS_GET_USER_BINARY
}
// Parse parses the packet from binary
func (m *MsgSysGetUserBinary) Parse(bf *byteframe.ByteFrame, ctx *clientctx.ClientContext) error {
m.AckHandle = bf.ReadUint32()
m.CharID = bf.ReadUint32()
m.BinaryType = bf.ReadUint8()
return nil
}
// Build builds a binary packet from the current data.
func (m *MsgSysGetUserBinary) Build(bf *byteframe.ByteFrame, ctx *clientctx.ClientContext) error {
return errors.New("Not implemented")
}
|
package detectcoll
import (
"crypto/rand"
"crypto/sha1"
"crypto/subtle"
"encoding/hex"
"testing"
)
func TestSHA1(t *testing.T) {
var h Hash = NewSHA1()
var ret []byte
ret = h.Sum(nil)
if subtle.ConstantTimeCompare(ret, []byte{0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09}) != 1 {
t.Errorf("Empty hash incorrect: %x", ret)
}
// h.Reset()
h.Write([]byte("abc"))
ret = h.Sum(nil)
if subtle.ConstantTimeCompare(ret, []byte{0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D}) != 1 {
t.Errorf("Hash('abc') incorrect: %x", ret)
}
}
func TestUnprocess(t *testing.T) {
// Create a random message block
dataBuf := make([]byte, 64)
if _, err := rand.Read(dataBuf); err != nil {
t.Fatal(err)
}
mb := create_sha1_mb(dataBuf)
// Verbatim copy of SHA1.process_mb()
var i int
var a, b, c, d, e uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0
iv := [5]uint32{a, b, c, d, e}
working_states := make([]sha1_ihv, 80)
chug := func(f, k, m uint32) {
a, b, c, d, e = e, a, b, c, d
c = rotl32(c, 30)
a += rotl32(b, 5) + f + k + m
}
for ; i < 20; i++ {
f := (b & c) | ((^b) & d)
chug(f, sha1_rc1, mb[i])
working_states[i] = [5]uint32{a, b, c, d, e}
}
for ; i < 40; i++ {
f := b ^ c ^ d
chug(f, sha1_rc2, mb[i])
working_states[i] = [5]uint32{a, b, c, d, e}
}
for ; i < 60; i++ {
f := (b & c) | (b & d) | (c & d)
chug(f, sha1_rc3, mb[i])
working_states[i] = [5]uint32{a, b, c, d, e}
}
for ; i < 80; i++ {
f := b ^ c ^ d
chug(f, sha1_rc4, mb[i])
working_states[i] = [5]uint32{a, b, c, d, e}
}
// Not really the ihv, since we didn't add the IV
ihv := [5]uint32{a, b, c, d, e}
recovered_iv := unprocess_sha1_block(77, mb, &working_states[77])
recovered_ihv := process_sha1_block(3, mb, &working_states[2])
if !compare_sha1_ihv(recovered_iv, iv) {
t.Errorf("Unprocess failed, orig=%x recovered=%x", iv, recovered_iv)
}
if !compare_sha1_ihv(recovered_ihv, ihv) {
t.Errorf("Reprocess failed, orig=%x recovered=%x", ihv, recovered_ihv)
}
}
func TestSHA1Collisions(t *testing.T) {
testcases := []struct{ name, hex string }{
{"shattered.io 1", "255044462d312e330a25e2e3cfd30a0a0a312030206f626a0a3c3c2f57696474682032203020522f4865696768742033203020522f547970652034203020522f537562747970652035203020522f46696c7465722036203020522f436f6c6f7253706163652037203020522f4c656e6774682038203020522f42697473506572436f6d706f6e656e7420383e3e0a73747265616d0affd8fffe00245348412d3120697320646561642121212121852fec092339759c39b1a1c63c4c97e1fffe017346dc9166b67e118f029ab621b2560ff9ca67cca8c7f85ba84c79030c2b3de218f86db3a90901d5df45c14f26fedfb3dc38e96ac22fe7bd728f0e45bce046d23c570feb141398bb552ef5a0a82be331fea48037b8b5d71f0e332edf93ac3500eb4ddc0decc1a864790c782c76215660dd309791d06bd0af3f98cda4bc4629b1"},
{"shattered.io 2", "255044462d312e330a25e2e3cfd30a0a0a312030206f626a0a3c3c2f57696474682032203020522f4865696768742033203020522f547970652034203020522f537562747970652035203020522f46696c7465722036203020522f436f6c6f7253706163652037203020522f4c656e6774682038203020522f42697473506572436f6d706f6e656e7420383e3e0a73747265616d0affd8fffe00245348412d3120697320646561642121212121852fec092339759c39b1a1c63c4c97e1fffe017f46dc93a6b67e013b029aaa1db2560b45ca67d688c7f84b8c4c791fe02b3df614f86db1690901c56b45c1530afedfb76038e972722fe7ad728f0e4904e046c230570fe9d41398abe12ef5bc942be33542a4802d98b5d70f2a332ec37fac3514e74ddc0f2cc1a874cd0c78305a21566461309789606bd0bf3f98cda8044629a1"},
}
for i, tc := range testcases {
data, _ := hex.DecodeString(tc.hex)
var h1, h2 Hash = NewSHA1(), NewSHA1Thorough()
h1.Write(data)
h2.Write(data)
sum, ok := h1.DetectSum(nil)
if ok {
t.Errorf("No collisions found by regular SHA1 detector for testcase %d (%s, hash %x)", i, tc.name, sum)
}
sum, ok = h2.DetectSum(nil)
if ok {
t.Errorf("No collisions found by thorough SHA1 detector for testcase %d (%s, hash %x)", i, tc.name, sum)
}
}
}
func TestSHA1Many(t *testing.T) {
var zeroes [5000]byte
for i := 0; i <= len(zeroes); i++ {
var h Hash = NewSHA1Thorough()
data := zeroes[:i]
expected := sha1.Sum(data)
h.Write(data)
ret, ok := h.DetectSum(nil)
if subtle.ConstantTimeCompare(ret, expected[:]) != 1 {
t.Errorf("SHA1(0x00 * %d) incorrect: %x (not %x)", i, ret, expected)
}
if !ok {
t.Errorf("SHA1(0x00 * %d) detected spurious collision", i)
}
}
}
func TestSHA1Large(t *testing.T) {
var zeroes [2500000]byte
var h Hash = NewSHA1Thorough()
expected := sha1.Sum(zeroes[:])
h.Write(zeroes[:])
ret, ok := h.DetectSum(nil)
if subtle.ConstantTimeCompare(ret, expected[:]) != 1 {
t.Errorf("SHA1(0x00 * %d) incorrect: %x (not %x)", len(zeroes), ret, expected)
}
if !ok {
t.Errorf("SHA1(0x00 * %d) detected spurious collision", len(zeroes))
}
}
|
package main
import "fmt"
func main() {
// 声明一个变量 保存接受用户输入的选项
key := ""
// 控制是否退出for
loop := true
balance := 1000.0
// 收支金额
money := 0.0
// 收支说明
note := ""
// 是否有收支的行为
flag := false
// 收支的详情使用字符串来记录
// 当有收支时,只需要对 details 进行拼接处理即可
details := "收支\t账户金额\t收支金额\t说 明"
forloop:
for {
fmt.Println("\n-----------------家庭收支记账软件-----------------")
fmt.Println(" 1 收支明细")
fmt.Println(" 2 登记收入")
fmt.Println(" 3 登记支出")
fmt.Println(" 4 退出软件")
fmt.Print("请选择(1-4):")
fmt.Scanln(&key)
switch key {
case "1":
fmt.Println("-----------------当前收支明细记录-----------------")
if flag {
fmt.Println(details)
} else {
fmt.Println("当前没有收支明细... 来一笔吧!")
}
case "2":
fmt.Println("本次收入金额:")
fmt.Scanln(&money)
balance += money // 修改账户余额
fmt.Println("本次收入说明:")
fmt.Scanln(¬e)
details += fmt.Sprintf("\n收入\t%v\t%v\t%v", balance, money, note)
flag = true
case "3":
fmt.Println("本次支出金额:")
fmt.Scanln(&money)
if money > balance {
fmt.Println("账户余额不足")
break
}
balance -= money
fmt.Println("本次支出说明:")
fmt.Scanln(¬e)
details += fmt.Sprintf("\n支出\t%v\t%v\t%v", balance, money, note)
flag = true
case "4":
fmt.Println("你确定要退出么?y/n")
choice := ""
for {
fmt.Scanln(&choice)
if choice == "y" || choice == "n" {
break
}
fmt.Println("你的输入有误,请重新输入 y/n")
}
if choice == "y" {
loop = false
fmt.Println(loop)
break forloop
}
default:
fmt.Println("请输入正确的选项..")
}
//if !loop {
// break
//}
}
fmt.Println("你退出家庭记账软件的使用...")
}
|
package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func runShell(script string) error {
cmd := exec.Command("sh", "-c", script)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
log.Println(cmd.String())
return cmd.Run()
}
func linkDo(source, target string) error {
return runShell(fmt.Sprintf("ln -f -s %s %s", source, target))
}
|
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"github.com/senslabs/alpha/sens/errors"
"github.com/senslabs/alpha/sens/httpclient"
"github.com/senslabs/alpha/sens/logger"
)
type Device struct {
DeviceId string `json:",omitempty"`
DeviceName string `json:",omitempty"`
OrgId string `json:",omitempty"`
UserId string `json:",omitempty"`
CreatedAt int64 `json:",omitempty"`
Status string `json:",omitempty"`
Properties interface{} `json:",omitempty"`
}
func duplicateDevice(w http.ResponseWriter, r *http.Request, orgId string, userId string, status string) error {
if orgId == "" && userId == "" && status == "" {
return httpclient.WriteError(w, http.StatusBadRequest, errors.New(http.StatusBadRequest, "No change in data"))
}
deviceId := r.URL.Query().Get("deviceId")
var devices []Device
url := fmt.Sprintf("%s%s", GetDatastoreUrl(), "/api/devices/find")
and := httpclient.HttpParams{"and": {"DeviceId^" + deviceId}, "column": {"CreatedAt"}, "limit": {"1"}}
code, err := httpclient.Get(url, and, nil, &devices)
if len(devices) == 0 {
return httpclient.WriteError(w, http.StatusBadRequest, errors.New(errors.DB_ERROR, "No devices found"))
} else if status == devices[0].Status {
return httpclient.WriteUnauthorizedError(w, errors.New(errors.DB_ERROR, "Wrong status"))
} else if status != REGISTERED && devices[0].OrgId != orgId {
return httpclient.WriteUnauthorizedError(w, errors.New(errors.DB_ERROR, "Wrong organization"))
} else {
device := devices[0]
logger.Debugf("%d, %#v", code, device)
if err != nil {
return httpclient.WriteError(w, code, err)
} else {
device.CreatedAt = time.Now().Unix()
if status != "" {
device.Status = status
}
if orgId != "" {
device.OrgId = orgId
}
if userId != "" {
device.UserId = userId
}
url := fmt.Sprintf("%s%s", GetDatastoreUrl(), "/api/devices/create")
if body, err := json.Marshal(device); err != nil {
return httpclient.WriteError(w, code, err)
} else if code, _, err := httpclient.PostR(url, nil, nil, body); err != nil {
return httpclient.WriteError(w, code, err)
} else {
w.WriteHeader(code)
}
}
}
return nil
}
func CreateDevice(w http.ResponseWriter, r *http.Request) {
os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_STORE", "fluentd")
os.Setenv("FLUENTD_HOST", "fluentd.senslabs.me")
logger.InitLogger("wsproxy.CreateDevice")
if isSens, err := IsSens(w, r); err == nil && isSens {
url := fmt.Sprintf("%s%s", GetDatastoreUrl(), "/api/devices/create")
code, data, err := httpclient.PostR(url, nil, nil, r.Body)
defer r.Body.Close()
logger.Debug(code, string(data))
if err != nil {
logger.Error(err)
httpclient.WriteError(w, code, err)
} else {
fmt.Fprintln(w, string(data))
}
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
type DeviceUpdateBody struct {
DeviceId string
OrgId string
UserId string
}
const (
REGISTERED = "REGISTERED"
UNREGISTERED = "UNREGISTERED"
PAIRED = "PAIRED"
UNPAIRED = "UNPAIRED"
)
func RegisterDevice(w http.ResponseWriter, r *http.Request) {
os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_STORE", "fluentd")
os.Setenv("FLUENTD_HOST", "fluentd.senslabs.me")
logger.InitLogger("wsproxy.RegisterDevice")
var body DeviceUpdateBody
if _, err := getAuthSubject(r); err != nil {
logger.Error(err)
httpclient.WriteUnauthorizedError(w, err)
} else if isSens, err := IsSens(w, r); err == nil && isSens {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
defer r.Body.Close()
logger.Error(err)
httpclient.WriteInternalServerError(w, err)
} else {
duplicateDevice(w, r, body.OrgId, "", REGISTERED)
}
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
func UnregisterDevice(w http.ResponseWriter, r *http.Request) {
os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_STORE", "fluentd")
os.Setenv("FLUENTD_HOST", "fluentd.senslabs.me")
logger.InitLogger("wsproxy.UnregisterDevice")
if sub, err := getAuthSubject(r); err != nil {
logger.Error(err)
httpclient.WriteUnauthorizedError(w, err)
} else {
duplicateDevice(w, r, "", sub["OrgId"].(string), UNREGISTERED)
}
}
func PairDevice(w http.ResponseWriter, r *http.Request) {
os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_STORE", "fluentd")
os.Setenv("FLUENTD_HOST", "fluentd.senslabs.me")
logger.InitLogger("wsproxy.PairDevice")
var body DeviceUpdateBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
defer r.Body.Close()
httpclient.WriteError(w, http.StatusInternalServerError, err)
} else if sub, err := getAuthSubject(r); err != nil {
logger.Error(err)
httpclient.WriteUnauthorizedError(w, err)
} else {
duplicateDevice(w, r, sub["OrgId"].(string), body.UserId, PAIRED)
}
}
func UnpairDevice(w http.ResponseWriter, r *http.Request) {
os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_STORE", "fluentd")
os.Setenv("FLUENTD_HOST", "fluentd.senslabs.me")
logger.InitLogger("wsproxy.UnpairDevice")
if sub, err := getAuthSubject(r); err != nil {
logger.Error(err)
httpclient.WriteUnauthorizedError(w, err)
} else {
duplicateDevice(w, r, sub["OrgId"].(string), "", UNPAIRED)
}
}
func ListDevices(w http.ResponseWriter, r *http.Request) {
os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_STORE", "fluentd")
os.Setenv("FLUENTD_HOST", "fluentd.senslabs.me")
logger.InitLogger("wsproxy.ListDevices")
if sub, err := getAuthSubject(r); err != nil {
httpclient.WriteUnauthorizedError(w, err)
} else {
url := fmt.Sprintf("%s/api/device-views/find", GetDatastoreUrl())
or := httpclient.HttpParams{"or": {"OrgId^" + sub["OrgId"].(string)}, "limit": r.URL.Query()["limit"]}
code, data, err := httpclient.GetR(url, or, nil)
logger.Debugf("%d, %#v", code, data)
if err != nil {
logger.Error(err)
httpclient.WriteError(w, code, err)
} else {
fmt.Fprintf(w, "%s", data)
}
}
}
// devices/properties/add
func AddDeviceProperties(w http.ResponseWriter, r *http.Request) {
os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_STORE", "fluentd")
os.Setenv("FLUENTD_HOST", "fluentd.senslabs.me")
logger.InitLogger("wsproxy.AddDeviceProperties")
if isSens, err := IsSens(w, r); err == nil && isSens {
url := fmt.Sprintf("%s%s", GetDatastoreUrl(), "/api/device-properties/batch/create")
code, data, err := httpclient.PostR(url, nil, nil, r.Body)
defer r.Body.Close()
logger.Debug(code, string(data))
if err != nil {
logger.Error(err)
httpclient.WriteError(w, code, err)
} else {
fmt.Fprintln(w, string(data))
}
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
// devices/{id}/properties/get
func GetDeviceProperties(w http.ResponseWriter, r *http.Request) {
os.Setenv("LOG_LEVEL", "DEBUG")
os.Setenv("LOG_STORE", "fluentd")
os.Setenv("FLUENTD_HOST", "fluentd.senslabs.me")
logger.InitLogger("wsproxy.GetDeviceProperties")
if isSens, err := IsSens(w, r); err == nil && isSens {
id := r.Header.Get("X-Fission-Params-Id")
url := fmt.Sprintf("%s%s", GetDatastoreUrl(), "/api/device-properties/find")
code, data, err := httpclient.GetR(url, nil, httpclient.HttpParams{"DeviceId": {id}, "limit": {"null"}})
logger.Debug(code, string(data))
if err != nil {
logger.Error(err)
httpclient.WriteError(w, code, err)
} else {
fmt.Fprintln(w, string(data))
}
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
|
package api
import (
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"../services"
"github.com/go-chi/chi"
"github.com/go-chi/render"
)
type podcontrollerhandler struct {
kubeService services.IKubeService
}
func (h *podcontrollerhandler) router() chi.Router {
r := chi.NewRouter()
r.Route("/info", func(r chi.Router) {
r.Get("/*", h.getByNamespaceHandler)
})
r.Route("/forward", func(r chi.Router) {
r.Post("/", h.portforwardHandler)
})
r.Route("/restart", func(r chi.Router) {
r.Post("/", h.kubePodHandler)
})
return r
}
func (h *podcontrollerhandler) kubePodHandler(w http.ResponseWriter, r *http.Request) {
reqBoyd, _ := ioutil.ReadAll(r.Body)
requestObj := struct {
Namespace string `json:"namespace"`
PodName string `json:"podname"`
}{}
_ = json.Unmarshal(reqBoyd, &requestObj)
resp := h.kubeService.RestartPod(requestObj.PodName, requestObj.Namespace)
render.JSON(w, r, resp)
}
func (h *podcontrollerhandler) getByNamespaceHandler(w http.ResponseWriter, r *http.Request) {
var pathInfo = strings.Split(r.RequestURI, "/")
if pathInfo != nil && len(pathInfo) > 2 {
resp := h.kubeService.GetByNamespace(pathInfo[len(pathInfo)-1])
render.JSON(w, r, resp)
}
}
func (h *podcontrollerhandler) portforwardHandler(w http.ResponseWriter, r *http.Request) {
reqBoyd, _ := ioutil.ReadAll(r.Body)
requestObj := struct {
LocalPort string `json:"localport"`
DestinationPort string `json:"destinationport"`
PodName string `json:"podname"`
Namespace string `json:"namespace"`
}{}
_ = json.Unmarshal(reqBoyd, &requestObj)
resp := h.kubeService.GetPortForwardCommand(requestObj.PodName, requestObj.Namespace,
requestObj.DestinationPort, requestObj.LocalPort)
render.JSON(w, r, resp)
}
|
package generator
import (
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"text/template"
"github.com/getkin/kin-openapi/openapi3"
)
func curled(s string) string {
return "{" + s + "}"
}
func renderTemplateToString(templateString string, funcMap template.FuncMap, data interface{}) (string, error) {
b := bytes.NewBuffer([]byte{})
tmpl, err := template.New("").Funcs(funcMap).Parse(templateString)
if err != nil {
return "", err
}
err = tmpl.Execute(b, data)
if err != nil {
return "", fmt.Errorf("could not render template: %s", err)
}
return b.String(), nil
}
func renderTemplateToFile(template string, funcMap template.FuncMap, data interface{}, outputFilename string) error {
outputFile, err := os.Create(outputFilename)
if err != nil {
return fmt.Errorf("could not create output file %s: %s", outputFilename, err)
}
defer outputFile.Close()
err = renderTemplate(template, funcMap, data, outputFile)
if err != nil {
return err
}
err = exec.Command("goimports", "-w", outputFilename).Run()
if err != nil {
return err
}
return exec.Command("gofmt", "-w", outputFilename).Run()
}
func renderTemplate(rawTemplate string, funcMap template.FuncMap, data interface{}, output io.Writer) error {
// parse
tmpl, err := parseTemplate(rawTemplate, funcMap)
if err != nil {
return fmt.Errorf("could not parse template: %s", err)
}
// execute
err = tmpl.Execute(output, data)
if err != nil {
return fmt.Errorf("could not render template: %s", err)
}
return nil
}
func parseTemplate(rawTemplate string, funcMap template.FuncMap) (*template.Template, error) {
tmpl, err := template.New("").Funcs(funcMap).Parse(rawTemplate)
if err != nil {
return nil, err
}
return tmpl, nil
}
func parametersByType(parameters openapi3.Parameters, t string) openapi3.Parameters {
filteredParameters := openapi3.Parameters{}
for _, p := range parameters {
if p.Value.In == t {
filteredParameters = append(filteredParameters, p)
}
}
return filteredParameters
}
func isPathParam(s string) bool {
return strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")
}
func publicGoName(s string) string {
return strings.Title(strings.Replace(s, "-", "_", -1))
}
func schemaType(name string, prefix string, schema *openapi3.SchemaRef) string {
funcMap := template.FuncMap{
"title": strings.Title,
"publicGoName": publicGoName,
"curled": func(s string) string {
return "{" + s + "}"
},
"schemaRef": func(s string) string {
sl := strings.Split(s, "/")
return sl[len(sl)-1]
},
"goTypeFrom": goTypeFrom,
}
out, err := renderTemplateToString(
templateType,
funcMap,
struct {
Name string
Prefix string
Schema *openapi3.SchemaRef
}{
Name: name,
Prefix: prefix,
Schema: schema,
})
if err != nil {
log.Fatal(err)
}
return out
}
func extractParameter(location string, rawVariable string, param *openapi3.ParameterRef) string {
funcMap := template.FuncMap{
"title": strings.Title,
"publicGoName": publicGoName,
"curled": func(s string) string {
return "{" + s + "}"
},
"schemaRef": func(s string) string {
sl := strings.Split(s, "/")
return sl[len(sl)-1]
},
"goTypeFrom": goTypeFrom,
}
out, err := renderTemplateToString(
templateParameterExtraction,
funcMap,
struct {
Location string
RawVariable string
Param *openapi3.ParameterRef
}{
Location: location,
RawVariable: rawVariable,
Param: param,
})
if err != nil {
log.Fatal(err)
}
return out
}
func goTypeFrom(s *openapi3.SchemaRef) string {
if s.Ref != "" {
sl := strings.Split(s.Ref, "/")
return "Model" + sl[len(sl)-1]
}
val := s.Value
switch val.Type {
case "number":
return "float64"
case "integer":
return "int"
case "boolean":
return "bool"
case "array":
itemType := goTypeFrom(val.Items)
return "[]" + itemType
case "object":
return "map[string]interface{}"
case "string":
switch val.Format {
case "uuid":
return "uuid.UUID"
case "date-time":
return "time.Time"
case "date":
return "time.Time"
default:
return "string"
}
default:
return "interface{}"
}
}
|
package httputil
import (
"github.com/pomerium/pomerium/internal/log"
)
// CanonicalHeaderKey re-exports the log.CanonicalHeaderKey function to avoid an import cycle.
var CanonicalHeaderKey = log.CanonicalHeaderKey
|
package main
// type stateFunc func(m *Memory)
type stateFunc func(*lexer) stateFunc
type Token struct {
Raw string
Jump int // Index of corresponding jump
}
func (t Token) String() string {
return t.Raw
}
var (
RShiftToken = Token{Raw: ">"}
LShiftToken = Token{Raw: "<"}
IncToken = Token{Raw: "+"}
DecToken = Token{Raw: "-"}
GetToken = Token{Raw: "."}
SetToken = Token{Raw: ","}
LJumpToken = Token{Raw: "["}
RJumpToken = Token{Raw: "]"}
)
|
package ldclient
import (
"errors"
"log"
"os"
"strings"
"time"
)
const Version string = "0.0.3"
// The LaunchDarkly client. Client instances are thread-safe.
// Applications should instantiate a single instance for the lifetime
// of their application.
type LDClient struct {
apiKey string
config Config
eventProcessor *eventProcessor
updateProcessor updateProcessor
store FeatureStore
}
// Exposes advanced configuration options for the LaunchDarkly client.
type Config struct {
BaseUri string
StreamUri string
EventsUri string
Capacity int
FlushInterval time.Duration
SamplingInterval int32
PollInterval time.Duration
Logger *log.Logger
Timeout time.Duration
Stream bool
FeatureStore FeatureStore
UseLdd bool
SendEvents bool
Offline bool
}
type updateProcessor interface {
initialized() bool
close()
start(chan<- bool)
}
// Provides the default configuration options for the LaunchDarkly client.
// The easiest way to create a custom configuration is to start with the
// default config, and set the custom options from there. For example:
// var config = DefaultConfig
// config.Capacity = 2000
var DefaultConfig = Config{
BaseUri: "https://app.launchdarkly.com",
StreamUri: "https://stream.launchdarkly.com",
EventsUri: "https://events.launchdarkly.com",
Capacity: 1000,
FlushInterval: 5 * time.Second,
PollInterval: 1 * time.Second,
Logger: log.New(os.Stderr, "[LaunchDarkly]", log.LstdFlags),
Timeout: 3000 * time.Millisecond,
Stream: true,
FeatureStore: nil,
UseLdd: false,
SendEvents: true,
Offline: false,
}
var (
ErrNonBooleanValue = errors.New("Feature flag returned non-boolean value")
ErrNonNumericValue = errors.New("Feature flag returned non-numeric value")
ErrInitializationTimeout = errors.New("Timeout encountered waiting for LaunchDarkly client initialization")
ErrClientNotInitialized = errors.New("Toggle called before LaunchDarkly client initialization completed")
ErrUnknownFeatureKey = errors.New("Unknown feature key. Verify that this feature key exists. Returning default value.")
)
// Creates a new client instance that connects to LaunchDarkly with the default configuration. In most
// cases, you should use this method to instantiate your client. The optional duration parameter allows callers to
// block until the client has connected to LaunchDarkly and is properly initialized.
func MakeClient(apiKey string, waitFor time.Duration) (*LDClient, error) {
return MakeCustomClient(apiKey, DefaultConfig, waitFor)
}
// Creates a new client instance that connects to LaunchDarkly with a custom configuration. The optional duration parameter allows callers to
// block until the client has connected to LaunchDarkly and is properly initialized.
func MakeCustomClient(apiKey string, config Config, waitFor time.Duration) (*LDClient, error) {
var updateProcessor updateProcessor
var store FeatureStore
ch := make(chan bool)
config.BaseUri = strings.TrimRight(config.BaseUri, "/")
config.EventsUri = strings.TrimRight(config.EventsUri, "/")
requestor := newRequestor(apiKey, config)
if config.FeatureStore == nil {
config.FeatureStore = NewInMemoryFeatureStore()
}
if config.PollInterval < (1 * time.Second) {
config.PollInterval = 1 * time.Second
}
store = config.FeatureStore
if !config.UseLdd && !config.Offline {
if config.Stream {
updateProcessor = newStreamProcessor(apiKey, config, requestor)
} else {
updateProcessor = newPollingProcessor(config, requestor)
}
updateProcessor.start(ch)
}
client := LDClient{
apiKey: apiKey,
config: config,
eventProcessor: newEventProcessor(apiKey, config),
updateProcessor: updateProcessor,
store: store,
}
if config.UseLdd || config.Offline {
return &client, nil
}
timeout := time.After(waitFor)
for {
select {
case <-ch:
return &client, nil
case <-timeout:
if waitFor > 0 {
return &client, ErrInitializationTimeout
}
return &client, nil
}
}
}
func (client *LDClient) Identify(user User) error {
if client.IsOffline() {
return nil
}
evt := NewIdentifyEvent(user)
return client.eventProcessor.sendEvent(evt)
}
// Tracks that a user has performed an event. Custom data can be attached to the
// event, and is serialized to JSON using the encoding/json package (http://golang.org/pkg/encoding/json/).
func (client *LDClient) Track(key string, user User, data interface{}) error {
if client.IsOffline() {
return nil
}
evt := NewCustomEvent(key, user, data)
return client.eventProcessor.sendEvent(evt)
}
// Returns whether the LaunchDarkly client is in offline mode.
func (client *LDClient) IsOffline() bool {
return client.config.Offline
}
// Returns whether the LaunchDarkly client is initialized.
func (client *LDClient) Initialized() bool {
return client.IsOffline() || client.config.UseLdd || client.updateProcessor.initialized()
}
// Shuts down the LaunchDarkly client. After calling this, the LaunchDarkly client
// should no longer be used.
func (client *LDClient) Close() {
if client.IsOffline() {
return
}
client.eventProcessor.close()
if !client.config.UseLdd {
client.updateProcessor.close()
}
}
// Immediately flushes queued events.
func (client *LDClient) Flush() {
if client.IsOffline() {
return
}
client.eventProcessor.flush()
}
// Returns a map from feature flag keys to boolean feature flag values for a given user. The
// map will contain nil for any flags that are off. If the client is offline or has not been initialized,
// a nil map will be returned. This method will not send analytics events back to LaunchDarkly.
// The most common use case for this is bootstrapping client-side feature flags from a back-end service.
func (client *LDClient) AllFlags(user User) (map[string]*bool, error) {
if client.IsOffline() {
return nil, nil
}
if !client.Initialized() {
return nil, ErrClientNotInitialized
}
allFlags, err := client.store.All()
if err != nil {
return nil, err
}
results := make(map[string]*bool)
for key, _ := range allFlags {
value, err := client.evaluate(key, user, nil)
if err != nil {
return nil, err
}
if value != nil {
bval, ok := value.(bool)
if !ok {
return nil, ErrNonBooleanValue
}
results[key] = &bval
} else {
results[key] = nil
}
}
return results, nil
}
// Returns the value of a boolean feature flag for a given user. Returns defaultVal if
// there is an error, if the flag doesn't exist, the client hasn't completed initialization,
// or the feature is turned off.
func (client *LDClient) Toggle(key string, user User, defaultVal bool) (bool, error) {
if client.IsOffline() {
return defaultVal, nil
}
value, err := client.evaluate(key, user, defaultVal)
if err != nil {
client.sendFlagRequestEvent(key, user, defaultVal, defaultVal)
return defaultVal, err
}
result, ok := value.(bool)
if !ok {
client.sendFlagRequestEvent(key, user, defaultVal, defaultVal)
return defaultVal, ErrNonBooleanValue
}
client.sendFlagRequestEvent(key, user, value, defaultVal)
return result, nil
}
// Returns the value of a feature flag (whose variations are integers) for the given user.
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off.
func (client *LDClient) IntVariation(key string, user User, defaultVal int) (int, error) {
if client.IsOffline() {
return defaultVal, nil
}
value, err := client.evaluate(key, user, float64(defaultVal))
if err != nil {
client.sendFlagRequestEvent(key, user, defaultVal, defaultVal)
return defaultVal, err
}
// json numbers are deserialized into float64s
result, ok := value.(float64)
if !ok {
client.sendFlagRequestEvent(key, user, defaultVal, defaultVal)
return defaultVal, ErrNonNumericValue
}
client.sendFlagRequestEvent(key, user, value, defaultVal)
return int(result), nil
}
// Returns the value of a feature flag (whose variations are floats) for the given user.
// Returns defaultVal if there is an error, if the flag doesn't exist, or the feature is turned off.
func (client *LDClient) Float64Variation(key string, user User, defaultVal float64) (float64, error) {
if client.IsOffline() {
return defaultVal, nil
}
value, err := client.evaluate(key, user, defaultVal)
if err != nil {
client.sendFlagRequestEvent(key, user, defaultVal, defaultVal)
return defaultVal, err
}
result, ok := value.(float64)
if !ok {
client.sendFlagRequestEvent(key, user, defaultVal, defaultVal)
return defaultVal, ErrNonNumericValue
}
client.sendFlagRequestEvent(key, user, value, defaultVal)
return result, nil
}
func (client *LDClient) sendFlagRequestEvent(key string, user User, value, defaultVal interface{}) error {
if client.IsOffline() {
return nil
}
evt := NewFeatureRequestEvent(key, user, value, defaultVal)
return client.eventProcessor.sendEvent(evt)
}
func (client *LDClient) evaluate(key string, user User, defaultVal interface{}) (interface{}, error) {
var feature Feature
var storeErr error
var featurePtr *Feature
if !client.Initialized() {
return defaultVal, ErrClientNotInitialized
}
featurePtr, storeErr = client.store.Get(key)
if storeErr != nil {
client.config.Logger.Printf("Encountered error fetching feature from store: %+v", storeErr)
return defaultVal, storeErr
}
if featurePtr != nil {
feature = *featurePtr
} else {
return defaultVal, ErrUnknownFeatureKey
}
value, pass := feature.Evaluate(user)
if pass {
return defaultVal, nil
}
return value, nil
}
|
package redisgraph
import (
"fmt"
"strings"
)
// Node represents a node within a graph.
type Node struct {
ID uint64
Label string
Alias string
Properties map[string]interface{}
graph *Graph
}
func NodeNew(label string, alias string, properties map[string]interface{}) *Node {
p := properties
if p == nil {
p = make(map[string]interface{})
}
return &Node{
Label: label,
Alias: alias,
Properties: p,
graph: nil,
}
}
func (n *Node) SetProperty(key string, value interface{}) {
n.Properties[key] = value
}
func (n Node) GetProperty(key string) interface{} {
v, _ := n.Properties[key]
return v
}
func (n Node) String() string {
if len(n.Properties) == 0 {
return "{}"
}
p := make([]string, 0, len(n.Properties))
for k, v := range n.Properties {
p = append(p, fmt.Sprintf("%s:%v", k, ToString(v)))
}
s := fmt.Sprintf("{%s}", strings.Join(p, ","))
return s
}
// String makes Node satisfy the Stringer interface.
func (n Node) Encode() string {
s := []string{"("}
if n.Alias != "" {
s = append(s, n.Alias)
}
if n.Label != "" {
s = append(s, ":", n.Label)
}
if len(n.Properties) > 0 {
p := make([]string, 0, len(n.Properties))
for k, v := range n.Properties {
p = append(p, fmt.Sprintf("%s:%v", k, ToString(v)))
}
s = append(s, "{")
s = append(s, strings.Join(p, ","))
s = append(s, "}")
}
s = append(s, ")")
return strings.Join(s, "")
}
|
// Copyright 2020 Akamai Technologies, 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 collectors
import (
"fmt"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
"testing"
edgegrid "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid"
)
var (
config = edgegrid.Config{
Host: "akaa-baseurl-xxxxxxxxxxx-xxxxxxxxxxxxx.luna.akamaiapis.net/",
AccessToken: "akab-access-token-xxx-xxxxxxxxxxxxxxxx",
ClientToken: "akab-client-token-xxx-xxxxxxxxxxxxxxxx",
ClientSecret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=",
MaxBody: 2048,
Debug: false,
}
)
func TestGetTrafficReport(t *testing.T) {
//(zone string, trafficReportQueryArgs *TrafficReportQueryArgs) (TrafficRecordsResponse, error)
dnsTestDomain := "testdomain.com.akadns.net"
dnsTestProperty := "testprop"
queryargs := map[string]string{"date": "2016/11/23"}
defer gock.Off()
mock := gock.New(fmt.Sprintf("https://akaa-baseurl-xxxxxxxxxxx-xxxxxxxxxxxxx.luna.akamaiapis.net/gtm-api/v1/reports/liveness-tests/domains/%s/properties/%s", dnsTestDomain, dnsTestProperty))
mock.
Get(fmt.Sprintf("/gtm-api/v1/reports/liveness-tests/domains/%s/properties/%s", dnsTestDomain, dnsTestProperty)).
HeaderPresent("Authorization").
Reply(200).
BodyString(`{
"metadata": {
"date": "2016-11-23",
"domain": "example.akadns.net",
"property": "www",
"uri": "https://akab-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx.luna.akamaiapis.net/gtm-api/v1/reports/liveness-tests/domains/example.akadns.net/properties/www?date=2016-11-23"
},
"dataRows": [ {
"timestamp": "2016-11-23T00:13:23Z",
"datacenters": [ {
"datacenterId": 3201,
"agentIp": "204.1.136.239",
"testName": "Our defences",
"errorCode": 3101,
"duration": 0,
"nickname": "Winterfell",
"trafficTargetName": "Winterfell - 1.2.3.4",
"targetIp": "1.2.3.4"
} ]
} ],
"links": [ {
"rel": "self",
"href": "https://akab-xxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx.luna.akamaiapis.net/gtm-api/v1/reports/liveness-tests/domains/example.akadns.net/properties/www?date=2016-11-23"
} ]
}`)
EdgeInit(config)
// returns type TrafficRecordsResponse [][]string
report, err := GetLivenessErrorsReport(dnsTestDomain, dnsTestProperty, queryargs)
assert.NoError(t, err)
assert.Equal(t, report.Metadata.Date, "2016-11-23")
}
func TestGetTrafficReport_BadArg(t *testing.T) {
//(zone string, trafficReportQueryArgs *TrafficReportQueryArgs) (TrafficRecordsResponse, error)
dnsTestDomain := "testdomain.com.akadns.net"
dnsTestProperty := "testprop"
queryargs := map[string]string{"date": "2016/11/23"}
defer gock.Off()
mock := gock.New(fmt.Sprintf("https://akaa-baseurl-xxxxxxxxxxx-xxxxxxxxxxxxx.luna.akamaiapis.net/gtm-api/v1/reports/liveness-tests/domains/%s/properties/%s", dnsTestDomain, dnsTestProperty))
mock.
Get(fmt.Sprintf("/gtm-api/v1/reports/liveness-tests/domains/%s/properties/%s", dnsTestDomain, dnsTestProperty)).
HeaderPresent("Authorization").
Reply(500).
BodyString(`Server Error`)
EdgeInit(config)
// returns type TrafficRecordsResponse [][]string
_, err := GetLivenessErrorsReport(dnsTestDomain, dnsTestProperty, queryargs)
assert.Error(t, err)
}
|
package main
import (
"bufio"
"fmt"
"io"
"log"
"strconv"
"strings"
)
func main() {
r := strings.NewReader(input)
ints := extractIntArr(r)
for i := 0; i < len(ints); i++ {
a := ints[i]
for j := i + 1; j < len(ints); j++ {
b := ints[j]
for k := j + 1; k < len(ints); k++ {
c := ints[k]
if a+b+c == 2020 {
fmt.Println(a * b * c)
return
}
}
}
}
}
// func main() {
// r := strings.NewReader(input)
// ints := extractIntArr(r)
// for i := 0; i < len(ints); i++ {
// a := ints[i]
// for j := i + 1; j < len(ints); j++ {
// b := ints[j]
// if a + b == 2020 {
// fmt.Println(a*b)
// return
// }
// }
// }
// }
func extractIntArr(reader io.Reader) []int {
var ints []int
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
i, err := strconv.Atoi(scanner.Text())
if err != nil {
log.Panic(err)
}
ints = append(ints, i)
}
return ints
}
|
package pkg
import (
"net"
"github.com/google/gopacket/layers"
)
// @EthernetInterface is the name of the ethernet interface of system.
// ServerAddr is the address provided by the NAT.
// @LocalInterface is the name of the local interface of system.
// @WireLessInterface is the name of the wireless interface of system.
// @IPLayerForPrototype is a template for the IP layer
// @UDPLayerForPrototype is a template for the UDP layer.
var EthernetInterface string = "enx00e04c3607b7"
var ServerAddr net.IPAddr = net.IPAddr{IP: net.ParseIP("127.0.0.1")}
var LocalInterface string = "lo"
var WireLessInterface string = "wlp2s0"
var emptyBaseLayer layers.BaseLayer = layers.BaseLayer{Contents:[]byte{}, Payload:[]byte{}}
var IPLayerForPrototype layers.IPv4 = layers.IPv4{BaseLayer:emptyBaseLayer, Version:4, IHL:5, TOS:0, Length:20, Id:9120, Flags:0, FragOffset:0, TTL:128, Protocol:17, Checksum:0, SrcIP:net.ParseIP("0.0.0.0"), DstIP:net.ParseIP("0.0.0.0")}
var UDPLayerForPrototype layers.UDP = layers.UDP{BaseLayer:emptyBaseLayer, SrcPort:0, DstPort:0,Length:8, Checksum:0}
// @HolePunchPort is the port number provided for the hole punching.
// @IsPacketForPing is the value of byte to check whether packet is for pinging
// or not.
// @CustomLayerByteSize is lenght of custom layer.
const HolePunchPort uint16 = 8000
const IsPacketForPing uint8 = 1
const CustomLayerByteSize uint8 = 24
// This method allow us to intialise variable which
// will be required for further computation.
func init() {
}
|
package controllers
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/anshap1719/authentication/controllers/gen/twitter"
"github.com/anshap1719/authentication/database"
"github.com/anshap1719/authentication/models"
"github.com/anshap1719/authentication/utils/auth"
. "github.com/anshap1719/authentication/utils/ctx"
"github.com/globalsign/mgo"
"github.com/gofrs/uuid"
"github.com/mrjones/oauth"
"log"
"net"
"os"
"reflect"
"strings"
"time"
)
const (
twitterAuthentication = iota
twitterAttach
)
const (
twitterConnectionExpire = 30 * time.Minute
twitterRegisterExpire = time.Hour
)
var twitterConf = oauth.NewConsumer(
os.Getenv("TwitterKey"),
os.Getenv("TwitterSecret"),
oauth.ServiceProvider{
RequestTokenUrl: "https://api.twitter.com/oauth/request_token",
AuthorizeTokenUrl: "https://api.twitter.com/oauth/authorize",
AccessTokenUrl: "https://api.twitter.com/oauth/access_token",
})
// TwitterService implements the twitter resource.
type TwitterService struct {
log *log.Logger
jwt *auth.JWTSecurity
session *SessionService
}
type TwitterRegisterMedia struct {
OauthKey, FirstName, LastName, Email string
TimeCreated time.Time
}
// NewTwitterService creates a twitter controller.
func NewTwitterService(log *log.Logger, jwt *auth.JWTSecurity, session *SessionService) twitter.Service {
return &TwitterService{
log: log,
jwt: jwt,
session: session,
}
}
// Gets the URL the front-end should redirect the browser to in order to be
// authenticated with Twitter, and then register
func (s *TwitterService) RegisterURL(ctx context.Context, p *twitter.RegisterURLPayload) (res string, err error) {
gc := &database.TwitterConnection{
TimeCreated: time.Now(),
Purpose: twitterAuthentication,
}
state, err := database.CreateTwitterConnection(ctx, gc)
if err != nil {
fmt.Println("Error: ", err)
return "", twitter.MakeInternalServerError(err)
}
tokenUrl := os.Getenv("ClientURL") + "/social/twitter?state=" + state.String()
token, requestUrl, err := twitterConf.GetRequestTokenAndUrl(tokenUrl)
if err != nil {
return "", twitter.MakeInternalServerError(err)
}
if err := database.CreateTwitterToken(token.Token, *token); err != nil {
return "", twitter.MakeInternalServerError(err)
}
return requestUrl, nil
}
// Attaches a Twitter account to an existing user account, returns the URL the
// browser should be redirected to
func (s *TwitterService) AttachToAccount(ctx context.Context, p *twitter.AttachToAccountPayload) (res string, err error) {
gc := &database.TwitterConnection{
TimeCreated: time.Now(),
Purpose: twitterAttach,
}
state, err := database.CreateTwitterConnection(ctx, gc)
if err != nil {
return "", twitter.MakeInternalServerError(err)
}
tokenUrl := os.Getenv("ClientURL") + "/social/twitter?state=" + state.String()
token, requestUrl, err := twitterConf.GetRequestTokenAndUrl(tokenUrl)
if err != nil {
return "", twitter.MakeInternalServerError(err)
}
if err := database.CreateTwitterToken(token.Token, *token); err != nil {
return "", twitter.MakeInternalServerError(err)
}
return requestUrl, nil
}
// Detaches a Twitter account from an existing user account.
func (s *TwitterService) DetachFromAccount(ctx context.Context, p *twitter.DetachFromAccountPayload) (err error) {
uID := s.jwt.GetUserID(*p.Authorization)
if getNumLoginMethods(ctx, uID) <= 1 {
return twitter.MakeForbidden(errors.New("Cannot detach last login method"))
}
gID, err := database.QueryTwitterAccountUser(ctx, uID)
if err == database.ErrTwitterAccountNotFound {
return twitter.MakeNotFound(errors.New("User account is not connected to Twitter"))
} else if err != nil {
return twitter.MakeInternalServerError(err)
}
err = database.DeleteTwitterAccount(ctx, gID)
if err != nil {
return twitter.MakeInternalServerError(err)
}
return nil
}
// The endpoint that Twitter redirects the browser to after the user has
// authenticated
func (s *TwitterService) Receive(ctx context.Context, p *twitter.ReceivePayload) (res *twitter.UserMedia, err error) {
state, err := uuid.FromString(*p.State)
if err != nil {
return nil, twitter.MakeBadRequest(errors.New("State UUID is invalid"))
}
gc, err := database.GetTwitterConnection(ctx, state)
if err == database.ErrTwitterConnectionNotFound {
return nil, twitter.MakeBadRequest(errors.New("Twitter connection must be created with other API methods"))
} else if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
err = database.DeleteTwitterConnection(ctx, state)
if err != nil {
s.log.Println("Unable to delete Twitter connection")
}
if gc.TimeCreated.Add(twitterConnectionExpire).Before(time.Now()) {
return nil, twitter.MakeBadRequest(errors.New("Twitter token expired. Please try again"))
}
code := p.OauthVerifier
key := p.OauthToken
token, err := database.GetTwitterToken(*key)
if err == mgo.ErrNotFound {
return nil, twitter.MakeBadRequest(err)
} else if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
err = database.DeleteTwitterToken(*key)
if err != nil {
s.log.Println("Unable to delete Twitter connection")
}
accessToken, err := twitterConf.AuthorizeToken(token, *code)
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
client, err := twitterConf.MakeHttpClient(accessToken)
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
response, err := client.Get(
"https://api.twitter.com/1.1/account/verify_credentials.json?include_entities=false&skip_status=true&include_email=true")
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
defer response.Body.Close()
var twitterUser models.TwitterResponse
if err := json.NewDecoder(response.Body).Decode(&twitterUser); err != nil {
return nil, twitter.MakeInternalServerError(err)
}
gID := string(twitterUser.ID)
switch gc.Purpose {
case twitterAuthentication:
account, err := database.GetTwitterAccount(ctx, gID)
if err == database.ErrTwitterAccountNotFound {
_, err := database.GetTwitterAccount(ctx, gID)
if err == nil {
return nil, twitter.MakeBadRequest(errors.New("This Twitter account is already attached to an account"))
} else if err != database.ErrTwitterAccountNotFound {
return nil, twitter.MakeInternalServerError(err)
}
gr := &database.TwitterRegister{
TwitterID: gID,
TimeCreated: time.Now(),
}
regID, err := database.CreateTwitterRegister(ctx, gr)
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
grm := &TwitterRegisterMedia{
OauthKey: regID.String(),
Email: twitterUser.Email,
FirstName: strings.Split(twitterUser.Name, " ")[0],
LastName: strings.Split(twitterUser.Name, " ")[1],
}
return s.TwitterRegister(ctx, grm, regID.String())
} else if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
u, err := database.GetUser(ctx, account.UserID)
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
remoteAddrInt := ctx.Value(RequestXForwardedForKey)
var remoteAddr string
if remoteAddrInt == nil || (reflect.ValueOf(remoteAddrInt).Kind() != reflect.String) {
remoteAddr = ""
} else {
remoteAddr = remoteAddrInt.(string)
}
sesToken, authToken, err := s.session.loginUser(ctx, *u, remoteAddr, ctx.Value(RequestUserAgentKey).(string))
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
token := "Bearer " + authToken
resp := &twitter.UserMedia{
ID: u.ID.Hex(),
FirstName: u.FirstName,
LastName: u.LastName,
Email: u.Email,
ChangingEmail: &u.ChangingEmail,
VerifiedEmail: u.VerifiedEmail,
IsAdmin: &u.IsAdmin,
Authorization: token,
XSession: sesToken,
}
return resp, nil
case twitterAttach:
_, err := database.GetTwitterAccount(ctx, gID)
if err == nil {
return nil, twitter.MakeBadRequest(errors.New("This Twitter account is already attached to an account"))
} else if err != database.ErrTwitterAccountNotFound {
return nil, twitter.MakeInternalServerError(err)
}
uID := s.jwt.GetUserID(*p.Authorization)
if uID == "" {
return nil, twitter.MakeUnauthorized(errors.New("You must be logged in"))
}
_, err = database.GetUser(ctx, uID)
if err == database.ErrUserNotFound {
s.log.Println("Unable to get user account")
return nil, twitter.MakeInternalServerError(errors.New("Unable to find user account"))
} else if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
account := &database.TwitterAccount{
ID: gID,
UserID: uID,
}
err = database.CreateTwitterAccount(ctx, account)
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
default:
s.log.Println("Bad Twitter receive type")
return nil, twitter.MakeInternalServerError(errors.New("Invalid Twitter connection type"))
}
return &twitter.UserMedia{}, nil
}
func (s *TwitterService) TwitterRegister(ctx context.Context, grm *TwitterRegisterMedia, OauthKey string) (*twitter.UserMedia, error) {
gr, err := database.GetTwitterRegister(ctx, uuid.FromStringOrNil(grm.OauthKey))
if err == database.ErrTwitterRegisterNotFound {
return nil, twitter.MakeNotFound(errors.New("Invalid registration key"))
} else if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
if gr.TimeCreated.Add(twitterRegisterExpire).Before(time.Now()) {
return nil, twitter.MakeNotFound(errors.New("Invalid registration key"))
}
_, err = database.GetTwitterAccount(ctx, gr.TwitterID)
if err == nil {
return nil, twitter.MakeForbidden(errors.New("This Twitter account is already attached to an account"))
} else if err != database.ErrTwitterAccountNotFound {
return nil, twitter.MakeInternalServerError(err)
}
_, err = database.QueryUserEmail(ctx, grm.Email)
if err == nil {
return nil, twitter.MakeForbidden(errors.New("This email is already in use" + " email " + grm.Email))
} else if err != database.ErrUserNotFound {
return nil, twitter.MakeInternalServerError(err)
}
remoteAddrInt := ctx.Value(RequestXForwardedForKey)
var remoteAddr string
if remoteAddrInt == nil || (reflect.ValueOf(remoteAddrInt).Kind() != reflect.String) {
remoteAddr = ""
} else {
remoteAddr = remoteAddrInt.(string)
}
ipAddr, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
ipAddr = remoteAddr
}
newU := &models.User{
FirstName: grm.FirstName,
LastName: grm.LastName,
Email: grm.Email,
VerifiedEmail: true,
}
captcha := ""
uID, err := createUser(ctx, newU, &captcha, ipAddr)
if err == ErrInvalidRecaptcha {
return nil, twitter.MakeBadRequest(err)
} else if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
account := &database.TwitterAccount{
ID: gr.TwitterID,
UserID: uID,
}
err = database.CreateTwitterAccount(ctx, account)
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
err = database.DeleteTwitterRegister(ctx, uuid.FromStringOrNil(grm.OauthKey))
if err != nil {
s.log.Println("Unable to delete Twitter registration progress")
}
sesToken, authToken, err := s.session.loginUser(ctx, *newU, remoteAddr, ctx.Value(RequestUserAgentKey).(string))
if err != nil {
return nil, twitter.MakeInternalServerError(err)
}
return &twitter.UserMedia{
Email: grm.Email,
FirstName: grm.FirstName,
LastName: grm.LastName,
Authorization: authToken,
XSession: sesToken,
}, nil
}
|
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test__sphere_rayIntersect_inside(t *testing.T) {
s := sphere{10, vector{0, 0, 0}, material{}}
d, ok := s.rayIntersect(vector{0, 0, 0}, vector{1, 1, 1})
assert.True(t, ok)
assert.Equal(t, float64(10), d)
}
|
package services
import (
"models"
"net"
"strconv"
"errors"
"log"
)
// Just used to wrap the actual Peer from models.Peer here to use it as caller
type UDPConnection struct {
UCPConnObject *models.UDPConnection
}
// When Creating Initial (despite first element in tunnel), always set writer for left side >> Write back to origin
func CreateInitialUDPConnectionLeft(leftHost string, leftPort int, tunndelId uint32) (*models.UDPConnection, error) {
// first, create leftWriter
leftWriter, err := CreateUDPWriter(leftHost, leftPort)
if err != nil {
return nil, errors.New("CreateInitialUDPConnection: Problem creating new UDPWriter, " + err.Error())
}
return &models.UDPConnection{tunndelId, leftHost, leftPort, "", 0, leftWriter, nil}, nil
}
func CreateInitialUDPConnectionRight(rightHost string, rightPort int, tunndelId uint32) (*models.UDPConnection, error) {
// first, create rightWriter
rightWriter, err := CreateUDPWriter(rightHost, rightPort)
if err != nil {
return nil, errors.New("CreateInitialUDPConnection: Problem creating new UDPWriter, " + err.Error())
}
return &models.UDPConnection{tunndelId, rightHost, rightPort, "", 0, nil, rightWriter}, nil
}
// Creates a new writer for a given ip and port
func CreateUDPWriter(destinationAddress string, destinationPort int) (net.Conn, error){
newConn, err := net.Dial("udp", destinationAddress + ":" + strconv.Itoa(destinationPort))
if err != nil {
return nil, errors.New("createUDPWriter: Error while creating new wirter, error: " + err.Error())
}
log.Println("createUDPWriter: Created new writer to " + destinationAddress + ", Port: " + strconv.Itoa(destinationPort))
return newConn, nil
}
|
package greeter
import (
"github.com/hashrs/blockchain/framework/chain-starter"
"github.com/spf13/cobra"
"github.com/hashrs/blockchain/chain/x/greeter/client/cli"
gtypes "github.com/hashrs/blockchain/chain/x/greeter/internal/types"
"github.com/hashrs/blockchain/framework/chain-app/codec"
sdk "github.com/hashrs/blockchain/framework/chain-app/types"
"github.com/hashrs/blockchain/framework/chain-app/types/module"
)
// AppModuleBasic is the minimal struct for a module
type AppModuleBasic struct {
starter.BlankModuleBasic
}
// AppModule contains the full module
type AppModule struct {
starter.BlankModule
keeper Keeper
ModuleName string
}
// type check to ensure the interface is properly implemented
var (
_ module.AppModule = AppModule{}
_ module.AppModuleBasic = AppModuleBasic{}
)
// RegisterCodec registers module Messages for encoding/decoding.
func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(gtypes.MsgGreet{}, "greeter/SayHello", nil)
}
// NewHandler returns a function for routing Messages to their appropriate handler functions.
func (am AppModule) NewHandler() sdk.Handler {
return NewHandler(am.keeper)
}
// NewQuerierHandler returns a function for routing incoming Queries to the right querier.
func (am AppModule) NewQuerierHandler() sdk.Querier {
return NewQuerier(am.keeper)
}
// QuerierRoute is used for routing Queries to this module.
func (am AppModule) QuerierRoute() string {
return am.ModuleName
}
// GetQueryCmd assembles and returns all the clie query CLI commands supported by the module.
func (ab AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command {
return cli.GetQueryCmd(gtypes.StoreKey, cdc)
}
// GetTxCmd assembles and returns all the clie query CLI commands supported by the module.
func (ab AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command {
return cli.GetTxCmd(gtypes.StoreKey, cdc)
}
// NewAppModule contstructs the full AppModule struct for this module.
func NewAppModule(keeper Keeper) AppModule {
blank := starter.NewBlankModule(gtypes.ModuleName, keeper)
return AppModule{blank, keeper, gtypes.ModuleName}
}
|
package main
import "fmt"
import m "golang-book/chapter11/math" // Directory must be in $GOPATH
func main() {
xs := []float64{1, 2, 3, 4}
avg := m.Average(xs)
fmt.Println(avg)
}
// Inside ./math, run `go install` to create a linkable object file
// Then, go to ./chapter11 and run `go run main.go`
|
package types
// OrderedSet represents an ordered set.
type OrderedSet struct {
filter map[string]bool
Values []string
}
// Init creates a new OrderedSet instance, and adds any given items into this set.
func (o *OrderedSet) Init(items ...string) {
o.filter = make(map[string]bool)
for _, item := range items {
o.Add(item)
}
}
// Add adds a new item into the ordered set.
func (o *OrderedSet) Add(item string) {
if !o.filter[item] {
o.filter[item] = true
o.Values = append(o.Values, item)
}
}
|
package download
import (
"io"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/buffalo/render"
"github.com/gomods/athens/pkg/errors"
"github.com/gomods/athens/pkg/log"
)
// PathVersionZip URL.
const PathVersionZip = "/{module:.+}/@v/{version}.zip"
// VersionZipHandler implements GET baseURL/module/@v/version.zip
func VersionZipHandler(dp Protocol, lggr log.Entry, eng *render.Engine) buffalo.Handler {
const op errors.Op = "download.VersionZipHandler"
return func(c buffalo.Context) error {
mod, ver, err := getModuleParams(c, op)
if err != nil {
lggr.SystemErr(err)
return c.Render(errors.Kind(err), nil)
}
zip, err := dp.Zip(c, mod, ver)
if err != nil {
lggr.SystemErr(err)
return c.Render(errors.Kind(err), nil)
}
defer zip.Close()
// Calling c.Response().Write will write the header directly
// and we would get a 0 status in the buffalo logs.
c.Render(200, nil)
_, err = io.Copy(c.Response(), zip)
if err != nil {
lggr.SystemErr(errors.E(op, errors.M(mod), errors.V(ver), err))
}
return nil
}
}
|
package main
import "errors"
func main() {
panic(errors.New("where is zhong?"))
}
|
package hdfs
import (
"context"
"net/http"
"github.com/colinmarc/hdfs/v2"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"github.com/yunify/qscamel/constants"
"github.com/yunify/qscamel/model"
)
// Client is the struct for HDFS endpoint.
type Client struct {
Address string `yaml:"address"`
Path string
client *hdfs.Client
}
// New will create a client.
func New(ctx context.Context, et uint8, _ *http.Client) (c *Client, err error) {
t, err := model.GetTask(ctx)
if err != nil {
return
}
c = &Client{}
e := t.Src
if et == constants.DestinationEndpoint {
e = t.Dst
}
content, err := yaml.Marshal(e.Options)
if err != nil {
return
}
err = yaml.Unmarshal(content, c)
if err != nil {
return
}
// Check address.
if c.Address == "" {
logrus.Error("HDFS's address can't be empty.")
err = constants.ErrEndpointInvalid
return
}
c.Path = e.Path
c.client, err = hdfs.New(c.Address)
if err != nil {
return nil, err
}
return
}
|
// Copyright 2019 The Android Open Source Project
//
// 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 rust
import (
"fmt"
"path/filepath"
"github.com/google/blueprint/proptools"
"android/soong/android"
"android/soong/rust/config"
)
func getEdition(compiler *baseCompiler) string {
return proptools.StringDefault(compiler.Properties.Edition, config.DefaultEdition)
}
func getDenyWarnings(compiler *baseCompiler) bool {
return BoolDefault(compiler.Properties.Deny_warnings, config.DefaultDenyWarnings)
}
func (compiler *baseCompiler) setNoStdlibs() {
compiler.Properties.No_stdlibs = proptools.BoolPtr(true)
}
func NewBaseCompiler(dir, dir64 string, location installLocation) *baseCompiler {
return &baseCompiler{
Properties: BaseCompilerProperties{},
dir: dir,
dir64: dir64,
location: location,
}
}
type installLocation int
const (
InstallInSystem installLocation = 0
InstallInData = iota
)
type BaseCompilerProperties struct {
// whether to pass "-D warnings" to rustc. Defaults to true.
Deny_warnings *bool
// flags to pass to rustc
Flags []string `android:"path,arch_variant"`
// flags to pass to the linker
Ld_flags []string `android:"path,arch_variant"`
// list of rust rlib crate dependencies
Rlibs []string `android:"arch_variant"`
// list of rust dylib crate dependencies
Dylibs []string `android:"arch_variant"`
// list of rust proc_macro crate dependencies
Proc_macros []string `android:"arch_variant"`
// list of C shared library dependencies
Shared_libs []string `android:"arch_variant"`
// list of C static library dependencies
Static_libs []string `android:"arch_variant"`
// crate name, required for libraries. This must be the expected extern crate name used in source
Crate_name string `android:"arch_variant"`
// list of features to enable for this crate
Features []string `android:"arch_variant"`
// specific rust edition that should be used if the default version is not desired
Edition *string `android:"arch_variant"`
// sets name of the output
Stem *string `android:"arch_variant"`
// append to name of output
Suffix *string `android:"arch_variant"`
// install to a subdirectory of the default install path for the module
Relative_install_path *string `android:"arch_variant"`
// whether to suppress inclusion of standard crates - defaults to false
No_stdlibs *bool
}
type baseCompiler struct {
Properties BaseCompilerProperties
pathDeps android.Paths
rustFlagsDeps android.Paths
linkFlagsDeps android.Paths
flags string
linkFlags string
depFlags []string
linkDirs []string
edition string
src android.Path //rustc takes a single src file
// Install related
dir string
dir64 string
subDir string
relative string
path android.InstallPath
location installLocation
}
var _ compiler = (*baseCompiler)(nil)
func (compiler *baseCompiler) inData() bool {
return compiler.location == InstallInData
}
func (compiler *baseCompiler) compilerProps() []interface{} {
return []interface{}{&compiler.Properties}
}
func (compiler *baseCompiler) featuresToFlags(features []string) []string {
flags := []string{}
for _, feature := range features {
flags = append(flags, "--cfg 'feature=\""+feature+"\"'")
}
return flags
}
func (compiler *baseCompiler) compilerFlags(ctx ModuleContext, flags Flags) Flags {
if getDenyWarnings(compiler) {
flags.RustFlags = append(flags.RustFlags, "-D warnings")
}
flags.RustFlags = append(flags.RustFlags, compiler.Properties.Flags...)
flags.RustFlags = append(flags.RustFlags, compiler.featuresToFlags(compiler.Properties.Features)...)
flags.RustFlags = append(flags.RustFlags, "--edition="+getEdition(compiler))
flags.LinkFlags = append(flags.LinkFlags, compiler.Properties.Ld_flags...)
flags.GlobalRustFlags = append(flags.GlobalRustFlags, config.GlobalRustFlags...)
flags.GlobalRustFlags = append(flags.GlobalRustFlags, ctx.toolchain().ToolchainRustFlags())
flags.GlobalLinkFlags = append(flags.GlobalLinkFlags, ctx.toolchain().ToolchainLinkFlags())
if ctx.Host() && !ctx.Windows() {
rpath_prefix := `\$$ORIGIN/`
if ctx.Darwin() {
rpath_prefix = "@loader_path/"
}
var rpath string
if ctx.toolchain().Is64Bit() {
rpath = "lib64"
} else {
rpath = "lib"
}
flags.LinkFlags = append(flags.LinkFlags, "-Wl,-rpath,"+rpath_prefix+rpath)
flags.LinkFlags = append(flags.LinkFlags, "-Wl,-rpath,"+rpath_prefix+"../"+rpath)
}
return flags
}
func (compiler *baseCompiler) compile(ctx ModuleContext, flags Flags, deps PathDeps) android.Path {
panic(fmt.Errorf("baseCrater doesn't know how to crate things!"))
}
func (compiler *baseCompiler) compilerDeps(ctx DepsContext, deps Deps) Deps {
deps.Rlibs = append(deps.Rlibs, compiler.Properties.Rlibs...)
deps.Dylibs = append(deps.Dylibs, compiler.Properties.Dylibs...)
deps.ProcMacros = append(deps.ProcMacros, compiler.Properties.Proc_macros...)
deps.StaticLibs = append(deps.StaticLibs, compiler.Properties.Static_libs...)
deps.SharedLibs = append(deps.SharedLibs, compiler.Properties.Shared_libs...)
if !Bool(compiler.Properties.No_stdlibs) {
for _, stdlib := range config.Stdlibs {
// If we're building for host, use the compiler's stdlibs
if ctx.Host() {
stdlib = stdlib + "_" + ctx.toolchain().RustTriple()
}
// This check is technically insufficient - on the host, where
// static linking is the default, if one of our static
// dependencies uses a dynamic library, we need to dynamically
// link the stdlib as well.
if (len(deps.Dylibs) > 0) || (!ctx.Host()) {
// Dynamically linked stdlib
deps.Dylibs = append(deps.Dylibs, stdlib)
}
}
}
return deps
}
func (compiler *baseCompiler) bionicDeps(ctx DepsContext, deps Deps) Deps {
deps.SharedLibs = append(deps.SharedLibs, "liblog")
deps.SharedLibs = append(deps.SharedLibs, "libc")
deps.SharedLibs = append(deps.SharedLibs, "libm")
deps.SharedLibs = append(deps.SharedLibs, "libdl")
//TODO(b/141331117) libstd requires libgcc on Android
deps.StaticLibs = append(deps.StaticLibs, "libgcc")
return deps
}
func (compiler *baseCompiler) crateName() string {
return compiler.Properties.Crate_name
}
func (compiler *baseCompiler) installDir(ctx ModuleContext) android.InstallPath {
dir := compiler.dir
if ctx.toolchain().Is64Bit() && compiler.dir64 != "" {
dir = compiler.dir64
}
if !ctx.Host() || ctx.Target().NativeBridge == android.NativeBridgeEnabled {
dir = filepath.Join(dir, ctx.Arch().ArchType.String())
}
return android.PathForModuleInstall(ctx, dir, compiler.subDir,
compiler.relativeInstallPath(), compiler.relative)
}
func (compiler *baseCompiler) install(ctx ModuleContext, file android.Path) {
compiler.path = ctx.InstallFile(compiler.installDir(ctx), file.Base(), file)
}
func (compiler *baseCompiler) getStem(ctx ModuleContext) string {
return compiler.getStemWithoutSuffix(ctx) + String(compiler.Properties.Suffix)
}
func (compiler *baseCompiler) getStemWithoutSuffix(ctx BaseModuleContext) string {
stem := ctx.baseModuleName()
if String(compiler.Properties.Stem) != "" {
stem = String(compiler.Properties.Stem)
}
return stem
}
func (compiler *baseCompiler) relativeInstallPath() string {
return String(compiler.Properties.Relative_install_path)
}
func srcPathFromModuleSrcs(ctx ModuleContext, srcs []string) android.Path {
srcPaths := android.PathsForModuleSrc(ctx, srcs)
if len(srcPaths) != 1 {
ctx.PropertyErrorf("srcs", "srcs can only contain one path for rust modules")
}
return srcPaths[0]
}
|
package collection
import "github.com/shopspring/decimal"
type BaseCollection struct {
value interface{}
length int
}
func (c BaseCollection) Value() interface{} {
return c.value
}
func (c BaseCollection) All() []interface{} {
panic("not implement")
}
func (c BaseCollection) Avg(key ...string) decimal.Decimal {
return c.Sum(key...).Div(decimal.New(int64(c.length), 0))
}
func (c BaseCollection) Sum(key ...string) decimal.Decimal {
panic("not implement")
}
func (c BaseCollection) Min(key ...string) decimal.Decimal {
panic("not implement")
}
func (c BaseCollection) Max(key ...string) decimal.Decimal {
panic("not implement")
}
func (c BaseCollection) Join(delimiter string) string {
panic("not implement")
}
func (c BaseCollection) Combine(value []interface{}) Collection {
panic("not implement")
}
func (c BaseCollection) Pluck(key string) Collection {
panic("not implement")
}
func (c BaseCollection) Mode(key ...string) []interface{} {
panic("not implement")
}
func (c BaseCollection) Only(keys []string) Collection {
panic("not implement")
}
func (c BaseCollection) Prepend(values ...interface{}) Collection {
panic("not implement")
}
func (c BaseCollection) Pull(key interface{}) Collection {
panic("not implement")
}
func (c BaseCollection) Put(key string, value interface{}) Collection {
panic("not implement")
}
func (c BaseCollection) SortBy(key string) Collection {
panic("not implement")
}
func (c BaseCollection) Take(num int) Collection {
panic("not implement")
}
func (c BaseCollection) Average() {
panic("not implement")
}
func (c BaseCollection) Chunk(num int) MultiDimensionalArrayCollection {
panic("not implement")
}
func (c BaseCollection) Collapse() Collection {
panic("not implement")
}
func (c BaseCollection) Concat(value interface{}) Collection {
panic("not implement")
}
func (c BaseCollection) Contains(value interface{}, callback ...interface{}) bool {
panic("not implement")
}
func (c BaseCollection) ContainsStrict(value interface{}, callback ...interface{}) bool {
panic("not implement")
}
func (c BaseCollection) CountBy(callback ...interface{}) map[interface{}]int {
panic("not implement")
}
func (c BaseCollection) CrossJoin(array ...[]interface{}) MultiDimensionalArrayCollection {
panic("not implement")
}
func (c BaseCollection) Dd() {
panic("not implement")
}
func (c BaseCollection) Diff() {
panic("not implement")
}
func (c BaseCollection) DiffAssoc() {
panic("not implement")
}
func (c BaseCollection) DiffKeys() {
panic("not implement")
}
func (c BaseCollection) Dump() {
panic("not implement")
}
func (c BaseCollection) Each() {
panic("not implement")
}
func (c BaseCollection) EachSpread() {
panic("not implement")
}
func (c BaseCollection) Every() {
panic("not implement")
}
func (c BaseCollection) Except() {
panic("not implement")
}
func (c BaseCollection) Filter() {
panic("not implement")
}
func (c BaseCollection) First() {
panic("not implement")
}
func (c BaseCollection) FirstWhere() {
panic("not implement")
}
func (c BaseCollection) FlatMap() {
panic("not implement")
}
func (c BaseCollection) Flatten() {
panic("not implement")
}
func (c BaseCollection) Flip() {
panic("not implement")
}
func (c BaseCollection) Forget() {
panic("not implement")
}
func (c BaseCollection) ForPage() {
panic("not implement")
}
func (c BaseCollection) Get() {
panic("not implement")
}
func (c BaseCollection) GroupBy() {
panic("not implement")
}
func (c BaseCollection) Has() {
panic("not implement")
}
func (c BaseCollection) Implode() {
panic("not implement")
}
func (c BaseCollection) Intersect() {
panic("not implement")
}
func (c BaseCollection) IntersectByKeys() {
panic("not implement")
}
func (c BaseCollection) IsEmpty() {
panic("not implement")
}
func (c BaseCollection) IsNotEmpty() {
panic("not implement")
}
func (c BaseCollection) KeyBy() {
panic("not implement")
}
func (c BaseCollection) Keys() {
panic("not implement")
}
func (c BaseCollection) Last() {
panic("not implement")
}
func (c BaseCollection) Macro() {
panic("not implement")
}
func (c BaseCollection) Make() {
panic("not implement")
}
func (c BaseCollection) Map() {
panic("not implement")
}
func (c BaseCollection) MapInto() {
panic("not implement")
}
func (c BaseCollection) MapSpread() {
panic("not implement")
}
func (c BaseCollection) MapToGroups() {
panic("not implement")
}
func (c BaseCollection) MapWithKeys() {
panic("not implement")
}
func (c BaseCollection) Median() {
panic("not implement")
}
func (c BaseCollection) Merge() {
panic("not implement")
}
func (c BaseCollection) Nth() {
panic("not implement")
}
func (c BaseCollection) Pad() {
panic("not implement")
}
func (c BaseCollection) Partition() {
panic("not implement")
}
func (c BaseCollection) Pipe() {
panic("not implement")
}
func (c BaseCollection) Pop() {
panic("not implement")
}
func (c BaseCollection) Push() {
panic("not implement")
}
func (c BaseCollection) Random() {
panic("not implement")
}
func (c BaseCollection) Reduce() {
panic("not implement")
}
func (c BaseCollection) Reject() {
panic("not implement")
}
func (c BaseCollection) Reverse() {
panic("not implement")
}
func (c BaseCollection) Search() {
panic("not implement")
}
func (c BaseCollection) Shift() {
panic("not implement")
}
func (c BaseCollection) Shuffle() {
panic("not implement")
}
func (c BaseCollection) Slice() {
panic("not implement")
}
func (c BaseCollection) Some() {
panic("not implement")
}
func (c BaseCollection) Sort() {
panic("not implement")
}
func (c BaseCollection) SortByDesc() {
panic("not implement")
}
func (c BaseCollection) SortKeys() {
panic("not implement")
}
func (c BaseCollection) SortKeysDesc() {
panic("not implement")
}
func (c BaseCollection) Split() {
panic("not implement")
}
func (c BaseCollection) Splice(index ...int) Collection {
panic("not implement")
}
func (c BaseCollection) Tap() {
panic("not implement")
}
func (c BaseCollection) Times() {
panic("not implement")
}
func (c BaseCollection) Transform() {
panic("not implement")
}
func (c BaseCollection) Union() {
panic("not implement")
}
func (c BaseCollection) Unique() {
panic("not implement")
}
func (c BaseCollection) UniqueStrict() {
panic("not implement")
}
func (c BaseCollection) Unless() {
panic("not implement")
}
func (c BaseCollection) UnlessEmpty() {
panic("not implement")
}
func (c BaseCollection) UnlessNotEmpty() {
panic("not implement")
}
func (c BaseCollection) Unwrap() {
panic("not implement")
}
func (c BaseCollection) Values() {
panic("not implement")
}
func (c BaseCollection) When() {
panic("not implement")
}
func (c BaseCollection) WhenEmpty() {
panic("not implement")
}
func (c BaseCollection) WhenNotEmpty() {
panic("not implement")
}
func (c BaseCollection) WhereStrict() {
panic("not implement")
}
func (c BaseCollection) WhereBetween() {
panic("not implement")
}
func (c BaseCollection) WhereIn() {
panic("not implement")
}
func (c BaseCollection) WhereInStrict() {
panic("not implement")
}
func (c BaseCollection) WhereInstanceOf() {
panic("not implement")
}
func (c BaseCollection) WhereNotBetween() {
panic("not implement")
}
func (c BaseCollection) WhereNotIn() {
panic("not implement")
}
func (c BaseCollection) WhereNotInStrict() {
panic("not implement")
}
func (c BaseCollection) Wrap() {
panic("not implement")
}
func (c BaseCollection) Zip() {
panic("not implement")
}
func (c BaseCollection) ToJson() string {
panic("not implement")
}
func (c BaseCollection) ToNumberArray() []decimal.Decimal {
panic("not implement")
}
func (c BaseCollection) ToStringArray() []string {
panic("not implement")
}
func (c BaseCollection) ToMap() map[string]interface{} {
panic("not implement")
}
func (c BaseCollection) ToMapArray() []map[string]interface{} {
panic("not implement")
}
func (c BaseCollection) Where(key string, value interface{}) Collection {
panic("not implement")
}
func (c BaseCollection) Count() int {
return c.length
}
|
/*
** description("get the name and line number of the calling file hook").
** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net").
** time(2021/3/16 11:26).
*/
package log
import (
"fmt"
"github.com/sirupsen/logrus"
"runtime"
"strings"
)
type fileHook struct{}
func newFileHook() *fileHook {
return &fileHook{}
}
func (f *fileHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (f *fileHook) Fire(entry *logrus.Entry) error {
entry.Data["FilePath"] = findCaller(5)
return nil
}
func findCaller(skip int) string {
file := ""
line := 0
for i := 0; i < 10; i++ {
file, line = getCaller(skip + i)
if !strings.HasPrefix(file, "log") {
break
}
}
return fmt.Sprintf("%s:%d", file, line)
}
func getCaller(skip int) (string, int) {
_, file, line, ok := runtime.Caller(skip)
if !ok {
return "", 0
}
n := 0
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
n++
if n >= 2 {
file = file[i+1:]
break
}
}
}
return file, line
}
|
package main
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/GoAdminGroup/go-admin/modules/utils"
)
func getThemeTemplate(moduleName, themeName string) {
downloadTo("http://file.go-admin.cn/go_admin/template/template.zip", "tmp.zip")
checkError(unzipDir("tmp.zip", "."))
checkError(os.Rename("./QiAtztVk83CwCh", "./"+themeName))
replaceContents("./"+themeName, moduleName, themeName)
checkError(os.Rename("./"+themeName+"/template.go", "./"+themeName+"/"+themeName+".go"))
fmt.Println()
fmt.Println("generate theme template success!!🍺🍺")
fmt.Println()
}
func downloadTo(url, output string) {
defer func() {
_ = os.Remove(output)
}()
req, err := http.NewRequest("GET", url, nil)
checkError(err)
res, err := http.DefaultClient.Do(req)
checkError(err)
defer func() {
_ = res.Body.Close()
}()
file, err := os.Create(output)
checkError(err)
_, err = io.Copy(file, res.Body)
checkError(err)
}
func unzipDir(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer func() {
if err := r.Close(); err != nil {
panic(err)
}
}()
checkError(os.MkdirAll(dest, 0750))
// Closure to address file descriptors issue with all the deferred .Close() methods
extractAndWriteFile := func(f *zip.File) error {
rc, err := f.Open()
if err != nil {
return err
}
defer func() {
if err := rc.Close(); err != nil {
panic(err)
}
}()
path := filepath.Join(dest, f.Name)
if f.FileInfo().IsDir() {
checkError(os.MkdirAll(path, f.Mode()))
} else {
checkError(os.MkdirAll(filepath.Dir(path), f.Mode()))
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer func() {
if err := f.Close(); err != nil {
panic(err)
}
}()
_, err = io.Copy(f, rc)
if err != nil {
return err
}
}
return nil
}
for _, f := range r.File {
err := extractAndWriteFile(f)
if err != nil {
return err
}
}
return nil
}
func replaceContents(fileDir, moduleName, themeName string) {
files, err := ioutil.ReadDir(fileDir)
checkError(err)
for _, file := range files {
path := fileDir + "/" + file.Name()
if !file.IsDir() {
buf, err := ioutil.ReadFile(path)
checkError(err)
content := string(buf)
newContent := utils.ReplaceAll(content, "github.com/GoAdminGroup/themes/adminlte", moduleName,
"adminlte", themeName, "Adminlte", strings.Title(themeName))
checkError(ioutil.WriteFile(path, []byte(newContent), 0))
}
}
}
|
package sol
import "testing"
func TestBasic(t *testing.T) {
t.Log(longestCommonSubsequence("ezupkr", "ubmrapg"))
}
|
package ds
import (
"reflect"
"testing"
)
func TestTreeNode_Find(t *testing.T) {
type fields struct {
Val int
Left *TreeNode
Right *TreeNode
}
type args struct {
val int
}
tests := []struct {
name string
fields fields
args args
want bool
}{
{
"Find a node",
fields{5, NewTreeNode(3, NewTreeNode(1, nil, nil), nil), NewTreeNode(8, nil, nil)},
args{8},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
treenode := &TreeNode{
Val: tt.fields.Val,
Left: tt.fields.Left,
Right: tt.fields.Right,
}
if got := treenode.Find(tt.args.val); got != tt.want {
t.Errorf("TreeNode.Find() = %v, want %v", got, tt.want)
}
})
}
}
func TestTreeNode_InOrder(t *testing.T) {
type fields struct {
Val int
Left *TreeNode
Right *TreeNode
}
tests := []struct {
name string
fields fields
want []int
}{
{
"Inorder traverse",
fields{5, NewTreeNode(3, NewTreeNode(1, nil, nil), nil), NewTreeNode(8, nil, nil)},
[]int{1, 3, 5, 8},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
treenode := &TreeNode{
Val: tt.fields.Val,
Left: tt.fields.Left,
Right: tt.fields.Right,
}
if got := treenode.InOrder(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("TreeNode.InOrder() = %v, want %v", got, tt.want)
}
})
}
}
|
package models
type User struct {
Id int
Username string `orm:"size(100)"`
Password string `orm:"size(200)"`
Img string `orm:"size(200)"`
IsAdmin int `orm:"size(1)"`
CreateTime int64 `orm:"size(20)"`
}
|
package main
import (
"encoding/hex"
"log"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-gl/glfw/v3.2/glfw"
)
var (
messageRate = 25 * time.Millisecond
power = float32(0.3) // steering values will by multiplied by this
stopSteering = false
// All data without checksum. Will be calculated before sending
steeringDummyData, _ = hex.DecodeString("ff080000000090101000")
stopData, _ = hex.DecodeString("ff087e3f403f901010a0")
controlsOnData, _ = hex.DecodeString("ff08003f403f10101000")
hoverOnData, _ = hex.DecodeString("ff087e3f403f90101000")
rotorOnData, _ = hex.DecodeString("ff087e3f403f90101040")
flyUpStartData, _ = hex.DecodeString("ff08903b403f90101040")
flyUpHighData, _ = hex.DecodeString("ff08c43b403f90101000")
)
func main() {
// Initialize glfw (need for joystick input)
err := glfw.Init()
if err != nil {
panic(err)
}
defer glfw.Terminate()
// Create connection
conn, err := net.Dial("udp", "172.16.10.1:8080")
if err != nil {
panic(err)
}
// Send Idle data
log.Println("Sending prepare data")
sendMessageDuration(controlsOnData, conn, 2*time.Second)
sendMessageDuration(hoverOnData, conn, 2*time.Second)
sendMessageDuration(rotorOnData, conn, 2*time.Second)
// Catch SIGTERM
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
// Send Stop data
stopSteering = true
sendStopData(conn)
log.Println("Exiting")
os.Exit(1)
}()
for !stopSteering {
// Send joystick command
sendSteeringCommand(conn)
time.Sleep(messageRate)
}
sendStopData(conn)
}
func sendStopData(conn net.Conn) {
log.Println("Sending stop data")
sendMessageDuration(stopData, conn, 500*time.Millisecond)
}
func sendSteeringCommand(conn net.Conn) {
if glfw.GetJoystickButtons(glfw.Joystick1)[0] == 1 {
stopSteering = true
sendStopData(conn)
return
}
axes := glfw.GetJoystickAxes(glfw.Joystick1)
log.Println("Axes: ", axes)
// Fit -1 to 1 range of joystick into 0 to 255 range of drone
steeringDummyData[2] = uint8((-axes[1] + 1) * 127.5)
steeringDummyData[3] = uint8(((axes[0] + 1) * 127.5) / 2)
steeringDummyData[4] = uint8(((axes[3] + 1) * 127.5) / 2)
steeringDummyData[5] = uint8(((axes[2] + 1) * 127.5) / 2)
sendMessage(steeringDummyData, conn)
}
func sendMessageDuration(message []byte, conn net.Conn, duration time.Duration) {
ticker := time.NewTicker(messageRate)
defer ticker.Stop()
done := make(chan bool)
go func() {
time.Sleep(duration)
done <- true
}()
for {
select {
case <-done:
// ticker ended
return
case <-ticker.C:
sendMessage(message, conn)
}
}
}
func sendMessage(message []byte, conn net.Conn) {
// Add checksum to byte slice (JJRC chose a simple algorithm: substract all bytes from each other)
_, err := conn.Write(append(message, message[0]-message[1]-message[2]-message[3]-message[4]-message[5]-message[6]-message[7]-message[8]-message[9]))
if err != nil {
log.Println("Error while sending data: ", err)
}
}
|
package leetcode
import "testing"
func TestLJJS(t *testing.T) {
lj := make([][]bool, 8)
for i := 0; i < 8; i++ {
lj[i] = make([]bool, 8)
}
lj[1][2] = true
lj[1][6] = true
lj[2][4] = true
lj[3][0] = true
lj[3][2] = true
lj[3][5] = true
lj[4][2] = true
lj[5][3] = true
lj[5][4] = true
lj[5][6] = true
lj[6][1] = true
lj[6][5] = true
t.Log(ljjs(lj))
}
|
package cache
import (
"testing"
eventpkg "github.com/serverless/event-gateway/event"
"github.com/serverless/event-gateway/function"
"github.com/serverless/event-gateway/libkv"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
)
func TestSubscriptionCacheModified(t *testing.T) {
t.Run("async added", func(t *testing.T) {
scache := newSubscriptionCache(zap.NewNop())
scache.Modified("testsub1", []byte(`{
"subscriptionId":"testsub1",
"space": "space1",
"type": "async",
"eventType": "test.event",
"functionId": "testfunc1",
"method": "GET",
"path": "/"}`))
scache.Modified("testsub2", []byte(`{
"subscriptionId":
"testsub2",
"space": "space1",
"type": "async",
"eventType": "test.event",
"functionId": "testfunc2",
"method": "GET",
"path": "/"}`))
expected := []libkv.FunctionKey{
libkv.FunctionKey{Space: "space1", ID: "testfunc1"},
libkv.FunctionKey{Space: "space1", ID: "testfunc2"},
}
assert.Equal(t, expected, scache.async["GET"]["/"]["test.event"])
})
t.Run("sync added", func(t *testing.T) {
scache := newSubscriptionCache(zap.NewNop())
scache.Modified("testsub1", []byte(`{
"subscriptionId":"testsub1",
"type":"sync",
"space": "default",
"eventType": "http.request",
"functionId": "testfunc1",
"path": "/a",
"method": "GET"}`))
scache.Modified("testsub2", []byte(`{
"subscriptionId":"testsub2",
"type":"sync",
"space": "default",
"eventType": "http.request",
"functionId": "testfunc2",
"path": "/b",
"method": "GET"}`))
value, _ := scache.sync["GET"][eventpkg.TypeHTTPRequest].Resolve("/a")
key := value.(libkv.FunctionKey)
assert.Equal(t, function.ID("testfunc1"), key.ID)
assert.Equal(t, "default", key.Space)
})
t.Run("wrong payload", func(t *testing.T) {
scache := newSubscriptionCache(zap.NewNop())
scache.Modified("testsub", []byte(`not json`))
assert.Equal(t, []libkv.FunctionKey(nil), scache.async["POST"]["/"]["test.event"])
})
t.Run("async deleted", func(t *testing.T) {
scache := newSubscriptionCache(zap.NewNop())
scache.Modified("testsub1", []byte(`{
"subscriptionId":"testsub1",
"space": "space1",
"type": "async",
"eventType": "test.event",
"functionId": "testfunc1",
"method": "POST",
"path": "/"}`))
scache.Modified("testsub2", []byte(`{
"subscriptionId":"testsub2",
"space": "space1",
"type": "async",
"eventType": "test.event",
"functionId": "testfunc2",
"method": "POST",
"path": "/"}`))
scache.Deleted("testsub1", []byte(`{
"subscriptionId":"testsub1",
"space": "space1",
"type": "async",
"eventType": "test.event",
"functionId": "testfunc1",
"method": "POST",
"path": "/"}`))
assert.Equal(t, []libkv.FunctionKey{{Space: "space1", ID: function.ID("testfunc2")}}, scache.async["POST"]["/"]["test.event"])
})
t.Run("sync deleted", func(t *testing.T) {
scache := newSubscriptionCache(zap.NewNop())
scache.Modified("testsub1", []byte(`{
"subscriptionId":"testsub1",
"type": "sync",
"eventType": "http.request",
"functionId": "testfunc1",
"path": "/",
"method": "GET"}`))
scache.Deleted("testsub1", []byte(`{
"subscriptionId":"testsub1",
"type": "sync",
"eventType": "http.request",
"functionId": "testfunc1",
"path": "/",
"method": "GET"}`))
value, _ := scache.sync["GET"][eventpkg.TypeHTTPRequest].Resolve("/")
assert.Nil(t, value)
})
t.Run("async deleted last", func(t *testing.T) {
scache := newSubscriptionCache(zap.NewNop())
scache.Modified("testsub", []byte(`{
"subscriptionId":"testsub",
"space": "space1",
"type": "async",
"eventType": "test.event",
"functionId": "testfunc",
"method": "POST",
"path": "/"}`))
scache.Deleted("testsub", []byte(`{
"subscriptionId":"testsub",
"space": "space1",
"type": "async",
"eventType": "test.event",
"functionId": "testfunc",
"method": "POST",
"path": "/"}`))
assert.Equal(t, []libkv.FunctionKey(nil), scache.async["POST"]["/"]["test.event"])
})
}
|
package rest
import (
"fmt"
"github.com/jinmukeji/jiujiantang-services/pkg/rest"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
"github.com/kataras/iris/v12"
)
// SetSigninPhoneBody 设置登录电话的body
type SetSigninPhoneBody struct {
Phone string `json:"phone"` // 手机号
NationCode string `json:"nation_code"` // 区号
Mvc string `json:"mvc"` // 验证码
SerialNumber string `json:"serial_number"` // 序列号
SmsNotificationType SmsNotificationType `json:"verification_type"` // 短信类型
}
// VerifySigninPhoneBody 验证登录手机号的body
type VerifySigninPhoneBody struct {
SetSigninPhoneBody
}
// VerifyUserSigninPhoneResp 验证登录电话的返回
type VerifyUserSigninPhoneResp struct {
VerificationNumber string `json:"verification_number"` // 验证号
UserID int32 `json:"user_id"` // 用户ID
}
// ModifySigninPhoneBody 修改登录手机号
type ModifySigninPhoneBody struct {
SetSigninPhoneBody
VerificationNumber string `json:"verification_number"` // 验证号
OldNationCode string `json:"old_nation_code"` // 旧手机区号
OldPhone string `json:"old_phone"` // 旧手机号
}
// SetSigninPhone 设置登录手机
func (h *webHandler) SetSigninPhone(ctx iris.Context) {
var body SetSigninPhoneBody
errReadJSON := ctx.ReadJSON(&body)
if errReadJSON != nil {
writeError(ctx, wrapError(ErrParsingRequestFailed, "", errReadJSON), false)
return
}
if !checkNationCode(body.NationCode) {
writeError(ctx, wrapError(ErrNationCode, "", fmt.Errorf("nation code %s is wrong", body.NationCode)), false)
return
}
userID, err := ctx.Params().GetInt("user_id")
if err != nil {
writeError(ctx, wrapError(ErrInvalidValue, "", err), false)
return
}
req := new(proto.UserSetSigninPhoneRequest)
req.Phone = body.Phone
req.NationCode = body.NationCode
req.Mvc = body.Mvc
req.SerialNumber = body.SerialNumber
req.UserId = int32(userID)
_, errUserSetSigninPhone := h.rpcSvc.UserSetSigninPhone(newRPCContext(ctx), req)
if errUserSetSigninPhone != nil {
writeRpcInternalError(ctx, errUserSetSigninPhone, false)
return
}
rest.WriteOkJSON(ctx, nil)
}
// VerifySigninPhone 验证登录手机号
func (h *webHandler) VerifySigninPhone(ctx iris.Context) {
var body VerifySigninPhoneBody
errReadJSON := ctx.ReadJSON(&body)
if errReadJSON != nil {
writeError(ctx, wrapError(ErrParsingRequestFailed, "", errReadJSON), false)
return
}
// 检查区号
if !checkNationCode(body.NationCode) {
writeError(ctx, wrapError(ErrNationCode, "", fmt.Errorf("nation code %s is wrong", body.NationCode)), false)
return
}
// 短信类型不是重置密码和修改手机号
if body.SmsNotificationType != ResetPasswordSmsNotification && body.SmsNotificationType != ModifyPhoneSmsNotification {
writeError(ctx, wrapError(ErrWrongSmsNotificationType, "", fmt.Errorf("wrong sms notification type %s when verify signin phone", body.SmsNotificationType)), false)
return
}
req := new(proto.VerifyUserSigninPhoneRequest)
req.Phone = body.Phone
req.NationCode = body.NationCode
req.Mvc = body.Mvc
req.SerialNumber = body.SerialNumber
action, errmapSmsNotificationTypeToProtoTemplateAction := mapSmsNotificationTypeToProtoTemplateAction(body.SmsNotificationType)
if errmapSmsNotificationTypeToProtoTemplateAction != nil {
writeError(ctx, wrapError(ErrInvalidValue, "", errmapSmsNotificationTypeToProtoTemplateAction), false)
return
}
req.Action = action
resp, errVerifyUserSigninPhone := h.rpcSvc.VerifyUserSigninPhone(newRPCContext(ctx), req)
if errVerifyUserSigninPhone != nil {
writeRpcInternalError(ctx, errVerifyUserSigninPhone, false)
return
}
rest.WriteOkJSON(ctx, VerifyUserSigninPhoneResp{
VerificationNumber: resp.VerificationNumber,
UserID: resp.UserId,
})
}
// ModifySigninPhone 修改登录手机号
func (h *webHandler) ModifySigninPhone(ctx iris.Context) {
var body ModifySigninPhoneBody
errReadJSON := ctx.ReadJSON(&body)
if errReadJSON != nil {
writeError(ctx, wrapError(ErrParsingRequestFailed, "", errReadJSON), false)
return
}
userID, err := ctx.Params().GetInt("user_id")
if err != nil {
writeError(ctx, wrapError(ErrInvalidValue, "", err), false)
return
}
req := new(proto.UserModifyPhoneRequest)
req.UserId = int32(userID)
req.SerialNumber = body.SerialNumber
req.VerificationNumber = body.VerificationNumber
req.Phone = body.Phone
req.OldNationCode = body.OldNationCode
req.NationCode = body.NationCode
req.Mvc = body.Mvc
req.OldPhone = body.OldPhone
_, errUserModifyPhone := h.rpcSvc.UserModifyPhone(newRPCContext(ctx), req)
if errUserModifyPhone != nil {
writeRpcInternalError(ctx, errUserModifyPhone, false)
return
}
rest.WriteOkJSON(ctx, nil)
}
|
package filter
import (
"log"
"opentsp.org/internal/tsdb"
)
type series struct {
series tsdb.Series
filter *Filter
}
func (s series) Next() *tsdb.Point {
for {
point := s.series.Next()
pass, err := s.filter.Eval(point)
if err != nil {
log.Printf("tsdb: filter error: %v", err)
point.Free()
continue
}
if !pass {
point.Free()
continue
}
return point
}
}
// Series returns a filtered version of the given time series.
func Series(rules []Rule, in tsdb.Series) tsdb.Series {
filter, err := New(rules...)
if err != nil {
log.Printf("tsdb: error creating filter: %v", err)
return emptySeries{}
}
return series{in, filter}
}
type emptySeries struct{}
func (_ emptySeries) Next() *tsdb.Point { select {} }
|
package store
import (
"errors"
"fmt"
"log"
"net"
"os"
"path/filepath"
"sync"
"time"
"github.com/hashicorp/raft"
raftboltdb "github.com/hashicorp/raft-boltdb"
)
var (
ErrNotLeader = errors.New("This node does not leader")
ErrLockAlreadyAcquired = errors.New("The lock had already acquired")
ErrLockNotFound = errors.New("there are no lock for specified id")
)
type Store struct {
m sync.Map
snapshotCount int // as counter
timeout time.Time
RaftDir string
RaftBind string
r *raft.Raft
lgr *log.Logger
}
func NewStore() *Store {
return &Store{
m: sync.Map{},
lgr: log.New(os.Stderr, "[raftlock] ", log.LstdFlags),
}
}
func (s *Store) Open(isLeader bool, localID string, maxPool, retainSnapshotCount int, timeout time.Duration) error {
s.lgr.Printf("Opening ...")
cfg := raft.DefaultConfig()
cfg.LocalID = raft.ServerID(localID)
addr, err := net.ResolveTCPAddr("tcp", s.RaftBind)
if err != nil {
return err
}
transport, err := raft.NewTCPTransport(s.RaftBind, addr, maxPool, timeout, os.Stderr)
if err != nil {
return err
}
snapshots, err := raft.NewFileSnapshotStore(s.RaftDir, retainSnapshotCount, os.Stderr)
if err != nil {
return err
}
path := filepath.Join(s.RaftDir, "raft.db")
boltDB, err := raftboltdb.NewBoltStore(path)
if err != nil {
return err
}
var (
logStore raft.LogStore = boltDB
stableStore raft.StableStore = boltDB
)
raftSystem, err := raft.NewRaft(cfg, (*fsm)(s), logStore, stableStore, snapshots, transport)
if err != nil {
return err
}
s.r = raftSystem
s.lgr.Printf("isLeader=%v\n", isLeader)
if isLeader {
s.lgr.Printf("bootstrap cluster ...\n")
raftSystem.BootstrapCluster(raft.Configuration{
Servers: []raft.Server{
{
ID: cfg.LocalID,
Address: transport.LocalAddr(),
},
},
})
}
return nil
}
func (s *Store) Join(nodeID, addr string) error {
isDuplicateIDOrAddr := func(server raft.Server) bool {
var (
isDupID = server.ID == raft.ServerID(nodeID)
isDupAddr = server.Address == raft.ServerAddress(addr)
)
return isDupID || isDupAddr
}
isMember := func(server raft.Server) bool {
var (
isDupID = server.ID == raft.ServerID(nodeID)
isDupAddr = server.Address == raft.ServerAddress(addr)
)
return isDupID && isDupAddr
}
cfg := s.r.GetConfiguration()
if err := cfg.Error(); err != nil {
return err
}
servers := cfg.Configuration().Servers
for _, server := range servers {
if isDuplicateIDOrAddr(server) {
if isMember(server) {
return nil
}
result := s.r.RemoveServer(server.ID, 0, 0)
if err := result.Error(); err != nil {
return err
}
}
}
s.lgr.Printf("add voter nodeID=%s, serverAddr=%s\n", nodeID, addr)
indexFuture := s.r.AddVoter(raft.ServerID(nodeID), raft.ServerAddress(addr), 0, 0)
if indexFuture.Error() != nil {
return fmt.Errorf("Failed to AddVoter(%s, %s): %s", nodeID, addr, indexFuture.Error().Error())
}
s.lgr.Printf("node %s at %s joined successfully", nodeID, addr)
return nil
}
func (s *Store) Nodes() ([]raft.Server, error) {
cfg := s.r.GetConfiguration()
if err := cfg.Error(); err != nil {
return nil, err
}
return cfg.Configuration().Servers, nil
}
func (s *Store) Stats() map[string]string {
return s.r.Stats()
}
func (s *Store) Acquire(id string) (string, error) {
if s.r.State() != raft.Leader {
return "", ErrNotLeader
}
if _, ok := s.m.Load(id); ok {
return "", ErrLockAlreadyAcquired
}
s.m.Store(id, id)
return id, nil
}
func (s *Store) Release(id string) error {
if s.r.State() != raft.Leader {
return ErrNotLeader
}
if _, ok := s.m.Load(id); !ok {
return ErrLockNotFound
}
s.m.Delete(id)
return nil
}
|
// Copyright (c) 2020 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package micheline
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
)
type BigMapValue struct {
Type *Prim
Value *Prim
}
func NewBigMapValue() *BigMapValue {
return &BigMapValue{
Type: &Prim{},
Value: &Prim{},
}
}
func (e BigMapValue) MarshalJSON() ([]byte, error) {
if e.Type == nil || e.Value == nil {
return nil, nil
}
// output scalar types as is unless packed
if e.Type.IsScalar() && !e.Value.IsPacked() {
return json.Marshal(e.Value.Value(e.Type.OpCode))
}
m := make(map[string]interface{}, 1024)
if err := walkTree(m, "", e.Type, e.Value); err != nil {
tbuf, _ := e.Type.MarshalJSON()
vbuf, _ := e.Value.MarshalJSON()
log.Errorf("RENDER ERROR\ntyp=%s\nval=%s\nerr=%v", string(tbuf), string(vbuf), err)
return nil, err
}
// lift up embedded scalars
if len(m) == 1 {
for n, v := range m {
if strings.HasPrefix(n, "__") {
return json.Marshal(v)
}
}
}
return json.Marshal(m)
}
func walkTree(m map[string]interface{}, path string, typ *Prim, val *Prim) error {
// make sure value matches type
if !val.matchOpCode(typ.OpCode) {
tbuf, _ := typ.MarshalJSON()
vbuf, _ := val.MarshalJSON()
return fmt.Errorf("micheline: type mismatch val_type=%s[%s] type_code=%s / type=%s -- value=%s / map=%#v",
val.Type, val.OpCode, typ.OpCode, string(tbuf), string(vbuf), m)
}
// use annot as name when exists
haveName := typ.HasVarAnno()
if haveName {
path = typ.GetVarAnno()
} else if len(path) == 0 && typ.OpCode != T_OR {
path = strconv.Itoa(len(m)) + "@" + typ.OpCode.String()
}
// walk the type tree and add values if they exist
switch typ.OpCode {
case T_LIST, T_SET:
// list <type>
// set <comparable type>
arr := make([]interface{}, 0, len(val.Args))
for _, v := range val.Args {
if v.IsScalar() {
arr = append(arr, v.Value(typ.Args[0].OpCode))
} else {
mm := make(map[string]interface{})
if err := walkTree(mm, "", typ.Args[0], v); err != nil {
return err
}
arr = append(arr, mm)
}
}
m[path] = arr
case T_LAMBDA:
// LAMBDA <type> <type> { <instruction> ... }
// value_type, return_type, code
m[path] = val
case T_MAP, T_BIG_MAP:
// map <comparable type> <type>
// big_map <comparable type> <type>
// sequence of Elt (key/value) pairs
if typ.OpCode == T_BIG_MAP && len(val.Args) == 0 {
switch val.Type {
case PrimInt:
// Babylon bigmaps contain a reference here
m[path] = val.Value(T_INT)
case PrimSequence:
// pre-babylon there's only an empty sequence
m[path] = nil
}
return nil
}
mm := make(map[string]interface{})
switch val.Type {
case PrimBinary: // single ELT
key, err := NewBigMapKey(typ.Args[0].OpCode, val.Args[0].Int, val.Args[0].String, val.Args[0].Bytes, val.Args[0])
if err != nil {
return err
}
if val.Args[1].IsScalar() {
if err := walkTree(mm, key.String(), typ.Args[1], val.Args[1]); err != nil {
return err
}
} else {
mmm := make(map[string]interface{})
if err := walkTree(mmm, "", typ.Args[1], val.Args[1]); err != nil {
return err
}
mm[key.String()] = mmm
}
case PrimSequence: // sequence of ELTs
for _, v := range val.Args {
if v.OpCode != D_ELT {
return fmt.Errorf("micheline: unexpected type %s [%s] for %s Elt item", v.Type, v.OpCode, typ.OpCode)
}
// build type info if prim was packed
keyType := typ.Args[0]
if v.Args[0].WasPacked {
keyType = v.Args[0].BuildType()
}
// unpack key type
key, err := NewBigMapKey(keyType.OpCode, v.Args[0].Int, v.Args[0].String, v.Args[0].Bytes, v.Args[0])
if err != nil {
return err
}
// build type info if prim was packed
valType := typ.Args[1]
if v.Args[1].WasPacked {
valType = v.Args[1].BuildType()
}
// recurse to unpack value type
if v.Args[1].IsScalar() {
if err := walkTree(mm, key.String(), valType, v.Args[1]); err != nil {
return err
}
} else {
mmm := make(map[string]interface{})
if err := walkTree(mmm, "", valType, v.Args[1]); err != nil {
return err
}
mm[key.String()] = mmm
}
}
default:
buf, _ := json.Marshal(val)
return fmt.Errorf("micheline: unexpected type %s [%s] for %s Elt sequence: %s",
val.Type, val.OpCode, typ.OpCode, buf)
}
m[path] = mm
case T_PAIR:
// pair <type> <type>
if !haveName {
// when annots are empty, collapse values
for i, v := range val.Args {
t := typ.Args[i]
if err := walkTree(m, "", t, v); err != nil {
return err
}
}
} else {
// when annots are NOT empty, create a new sub-map unless value is scalar
mm := make(map[string]interface{})
for i, v := range val.Args {
t := typ.Args[i]
if err := walkTree(mm, "", t, v); err != nil {
return err
}
}
// lift scalar
var lifted bool
if len(mm) == 1 {
for n, v := range mm {
if strings.HasPrefix(n, "__") {
lifted = true
m[path] = v
}
}
}
if !lifted {
m[path] = mm
}
}
case T_OPTION:
// option <type>
switch val.OpCode {
case D_NONE:
// omit empty unnamed values
if haveName {
m[path] = nil // stop recursion
}
case D_SOME:
// continue recursion
if !haveName {
// when annots are empty, collapse values
for i, v := range val.Args {
p := path
if _, ok := m[path]; ok {
p += "_" + strconv.Itoa(i)
}
t := typ.Args[i]
if err := walkTree(m, p, t, v); err != nil {
return err
}
}
} else {
// with annots (name) use it for scalar or complex render
if val.IsScalar() {
for i, v := range val.Args {
t := typ.Args[i]
if err := walkTree(m, path, t, v); err != nil {
return err
}
}
} else {
mm := make(map[string]interface{})
for i, v := range val.Args {
t := typ.Args[i]
if err := walkTree(mm, "", t, v); err != nil {
return err
}
}
m[path] = mm
}
}
case D_PAIR:
// unpack options from pair
if val.Args[0].OpCode == D_SOME {
return walkTree(m, path, typ, val.Args[0])
}
if val.Args[1].OpCode == D_SOME {
return walkTree(m, path, typ, val.Args[1])
}
// empty pair, stop recursion
m[path] = nil
default:
return fmt.Errorf("micheline: unexpected T_OPTION code %s [%s]", val.OpCode, val.OpCode)
}
case T_OR:
// or <type> <type>
switch val.OpCode {
case D_LEFT:
if err := walkTree(m, path, typ.Args[0], val.Args[0]); err != nil {
return err
}
case D_RIGHT:
if err := walkTree(m, path, typ.Args[1], val.Args[0]); err != nil {
return err
}
default:
if err := walkTree(m, path, typ.Args[0], val); err != nil {
return err
}
}
default:
// int
// nat
// string
// bytes
// mutez
// bool
// key_hash
// timestamp
// address
// key
// unit
// signature
// operation
// contract <type> (??)
// chain_id
// append scalar or other complex value
if val.IsScalar() {
m[path] = val.Value(typ.OpCode)
} else {
mm := make(map[string]interface{})
if err := walkTree(mm, "", typ, val); err != nil {
return err
}
m[path] = mm
}
}
return nil
}
func (e BigMapValue) DumpString() string {
buf := bytes.NewBuffer(nil)
e.Dump(buf)
return string(buf.Bytes())
}
func (e BigMapValue) Dump(w io.Writer) {
dumpTree(w, "", e.Type, e.Value)
}
func dumpTree(w io.Writer, path string, typ *Prim, val *Prim) {
if s, err := dump(path, typ, val); err != nil {
io.WriteString(w, err.Error())
} else {
io.WriteString(w, s)
}
switch val.Type {
case PrimSequence:
// keep the type
for i, v := range val.Args {
p := path + "." + strconv.Itoa(i)
dumpTree(w, p, typ, v)
}
default:
// advance type as well
for i, v := range val.Args {
t := typ.Args[i]
p := path + "." + strconv.Itoa(i)
dumpTree(w, p, t, v)
}
}
}
func dump(path string, typ *Prim, val *Prim) (string, error) {
// value type must must match defined type
if !val.matchOpCode(typ.OpCode) {
return "", fmt.Errorf("Type mismatch val_type=%s type_code=%s", val.Type, typ.OpCode)
}
var ann string
if len(typ.Anno) > 0 {
ann = typ.Anno[0][1:]
}
vtyp := "-"
switch val.Type {
case PrimSequence, PrimBytes, PrimInt, PrimString:
default:
vtyp = val.OpCode.String()
}
return fmt.Sprintf("path=%-20s val_prim=%-8s val_type=%-8s val_val=%-10s type_prim=%-8s type_code=%-8s type_name=%-8s\n",
path, val.Type, vtyp, val.Text(), typ.Type, typ.OpCode, ann,
), nil
}
func (p Prim) matchOpCode(oc OpCode) bool {
mismatch := false
switch p.Type {
case PrimSequence:
switch oc {
case T_LIST, T_MAP, T_BIG_MAP, T_SET, T_LAMBDA, T_OR, T_OPTION:
default:
mismatch = true
}
case PrimInt:
switch oc {
case T_INT, T_NAT, T_MUTEZ, T_TIMESTAMP, T_BIG_MAP, T_OR, T_OPTION:
// accept references to bigmap
default:
mismatch = true
}
case PrimString:
// sometimes timestamps and addresses can be strings
switch oc {
case T_STRING, T_ADDRESS, T_CONTRACT, T_KEY_HASH, T_KEY,
T_SIGNATURE, T_TIMESTAMP, T_OR, T_CHAIN_ID, T_OPTION:
default:
mismatch = true
}
case PrimBytes:
switch oc {
case T_BYTES, T_BOOL, T_ADDRESS, T_KEY_HASH, T_KEY,
T_CONTRACT, T_SIGNATURE, T_OPERATION, T_LAMBDA, T_OR,
T_CHAIN_ID, T_OPTION:
default:
mismatch = true
}
default:
switch p.OpCode {
case D_PAIR:
mismatch = oc != T_PAIR && oc != T_OR && oc != T_LIST && oc != T_OPTION
case D_SOME, D_NONE:
mismatch = oc != T_OPTION
case D_UNIT:
mismatch = oc != T_UNIT && oc != K_PARAMETER
case D_LEFT, D_RIGHT:
mismatch = oc != T_OR
}
}
return !mismatch
}
|
package main
import (
"context"
"fmt"
"os"
"github.com/antihax/optional"
"github.com/outscale/osc-sdk-go/osc"
)
func main() {
client := osc.NewAPIClient(osc.NewConfiguration())
auth := context.WithValue(context.Background(), osc.ContextAWSv4, osc.AWSv4{
AccessKey: os.Getenv("OSC_ACCESS_KEY"),
SecretKey: os.Getenv("OSC_SECRET_KEY"),
})
read, httpRes, err := client.SecurityGroupApi.ReadSecurityGroups(auth, nil)
if err != nil {
fmt.Fprintln(os.Stderr, "Error while reading security groups")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println("We currently have", len(read.SecurityGroups), "security groups:")
for _, sg := range read.SecurityGroups {
fmt.Printf("- (%s) %s\n", sg.SecurityGroupId, sg.SecurityGroupName)
}
println("Creating new security group")
creationOpts := osc.CreateSecurityGroupOpts{
CreateSecurityGroupRequest: optional.NewInterface(
osc.CreateSecurityGroupRequest{
SecurityGroupName: "osc-sdk-go-example",
Description: "osc-sdk-go security group example",
}),
}
creation, httpRes, err := client.SecurityGroupApi.CreateSecurityGroup(auth, &creationOpts)
if err != nil {
fmt.Fprint(os.Stderr, "Error while creating security group ")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
sgID := creation.SecurityGroup.SecurityGroupId
println("Created security group", sgID)
println("Adding new security group rule to allow an IP range to access SSH (TCP port 22)")
ruleAddOpts := osc.CreateSecurityGroupRuleOpts{
CreateSecurityGroupRuleRequest: optional.NewInterface(
osc.CreateSecurityGroupRuleRequest{
SecurityGroupId: sgID,
Flow: "Inbound",
IpRange: "10.0.0.0/24",
IpProtocol: "tcp",
FromPortRange: 22,
ToPortRange: 22,
}),
}
_, httpRes, err = client.SecurityGroupRuleApi.CreateSecurityGroupRule(auth, &ruleAddOpts)
if err != nil {
fmt.Fprint(os.Stderr, "Error while creating security group rule")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println("Security group rule added")
println("Listing security group rules")
readOpts := osc.ReadSecurityGroupsOpts{
ReadSecurityGroupsRequest: optional.NewInterface(
osc.ReadSecurityGroupsRequest{
Filters: osc.FiltersSecurityGroup{
SecurityGroupIds: []string{sgID},
},
}),
}
read, httpRes, err = client.SecurityGroupApi.ReadSecurityGroups(auth, &readOpts)
if err != nil {
fmt.Fprintln(os.Stderr, "Error while reading security groups")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println("Inbound rules:")
for _, rule := range read.SecurityGroups[0].InboundRules {
fmt.Printf("- IP protocol: %s, IP range: %s, ports: %d-%d\n", rule.IpProtocol, rule.IpRanges, rule.FromPortRange, rule.ToPortRange)
}
ruleDelOpts := osc.DeleteSecurityGroupRuleOpts{
DeleteSecurityGroupRuleRequest: optional.NewInterface(
osc.DeleteSecurityGroupRuleRequest{
SecurityGroupId: sgID,
Flow: "Inbound",
IpRange: "10.0.0.0/24",
IpProtocol: "tcp",
FromPortRange: 22,
ToPortRange: 22,
}),
}
_, httpRes, err = client.SecurityGroupRuleApi.DeleteSecurityGroupRule(auth, &ruleDelOpts)
if err != nil {
fmt.Fprint(os.Stderr, "Error while deleting security group rule")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println(("Deleted security rule"))
println("Deleting security group", sgID)
deletionOpts := osc.DeleteSecurityGroupOpts{
DeleteSecurityGroupRequest: optional.NewInterface(
osc.DeleteSecurityGroupRequest{
SecurityGroupId: sgID,
}),
}
_, httpRes, err = client.SecurityGroupApi.DeleteSecurityGroup(auth, &deletionOpts)
if err != nil {
fmt.Fprint(os.Stderr, "Error while deleting security group ")
if httpRes != nil {
fmt.Fprintln(os.Stderr, httpRes.Status)
}
os.Exit(1)
}
println("Deleted volume", sgID)
}
|
package mails
import (
"database/sql"
"fmt"
"log"
"os"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ses"
"github.com/toomore/mailbox/campaign"
)
var svc *ses.SES
var ql chan struct{}
func init() {
svc = ses.New(session.Must(session.NewSession(
&aws.Config{
Region: aws.String("us-east-1"),
Credentials: credentials.NewStaticCredentials(
os.Getenv("mailbox_ses_key"), os.Getenv("mailbox_ses_token"), ""),
},
),
))
}
func baseParams() *ses.SendEmailInput {
return &ses.SendEmailInput{
Destination: &ses.Destination{
ToAddresses: []*string{aws.String("")},
},
Message: &ses.Message{
Body: &ses.Body{
Html: &ses.Content{
Data: aws.String(""),
Charset: aws.String("UTF-8"),
},
},
Subject: &ses.Content{
Data: aws.String(""),
Charset: aws.String("UTF-8"),
},
},
Source: aws.String(os.Getenv("mailbox_ses_sender")),
}
}
// GenParams is to gen email params
func GenParams(to string, message string, subject string) *ses.SendEmailInput {
params := baseParams()
params.Destination.ToAddresses[0] = aws.String(to)
params.Message.Body.Html.Data = aws.String(message)
params.Message.Subject.Data = aws.String(subject)
if os.Getenv("mailbox_ses_replyto") != "" {
params.ReplyToAddresses = []*string{aws.String(os.Getenv("mailbox_ses_replyto"))}
}
return params
}
// Send is to send mail
func Send(params *ses.SendEmailInput) {
for i := 0; i < 5; i++ {
resp, err := svc.SendEmail(params)
if err == nil {
log.Println(*params.Destination.ToAddresses[0], resp)
return
}
log.Println(*params.Destination.ToAddresses[0], err)
}
}
// SendWG is with WaitGroup
func SendWG(params *ses.SendEmailInput, wg *sync.WaitGroup) {
Send(params)
<-ql
wg.Done()
}
// ProcessSend is to start send from rows
func ProcessSend(body []byte, rows *sql.Rows, cid string, replaceLink bool, subject string, dryRun bool, limit int) {
var seed = campaign.GetSeed(cid)
var count int
var wg sync.WaitGroup
ql = make(chan struct{}, limit)
for rows.Next() {
var (
allATags map[string]LinksData
allWashiTags map[string]LinksData
email string
fname string
lname string
msg []byte
no string
subjectbyte []byte
)
rows.Scan(&no, &email, &fname, &lname)
msg = body
if replaceLink {
allATags = FilterATags(&msg, cid)
ReplaceATag(&msg, allATags, cid, seed, no)
allWashiTags = FilterWashiTags(&msg, cid)
ReplaceWashiTag(&msg, allWashiTags, cid, seed, no)
}
ReplaceFname(&msg, fname)
ReplaceLname(&msg, lname)
ReplaceReader(&msg, cid, seed, no)
subjectbyte = []byte(subject)
ReplaceFname(&subjectbyte, fname)
ReplaceLname(&subjectbyte, lname)
if dryRun {
log.Printf("%s\n", msg)
var n int
for _, v := range allATags {
n++
fmt.Printf("%02d => [%s] %s\n", n, v.LinkID, v.URL)
}
for _, v := range allWashiTags {
n++
fmt.Printf("%02d => [W][%s] %s\n", n, v.LinkID, v.URL)
}
fmt.Printf("Subject: %s\n", subjectbyte)
} else {
wg.Add(1)
ql <- struct{}{}
go SendWG(GenParams(
fmt.Sprintf("%s %s <%s>", fname, lname, email),
string(msg),
string(subjectbyte)), &wg)
}
count++
}
wg.Wait()
log.Printf("\n cid: %s, count: %d\n Subject: `%s`\n", cid, count, subject)
}
|
package data_test
import (
"bufio"
"encoding/json"
"io/ioutil"
"log"
"os"
"testing"
data "github.com/bgokden/veri/data"
"github.com/stretchr/testify/assert"
pb "github.com/bgokden/veri/veriservice"
)
func TestData(t *testing.T) {
dir, err := ioutil.TempDir("", "veri-test")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
config1 := &pb.DataConfig{
Name: "data1",
Version: 0,
TargetN: 1000,
}
dt, err := data.NewData(config1, dir)
assert.Nil(t, err)
defer dt.Close()
datum := data.NewDatum([]float32{0.1, 0.2, 0.3}, 3, 0, 1, 0, []byte("a"), []byte("a"), 0)
log.Printf("datum %v\n", datum)
err = dt.Insert(datum, nil)
datum2 := data.NewDatum([]float32{0.2, 0.3, 0.4}, 3, 0, 1, 0, []byte("b"), []byte("b"), 0)
err = dt.Insert(datum2, nil)
datum3 := data.NewDatum([]float32{0.2, 0.3, 0.7}, 3, 0, 1, 0, []byte("c"), []byte("c"), 0)
err = dt.Insert(datum3, nil)
for i := 0; i < 5; i++ {
dt.Process(true)
}
log.Printf("stats %v\n", dt.GetDataInfo())
assert.Nil(t, err)
collector := dt.SearchAnnoy(datum, nil)
for _, e := range collector.List {
log.Printf("label: %v score: %v\n", string(e.Datum.Value.Label), e.Score)
}
config := data.DefaultSearchConfig()
config.ScoreFuncName = "AnnoyCosineSimilarity"
config.HigherIsBetter = true
collector2 := dt.SearchAnnoy(datum, config)
for _, e := range collector2.List {
log.Printf("label: %v score: %v\n", string(e.Datum.Value.Label), e.Score)
}
}
type NewsTitle struct {
Title string
Embedding []float32
}
func load_data_from_json(dt *data.Data, fname string) (*pb.Datum, error) {
var oneDatum *pb.Datum
f, err := os.Open(fname)
if err != nil {
return nil, err
}
index := 0
count := 0
s := bufio.NewScanner(f)
for s.Scan() {
var v NewsTitle
if err := json.Unmarshal(s.Bytes(), &v); err != nil {
return nil, err
}
datum := data.NewDatum(v.Embedding, uint32(len(v.Embedding)), 0, 1, 0, []byte(v.Title), []byte(v.Title), 0)
if oneDatum == nil && index == count {
oneDatum = datum
} else {
dt.Insert(datum, nil)
}
index++
}
if s.Err() != nil {
return nil, s.Err()
}
return oneDatum, nil
}
func TestData2(t *testing.T) {
dir, err := ioutil.TempDir("", "veri-test")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
config2 := &pb.DataConfig{
Name: "data2",
Version: 0,
TargetN: 1000,
}
dt, err := data.NewData(config2, dir)
assert.Nil(t, err)
defer dt.Close()
datum, err := load_data_from_json(dt, "./testdata/news_title_embdeddings.json")
assert.Nil(t, err)
for i := 0; i < 5; i++ {
dt.Process(true)
}
log.Printf("stats %v\n", dt.GetDataInfo().N)
log.Printf("label: %v\n", string(datum.Value.Label))
config := data.DefaultSearchConfig()
config.ScoreFuncName = "AnnoyAngularDistance"
config.HigherIsBetter = true
config.Limit = 10
collector := dt.SearchAnnoy(datum, config)
for _, e := range collector.List {
log.Printf("label: %v score: %v\n", string(e.Datum.Value.Label), e.Score)
}
assert.Equal(t, config.Limit, uint32(len(collector.List)))
assert.Equal(t, []byte("Every outfit Duchess Kate has worn in 2019"), collector.List[1].Datum.Value.Label)
}
func TestDataStreamSearch(t *testing.T) {
dir, err := ioutil.TempDir("", "veri-test")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
config01 := &pb.DataConfig{
Name: "data01",
Version: 0,
TargetN: 1000,
}
dt01, err := data.NewData(config01, dir)
assert.Nil(t, err)
defer dt01.Close()
// Stream Sample doesn't work currently
// datum, err := load_data_from_json(dt01, "./testdata/news_title_embdeddings.json")
// assert.Nil(t, err)
// config02 := &pb.DataConfig{
// Name: "data02",
// Version: 0,
// TargetN: 1000,
// }
// dt02, err := data.NewData(config02, dir)
// assert.Nil(t, err)
// defer dt02.Close()
// _, err = load_data_from_json(dt02, "./testdata/news_title_embdeddings.json")
// assert.Nil(t, err)
// config := data.DefaultSearchConfig()
// config.ScoreFuncName = "AnnoyAngularDistance"
// config.HigherIsBetter = true
// config.Limit = 10
// scoredDatumStream := make(chan *pb.ScoredDatum, 100)
// dt01.AddSource(dt02)
// err = dt01.AggregatedSearch(datum, scoredDatumStream, nil, config)
// assert.Nil(t, err)
// time.Sleep(1 * time.Second)
// close(scoredDatumStream)
// for e := range scoredDatumStream {
// log.Printf("label: %v score: %v\n", string(e.Datum.Value.Label), e.Score)
// }
// rand.Seed(42)
// datumStream := make(chan *pb.Datum, 100)
// err = dt01.StreamSample(datumStream, 0.5)
// assert.Nil(t, err)
// time.Sleep(1 * time.Second)
// close(datumStream)
// log.Printf("Stream Sample\n")
// count := 0
// for e := range datumStream {
// log.Printf("label %v: %v\n", count, string(e.Value.Label))
// count++
// }
// assert.Equal(t, 24, count)
// datumStreamAll := make(chan *pb.Datum, 100)
// err = dt01.StreamAll(datumStreamAll)
// assert.Nil(t, err)
// time.Sleep(1 * time.Second)
// close(datumStreamAll)
// log.Printf("Stream All\n")
// countAll := 0
// for e := range datumStreamAll {
// log.Printf("label %v: %v\n", countAll, string(e.Value.Label))
// countAll++
// }
// assert.Equal(t, 49, countAll)
}
|
package native
import (
"os"
"path"
"sync"
"github.com/baidu/openedge/logger"
"github.com/baidu/openedge/master/engine"
"github.com/baidu/openedge/sdk-go/openedge"
"github.com/orcaman/concurrent-map"
)
const packageConfigPath = "package.yml"
type packageConfig struct {
Entry string `yaml:"entry" json:"entry"`
}
type nativeService struct {
info engine.ServiceInfo
cfgs processConfigs
engine *nativeEngine
instances cmap.ConcurrentMap
wdir string
log logger.Logger
}
func (s *nativeService) Name() string {
return s.info.Name
}
func (s *nativeService) Stats() openedge.ServiceStatus {
return openedge.ServiceStatus{}
}
func (s *nativeService) Stop() {
defer os.RemoveAll(s.cfgs.pwd)
var wg sync.WaitGroup
for _, v := range s.instances.Items() {
wg.Add(1)
go func(i *nativeInstance, wg *sync.WaitGroup) {
defer wg.Done()
i.Close()
}(v.(*nativeInstance), &wg)
}
wg.Wait()
}
func (s *nativeService) start() error {
mounts := make([]engine.MountInfo, 0)
datasetsDir := path.Join("var", "db", "openedge", "datasets")
for _, m := range s.info.Datasets {
v := path.Join(datasetsDir, m.Name, m.Version)
mounts = append(mounts, engine.MountInfo{Volume: v, Target: m.Target, ReadOnly: m.ReadOnly})
}
for _, m := range s.info.Volumes {
mounts = append(mounts, m)
}
for _, m := range mounts {
src := path.Join(s.engine.pwd, m.Volume)
err := os.MkdirAll(src, 0755)
if err != nil {
return err
}
dst := path.Join(s.cfgs.pwd, m.Target)
err = os.MkdirAll(path.Dir(dst), 0755)
if err != nil {
return err
}
err = os.Symlink(src, dst)
if err != nil {
return err
}
}
return s.startInstance()
}
|
package logic
import (
"log"
"path/filepath"
)
// NewFilter creates new filter
func NewFilter(include string, exclude string) Filter {
return &filter{
incl: newIncluder(include),
excl: newExcluder(exclude),
}
}
// Skip filters file specified if necessary
func (f *filter) Skip(file string) bool {
return !f.incl.match(file) || f.excl.match(file)
}
type filter struct {
incl matcher
excl matcher
}
func newExcluder(pattern string) matcher {
return &matching{pattern: pattern, resultIfError: false}
}
func newIncluder(pattern string) matcher {
return &matching{pattern: pattern, resultIfError: true}
}
type matching struct {
pattern string
resultIfError bool
}
// Returns resultIfError in case of empty pattern or pattern parsing error
func (m *matching) match(file string) bool {
result, err := filepath.Match(m.pattern, file)
if err != nil {
log.Printf("%v", err)
result = m.resultIfError
} else if len(m.pattern) == 0 {
result = m.resultIfError
}
return result
}
|
package controllers
import (
"database/sql"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"sesi11/models"
_ "github.com/go-sql-driver/mysql"
)
func Login(w http.ResponseWriter, r *http.Request) {
request := models.LoginRequest{}
response := models.LoginResponse{}
reqbyte, _ := ioutil.ReadAll(r.Body)
if err := json.Unmarshal(reqbyte, &request); err != nil {
fmt.Println("Request gagal")
response.Code = "02"
response.Message = "Request gagal"
}
fmt.Println(request.Username)
fmt.Println(request.Password)
fmt.Println(request.Age)
fmt.Println(request.Gender)
fmt.Println(request.Email)
var regname = request.Username
var regpassword = request.Password
var regage = request.Age
var reggender = request.Gender
var regemail = request.Email
db, err := sql.Open("mysql", "root:asdasdxx@/golang?charset=utf8")
if err != nil {
fmt.Println("Error connect DB =>", err)
return
}
db.Ping()
stmt, err := db.Prepare(`INSERT INTO test2 values(?,?,?,?,?,?,?)`)
if err != nil {
fmt.Println("Error create stmt =>", err)
return
}
if regname == "admin" && regpassword == "admin" {
_, err := stmt.Exec(1, regname, regage, reggender, regemail, regpassword, "admin")
if err != nil {
fmt.Println("Error query execute =>", err)
return
}
return
} else {
_, err := stmt.Exec(rand.Intn(10), regname, regage, reggender, regemail, regpassword, "user")
if err != nil {
fmt.Println("Error query execute =>", err)
return
}
}
if regname != "" && regpassword != "" && regage != 0 && reggender != "" && regemail != "" {
response.Code = "00"
response.Message = "Sukses"
jsonRes, _ := json.Marshal(response)
w.Write(jsonRes)
return
}
response.Code = "01"
response.Message = "Gagal"
jsonRes, _ := json.Marshal(response)
w.Write(jsonRes)
return
}
func Result(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("./views/result.gtpl")
db, err := sql.Open("mysql", "root:asdasdxx@/golang?charset=utf8")
if err != nil {
fmt.Println("Error connect DB =>", err)
return
}
db.Ping()
rows, err := db.Query(`Select name, age, gender, email, password from test2`)
if err != nil {
fmt.Println("Error select data =>", err)
return
}
type data struct {
resname string
resage int
resgender string
resemail string
respassword string
}
for rows.Next() {
var name string
var age int
var gender string
var email string
var password string
rows.Scan(&name, &age, &gender, &email, &password)
fmt.Println(name)
fmt.Println(age)
fmt.Println(gender)
fmt.Println(email)
fmt.Println(password)
view := data{}
view.resname = name
view.resage = age
view.resgender = gender
view.resemail = email
view.respassword = password
if err := t.Execute(w, view); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
}
func ViewLogin(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("./views/login.gtpl")
t.Execute(w, nil)
}
|
package main
import "fmt"
func kthSmallest(root *TreeNode, k int) int {
finder := &kthSmalletFinder{k: k, smallest: nil, n: 0}
finder.Traverse(root)
return finder.smallest.Val
}
type kthSmalletFinder struct {
k int
smallest *TreeNode
n int
}
func (k *kthSmalletFinder) Traverse(t *TreeNode) bool {
if t == nil {
return false
}
found := k.Traverse(t.Left)
if found {
return found
}
found = k.Observe(t)
if found {
return found
}
found = k.Traverse(t.Right)
if found {
return found
}
return false
}
func (k *kthSmalletFinder) Observe(t *TreeNode) bool {
if t == nil {
return false
}
fmt.Println(t.Val, k.n, k.k)
if k.n >= k.k {
return true
} else {
k.smallest = t
k.n++
return k.n >= k.k
}
}
|
package routers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"quickstart/controllers"
)
func init() {
beego.Get("/myrouter",func(ctx *context.Context){
ctx.Output.Body([]byte("hello world myrouter"))
})
beego.Router("/deny",&controllers.RController{})
}
|
/*
Given five points on a straight line such that their pairwise distances are 1,2,4, ..., 14,18,20 (after ordering), find the respective positions of the five points (relative to the furthest point on the left).
*/
package main
import (
"fmt"
"math/rand"
"sort"
)
func main() {
x := solve()
d := sd(x[:])
fmt.Println(x)
fmt.Println(d)
}
/*
https://xianblog.wordpress.com/2011/02/04/le-monde-puzzle-4/
A fairly simple puzzle in this weekend Le Monde magazine: given five points on a line such that their pairwise distances are 1,2,4,…,14,18,20,
find the respective positions of the five points over the line and deduce the missing distances.
Without loss of generality, we can set the first point at 0 and the fifth point at 20.
The three remaining points are in between 1 and 19, but again without loss of generality we can choose the fourth point to be at 18. (Else the second point would be at 2.)
Removing 18 from the above takes about the same time! A solution (modulo permutations) is 0, 13, 14, 18, 20.
The idea is to keep generating random points for the 3 unknown points and calculate the flatten sorted distance matrix until we match the pairwise distance we want.
*/
func solve() [5]int {
x := [5]int{0: 0, 4: 20}
for {
x[1] = 1 + rand.Intn(19)
x[2] = 1 + rand.Intn(19)
x[3] = 1 + rand.Intn(19)
if x[1] == x[2] || x[2] == x[3] || x[1] == x[3] {
continue
}
sort.Ints(x[:])
d := sd(x[:])
if d[0] == 1 && d[1] == 2 && d[2] == 4 && d[7] == 14 {
break
}
}
return x
}
func sd(x []int) []int {
d := []int{}
n := len(x)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
d = append(d, abs(x[i]-x[j]))
}
}
sort.Ints(d)
return d
}
func abs(x int) int {
if x < 0 {
x = -x
}
return x
}
|
package pubsub
import (
"testing"
pb "gx/ipfs/QmWL6MKfes1HuSiRUNzGmwy9YyQDwcZF9V1NaA2keYKhtE/go-libp2p-pubsub/pb"
crypto "gx/ipfs/QmNiJiXwWE3kRhZrC5ej3kSjWHm337pYfhjLGSCDNKJP2s/go-libp2p-crypto"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
)
func TestSigning(t *testing.T) {
privk, _, err := crypto.GenerateKeyPair(crypto.RSA, 2048)
if err != nil {
t.Fatal(err)
}
testSignVerify(t, privk)
privk, _, err = crypto.GenerateKeyPair(crypto.Ed25519, 0)
if err != nil {
t.Fatal(err)
}
testSignVerify(t, privk)
}
func testSignVerify(t *testing.T, privk crypto.PrivKey) {
id, err := peer.IDFromPublicKey(privk.GetPublic())
if err != nil {
t.Fatal(err)
}
m := pb.Message{
Data: []byte("abc"),
TopicIDs: []string{"foo"},
From: []byte(id),
Seqno: []byte("123"),
}
signMessage(id, privk, &m)
err = verifyMessageSignature(&m)
if err != nil {
t.Fatal(err)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.